Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/declarations.rs

59.7 KiB, 1 run

created by r1870400018:62387, 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//! Declarations, includes and fields are read where the reader meets them: a `#show` rule, an `#include` or
2//! a front-matter field that a comment holds or a raw block shows is text and does nothing, and a `#show`
3//! rule inside a body the engine does not scope it to is refused there rather than applied to the whole
4//! document. Driven through the `compile` functions the wasm `DaimondTypst` calls, with the source map
5//! installed as it installs one.
6
7use oxedyne_fe2o3_austenite::compile::{
8 self,
9 DiagnosticKind,
10 Rendered,
11 Report,
12};
13use oxedyne_fe2o3_austenite::fonts;
14use oxedyne_fe2o3_austenite::page::PlacedKind;
15use oxedyne_fe2o3_austenite::vfs;
16
17use oxedyne_fe2o3_core::prelude::*;
18
19use std::collections::HashMap;
20use std::path::{
21 Path,
22 PathBuf,
23};
24use std::sync::{
25 Arc,
26 Mutex,
27 MutexGuard,
28};
29
30// The source map is a process global, so the tests that install one take turns.
31static VFS_TURN: Mutex<()> = Mutex::new(());
32
33fn turn() -> MutexGuard<'static, ()> {
34 VFS_TURN.lock().unwrap_or_else(|p| p.into_inner())
35}
36
37/// Installs `files`, compiles `main` as the wasm surface does, and returns the render and its report,
38/// clearing the map either way.
39fn compile_of(main: &str, files: &[(&str, &str)]) -> Outcome<(Rendered, Report)> {
40 let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new();
41 for (p, b) in files {
42 map.insert(PathBuf::from(p), b.as_bytes().to_vec());
43 }
44 compile_map(main, map)
45}
46
47/// As [`compile_of`], for a source map already built.
48fn compile_map(main: &str, map: HashMap<PathBuf, Vec<u8>>) -> Outcome<(Rendered, Report)> {
49 res!(vfs::install(map));
50 let main = PathBuf::from(main);
51 let fonts = Arc::new(res!(fonts::libertinus()));
52 let run = || -> Outcome<(Rendered, Report)> {
53 let assembled = res!(compile::assemble(&main, || Ok(fonts.clone())));
54 let empty = assembled.blocks.is_empty();
55 let rendered = res!(compile::author_and_run(assembled));
56 let report = Report::new(rendered.out.pages.len(), &rendered.refusals, empty);
57 Ok((rendered, report))
58 };
59 let out = run();
60 res!(vfs::clear());
61 out
62}
63
64/// Every text run set on every page, with the size it is set at.
65fn runs(rendered: &Rendered) -> Vec<(String, f32)> {
66 let mut out = Vec::new();
67 for page in &rendered.out.pages {
68 for placed in &page.frame.placed {
69 if let PlacedKind::Text(t) = &placed.kind {
70 out.push((t.source().to_string(), t.size()));
71 }
72 }
73 }
74 out
75}
76
77/// A `#show heading` rule shown in a raw block, written in a comment or placed in a `#styled-box` body sizes
78/// no heading of the document; the boxed one is refused where it stands, and nothing else is reported.
79#[test]
80fn a_shown_commented_or_boxed_show_rule_sizes_no_heading() -> Outcome<()> {
81 let _turn = turn();
82 let src = "= Visible Heading\n\n```typst\n#show heading: set text(size: 30pt)\n```\n\n\
83 /*\n#show heading: set text(size: 31pt)\n*/\n\n#styled-box[\n#show heading: set text(size: 32pt)\n\
84 Boxed words.\n]\n\nBody words.\n";
85 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
86 let head = runs(&rendered).into_iter().find(|(t, _)| t.contains("Visible"));
87 let size = match head {
88 Some((_, size)) => size,
89 None => return Err(err!("the heading is set: {:?}", runs(&rendered); Test, Missing)),
90 };
91 assert!(size < 29.0, "no rule resized the heading: {}", size);
92 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
93 assert_eq!(names, ["skipped #show heading (inside a body, where it is not applied) (fixed-point)"]);
94 assert_eq!(report.diagnostics[0].kind, DiagnosticKind::Unsupported);
95 Ok(())
96}
97
98/// An `#include` a block comment holds is not followed: the draft chapter sets none of its words, the
99/// comment's closer is not set as prose, and the included chapter beside it still is.
100#[test]
101fn a_commented_include_is_not_followed() -> Outcome<()> {
102 let _turn = turn();
103 let root = "#include \"ch1.typ\"\n/*\n#include \"draft.typ\"\n*/\n";
104 let files = [
105 ("/proj/root.typ", root),
106 ("/proj/ch1.typ", "= Chapter\n\nCHAPTERWORDS are set.\n"),
107 ("/proj/draft.typ", "= Draft\n\nDRAFTWORDS never shown.\n"),
108 ];
109 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
110 let text: String = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
111 assert!(text.contains("CHAPTERWORDS"), "the chapter is set: {}", text);
112 assert!(!text.contains("DRAFTWORDS") && !text.contains("Draft"), "the draft is not: {}", text);
113 assert!(!text.contains("*/"), "the comment's closer is not prose: {}", text);
114 assert!(report.strict_failure(Path::new("/proj/root.typ")).is_none(), "{:?}", report.diagnostics);
115 Ok(())
116}
117
118/// A block comment nests, as Typst nests one: a `#set document`, a `#show` rule and an `#include` in a comment
119/// that holds another are text, the outer comment's closer is not set as prose, and nothing is reported --
120/// where the first `*/` once closed the comment, and the title, the rule and the draft all took effect.
121#[test]
122fn a_nested_comment_holds_its_declarations_and_includes() -> Outcome<()> {
123 let _turn = turn();
124 let root = "/* outer /* inner */\n#set document(title: \"Commented Out\")\n\
125 #show heading: set text(size: 30pt)\n#include \"draft.typ\"\n*/\n#include \"ch1.typ\"\n";
126 let files = [
127 ("/proj/root.typ", root),
128 ("/proj/ch1.typ", "= Chapter\n\nCHAPTERWORDS are set.\n"),
129 ("/proj/draft.typ", "= Draft\n\nDRAFTWORDS never shown.\n"),
130 ];
131 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
132 let set = runs(&rendered);
133 let text = set.iter().map(|(t, _)| t.as_str()).collect::<Vec<_>>().join(" ");
134 assert!(text.contains("CHAPTERWORDS"), "the chapter is set: {}", text);
135 assert!(!text.contains("DRAFTWORDS") && !text.contains("Draft"), "the draft is not: {}", text);
136 assert!(!text.contains("*/"), "the outer closer is not prose: {}", text);
137 assert_eq!(rendered.doc_info.title, None, "the commented title is not written");
138 let size = match set.iter().find(|(t, _)| t.contains("Chapter")) {
139 Some((_, size)) => *size,
140 None => return Err(err!("the heading is set: {}", text; Test, Missing)),
141 };
142 assert!(size < 29.0, "the commented rule sizes no heading: {}", size);
143 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
144 Ok(())
145}
146
147/// A `#set document`'s site names the fields it left unapplied, read from the same arguments the Info
148/// dictionary is read from, comments as trivia: a field commented out asks for nothing, a field whose value
149/// the reader cannot evaluate is named rather than dropped, and a field named twice, which Typst refuses,
150/// applies nothing and says so.
151#[test]
152fn a_set_documents_site_names_the_fields_it_left_unapplied() -> Outcome<()> {
153 let _turn = turn();
154 let cases = [
155 ("#set document(title: \"T\" /* c */, date: auto)\n", Some("T"),
156 vec!["#set document left unapplied: date"]),
157 ("#set document(title: 1 + 1)\n", None, vec!["#set document left unapplied: title"]),
158 ("#set document(title: \"A\", title: \"B\")\n", None,
159 vec!["#set document names title twice, so none of it is applied"]),
160 ("#set document(\n // author: \"Old\", date: auto,\n title: \"T\",\n)\n", Some("T"), vec![]),
161 ];
162 for (set, title, want) in cases {
163 let src = fmt!("{}= H\n\nBody.\n", set);
164 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", &src)]));
165 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
166 let want: Vec<(usize, &str)> = want.into_iter().map(|m| (1, m)).collect();
167 assert_eq!(sites, want, "{:?}", set);
168 assert_eq!(rendered.doc_info.title.as_deref(), title, "{:?}", set);
169 assert_eq!(report.strict_failure(Path::new("/proj/main.typ")).is_some(), !want.is_empty(), "{:?}", set);
170 }
171 Ok(())
172}
173
174/// An `#include` in a callout's body is the body's: the file is the lone file it is, with no contents page,
175/// the callout is read whole and set, its include refused where it stands, and nothing after it is refused
176/// as never closing -- where the include was once followed as the file's own, the callout cut at it, and its
177/// `]` set as prose. A binding the unfollowed file defines is not in scope.
178#[test]
179fn an_include_in_a_body_is_refused_where_it_stands() -> Outcome<()> {
180 let _turn = turn();
181 let src = "= Lone\n\n#styled-box[\nBoxed words.\n#include \"ch1.typ\"\n]\n\nAfter words.\n\n#chapword\n";
182 let files = [
183 ("/proj/main.typ", src),
184 ("/proj/ch1.typ", "#let chapword = [CHAPTERWORDS bound.]\n= Chapter\n\nCHAPTERWORDS are set.\n"),
185 ];
186 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
187 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
188 assert_eq!(rendered.out.pages.len(), 1, "one page, no contents: {}", text);
189 assert!(text.contains("Boxed") && text.contains("After"), "the callout and what follows are set: {}", text);
190 assert!(!text.contains("CHAPTERWORDS") && !text.contains(']'), "{}", text);
191 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
192 assert_eq!(names, ["skipped #include (inside a body, where it is not followed) (unsupported)", "skipped #chapword (unsupported)"]);
193 Ok(())
194}
195
196/// An `#include` in a binding's body is the binding's: a binding never used sets nothing from the file, as
197/// Typst sets nothing, its `]` is not prose, and the binding is not refused as never closing.
198#[test]
199fn an_include_in_an_unused_binding_is_not_followed() -> Outcome<()> {
200 let _turn = turn();
201 let root = "#let later = [\n#include \"draft.typ\"\n]\n#include \"ch1.typ\"\n";
202 let files = [
203 ("/proj/root.typ", root),
204 ("/proj/ch1.typ", "= Chapter\n\nCHAPTERWORDS are set.\n"),
205 ("/proj/draft.typ", "= Draft\n\nDRAFTWORDS never shown.\n"),
206 ];
207 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
208 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
209 assert!(text.contains("CHAPTERWORDS"), "the chapter is set: {}", text);
210 assert!(!text.contains("DRAFTWORDS") && !text.contains("Draft") && !text.contains(']'), "{}", text);
211 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
212 assert_eq!(names, ["skipped #let (fixed-point)"]);
213 Ok(())
214}
215
216/// An `#include` directly in an `#if` include guard's branch is the file's own: a root whose only includes
217/// stand in a guard is a book, and the taken branch's chapter is set while the other is not.
218#[test]
219fn an_include_in_a_guard_branch_is_followed() -> Outcome<()> {
220 let _turn = turn();
221 let root = "#let media = \"ebook\"\n\n= Sources\n\n#if media == \"ebook\" [\n #include \"ebook.typ\"\n] else [\n\
222 #include \"print.typ\"\n]\n";
223 let files = [
224 ("/proj/root.typ", root),
225 ("/proj/ebook.typ", "EBOOKWORDS are set.\n"),
226 ("/proj/print.typ", "PRINTWORDS are not.\n"),
227 ];
228 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
229 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
230 assert!(text.contains("EBOOKWORDS") && !text.contains("PRINTWORDS"), "{}", text);
231 assert!(report.diagnostics.iter().all(|d| !d.message.contains("#include") && !d.message.contains("#if")),
232 "{:?}", report.diagnostics);
233 Ok(())
234}
235
236/// A lone file that shows an `#include` in a raw block is compiled as the lone file it is: no chapter is
237/// looked for, so the absent one is no error, and no contents page is set.
238#[test]
239fn a_shown_include_makes_no_book() -> Outcome<()> {
240 let _turn = turn();
241 let src = "= Lone\n\nHow to include a chapter:\n\n```typst\n#include \"chapter.typ\"\n```\n";
242 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
243 assert_eq!(rendered.out.pages.len(), 1, "one page, no contents");
244 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
245 Ok(())
246}
247
248/// A title-page logo field a comment holds is not read: no logo is looked for, so none is missing.
249#[test]
250fn a_commented_logo_field_asks_for_no_logo() -> Outcome<()> {
251 let _turn = turn();
252 let root = "#show: doc.with(\n title: [Doc],\n // title-top-logo-path: \"assets/old-top.png\",\n)\n\
253 #include \"ch1.typ\"\n";
254 let files = [
255 ("/proj/root.typ", root),
256 ("/proj/ch1.typ", "= Chapter\n\nWords.\n"),
257 ];
258 let (_, report) = res!(compile_of("/proj/root.typ", &files));
259 assert!(report.diagnostics.iter().all(|d| d.kind != DiagnosticKind::MissingFile),
260 "no logo is missing: {:?}", report.diagnostics);
261 Ok(())
262}
263
264/// A `[` in prose is text, as Typst reads one: in a paragraph, a heading or a chapter, it hides none of the
265/// declarations, includes, guards or part pages after it, and nothing is refused for it.
266#[test]
267fn a_bracket_in_prose_hides_nothing_after_it() -> Outcome<()> {
268 let _turn = turn();
269 let root = "#let media = \"ebook\"\n\n= Intervals [0, 1)\n\nThe interval [0, 1) is BRACKETWORDS.\n\n\
270 #set document(title: \"After Bracket\")\n\n#include \"ch1.typ\"\n\n#if media == \"ebook\" [\n #include \"ebook.typ\"\n\
271 ] else [\n #include \"print.typ\"\n]\n\n#part-page[Part Two]\n\n#include \"ch2.typ\"\n";
272 let files = [
273 ("/proj/root.typ", root),
274 ("/proj/ch1.typ", "= Chapter One\n\nThe set [a, b) is open.\n\n#include \"sub.typ\"\n"),
275 ("/proj/sub.typ", "SUBWORDS are set.\n"),
276 ("/proj/ebook.typ", "EBOOKWORDS are set.\n"),
277 ("/proj/print.typ", "PRINTWORDS are not.\n"),
278 ("/proj/ch2.typ", "= Chapter Two\n\nCHAPTWOWORDS are set.\n"),
279 ];
280 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
281 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
282 for want in ["BRACKETWORDS", "SUBWORDS", "EBOOKWORDS", "Part Two", "CHAPTWOWORDS"] {
283 assert!(text.contains(want), "{} is set: {}", want, text);
284 }
285 assert!(!text.contains("PRINTWORDS") && !text.contains("#include"), "{}", text);
286 assert_eq!(rendered.doc_info.title.as_deref(), Some("After Bracket"));
287 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
288 assert_eq!(names, ["skipped #let (fixed-point)"]);
289 Ok(())
290}
291
292/// A comment is where Typst's lexer opens one: a link is one token, so the `/*` and `//` in it open none and
293/// the declaration, the include and the prose after it are read; a quotation mark in prose is a character,
294/// so a `/*` in a quoted phrase opens a comment that holds the declaration after it.
295#[test]
296fn a_comment_opens_where_typst_opens_one() -> Outcome<()> {
297 let _turn = turn();
298 let root = "See https://example.com/x/*y ZQX and https://a.io//b too.\n\n\
299 #set document(title: \"After Url\")\n\n#include \"ch1.typ\"\n\nLASTWORDS set.\n";
300 let files = [
301 ("/proj/root.typ", root),
302 ("/proj/ch1.typ", "= Chapter\n\nCHAPTERWORDS are set.\n"),
303 ];
304 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
305 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
306 assert!(text.contains("ZQX") && text.contains("CHAPTERWORDS") && text.contains("LASTWORDS"), "{}", text);
307 assert_eq!(rendered.doc_info.title.as_deref(), Some("After Url"));
308 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
309
310 let src = "He said \"use /* here\" today.\n\n#set document(title: \"After Quote\")\n\nHIDDENWORDS */ TAILWORDS.\n";
311 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
312 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
313 assert!(text.contains("TAILWORDS") && !text.contains("HIDDENWORDS") && !text.contains("today"), "{}", text);
314 assert_eq!(rendered.doc_info.title, None, "the commented title is not written");
315 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
316 Ok(())
317}
318
319/// A conditional the reader meets sets its taken branch where it stands and nothing else of it -- no branch
320/// it does not take, no `else`, no bracket and no site -- as Typst sets it: in a lone file mid-paragraph,
321/// line-leading, mid-sentence on one line and in a callout, and in a callout of a book root.
322#[test]
323fn a_guard_the_reader_meets_sets_its_taken_branch_alone() -> Outcome<()> {
324 let _turn = turn();
325 let guard = "#if media == \"print\" [\nPRINTWORDS\n] else if media == \"ebook\" [\nEBOOKWORDS set.\n] else [\n\
326 OTHERWORDS\n]";
327 let lone = fmt!("#let media = \"ebook\"\n\nText before.\n{g}\n\n{g}\n\n\
328 Words #if media == \"ebook\" [INLINEWORDS] else [PRINTWORDS] after.\n\n#styled-box[\nBoxed.\n{g}\n]\n\n\
329 TAILWORDS.\n", g = guard);
330 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", &lone)]));
331 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
332 assert_eq!(text.matches("EBOOKWORDS").count(), 3, "{}", text);
333 for want in ["Text before.", "Words", "INLINEWORDS", "after.", "Boxed.", "TAILWORDS"] {
334 assert!(text.contains(want), "{} is set: {}", want, text);
335 }
336 for leak in ["PRINTWORDS", "OTHERWORDS", "#if", "else", "[", "]"] {
337 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
338 }
339 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
340 assert_eq!(names, ["skipped #let (fixed-point)"]);
341
342 let root = fmt!("#let media = \"ebook\"\n\n= Root\n\n#styled-box[\nBoxed.\n{g}\n]\n\n#include \"ch1.typ\"\n", g = guard);
343 let files = [
344 ("/proj/root.typ", root.as_str()),
345 ("/proj/ch1.typ", "= Chapter One\n\nCHAPTERWORDS are set.\n"),
346 ];
347 let (rendered, report) = res!(compile_of("/proj/root.typ", &files));
348 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
349 assert!(text.contains("Boxed.") && text.contains("EBOOKWORDS") && text.contains("CHAPTERWORDS"), "{}", text);
350 for leak in ["PRINTWORDS", "OTHERWORDS", "#if", "else", "]"] {
351 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
352 }
353 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
354 assert_eq!(names, ["skipped #let (fixed-point)"]);
355 Ok(())
356}
357
358/// A loop, and a conditional the reader does not evaluate -- one on a name nothing binds, one taking a code
359/// block, one whose taken branch holds an `#include` -- are refused whole, each at its own line: nothing of
360/// them is set, neither branch, no `else` and no bracket, and the prose around them is.
361#[test]
362fn a_loop_or_an_unread_conditional_is_refused_whole_at_its_line() -> Outcome<()> {
363 let _turn = turn();
364 let src = "#let media = \"ebook\"\n\n= Top\n\n#for i in range(2) [\nFORWORDS\n]\n\n\
365 Words #while false [WHILEWORDS] after.\n\n#if unbound == \"x\" [\nIFWORDS\n] else [\nELSEWORDS\n]\n\n\
366 #if media == \"ebook\" {\n[CODEWORDS]\n}\n\n#styled-box[\nBoxed.\n#if media == \"ebook\" [\n\
367 #include \"ch1.typ\"\n]\n]\n\nTAILWORDS.\n";
368 let files = [
369 ("/proj/main.typ", src),
370 ("/proj/ch1.typ", "CHAPTERWORDS.\n"),
371 ];
372 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
373 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
374 for want in ["Top", "Words", "after.", "Boxed.", "TAILWORDS"] {
375 assert!(text.contains(want), "{} is set: {}", want, text);
376 }
377 for leak in ["FORWORDS", "WHILEWORDS", "IFWORDS", "ELSEWORDS", "CODEWORDS", "CHAPTERWORDS", "#", "else", "]", "}"] {
378 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
379 }
380 let line_of = |needle: &str| src.lines().position(|l| l.contains(needle)).map_or(0, |i| i + 1);
381 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
382 let want: Vec<(usize, &str)> = vec![
383 (1, "skipped #let (fixed-point)"),
384 (line_of("#for"), "#for is a loop the reader does not run, so its body is not set"),
385 (line_of("#while"), "#while is a loop the reader does not run, so its body is not set"),
386 (line_of("#if unbound"), "#if names `unbound`, which nothing binds above it (Typst stops: unknown variable: unbound)"),
387 (line_of("{"), "#if takes a code block the reader does not run, so no branch of it is set"),
388 ];
389 assert_eq!(&sites[..want.len()], &want[..], "{:?}", sites);
390 // The callout's body is read apart, so its site's line is counted from the body (gate note, F1).
391 assert_eq!(sites.len(), want.len() + 1, "{:?}", sites);
392 assert_eq!(sites[want.len()].1,
393 "#if takes a branch holding #include, which the reader does not read there, so no branch of it is set");
394 Ok(())
395}
396
397/// A conditional in a chapter resolves in the bindings and imports in force where it stands, as the include
398/// walk resolves its guards. A guard on the config's `media`, which the chapter imports, in a chapter's callout
399/// and one mid-paragraph set their taken branch alone, as the chapter's include guard does, with no site; a
400/// name only another chapter binds is not in scope, so the guard testing it is refused at its line.
401#[test]
402fn a_chapter_guard_resolves_in_the_book_config_as_the_include_walk_does() -> Outcome<()> {
403 let _turn = turn();
404 let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new();
405 let fonts = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fonts");
406 for f in ["LibertinusSerif-Regular.otf", "LibertinusSerif-Bold.otf", "LibertinusSerif-Italic.otf",
407 "LibertinusSerif-BoldItalic.otf", "LibertinusMono-Regular.otf"]
408 {
409 map.insert(PathBuf::from(fmt!("/b/assets/fonts/libertinus/{}", f)), res!(std::fs::read(fonts.join(f))));
410 }
411 let root = "#show: book.with(\n title: [A Book],\n)\n\n#include \"ch1.typ\"\n#include \"ch2.typ\"\n";
412 let config = "#let format = \"a5\"\n#let media = \"ebook\"\n";
413 let ch1 = "#import \"config.typ\": media\n#let side = \"a\"\n\n= One\n\n#styled-box[\nBoxed.\n\
414 #if media == \"ebook\" [\nEBOOKWORDS set.\n] else [\nPRINTWORDS\n]\n]\n\n\
415 Words #if media == \"print\" [PRINTWORDS] else [INLINEWORDS] after.\n\n\
416 #if media == \"ebook\" [\n #include \"sub.typ\"\n]\n\n#if side == \"a\" [SIDEWORDS]\n\n\
417 #if media == \"print\" [\nPRINTWORDS\n] else if media == \"ebook\" [\nCHAINWORDS\n] else [\nOTHERWORDS\n]\n";
418 let ch2 = "= Two\n\nTWOWORDS #if side == \"a\" [LEAKWORDS] here.\n";
419 for (p, b) in [("/b/book/main.typ", root), ("/b/book/config.typ", config), ("/b/book/ch1.typ", ch1),
420 ("/b/book/ch2.typ", ch2), ("/b/book/sub.typ", "SUBWORDS set.\n")]
421 {
422 map.insert(PathBuf::from(p), b.as_bytes().to_vec());
423 }
424 let (rendered, report) = res!(compile_map("/b/book/main.typ", map));
425 let text = runs(&rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ");
426 for want in ["Boxed.", "EBOOKWORDS", "Words", "INLINEWORDS", "after.", "SUBWORDS", "SIDEWORDS", "CHAINWORDS", "TWOWORDS",
427 "here."]
428 {
429 assert!(text.contains(want), "{} is set: {}", want, text);
430 }
431 for leak in ["PRINTWORDS", "OTHERWORDS", "LEAKWORDS", "#if", "else", "]"] {
432 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
433 }
434 let ifs: Vec<(&str, usize, &str)> = report.diagnostics.iter()
435 .filter(|d| d.message.contains("#if"))
436 .map(|d| (d.file.as_str(), d.line, d.message.as_str()))
437 .collect();
438 assert_eq!(ifs, [("/b/book/ch2.typ", 3,
439 "#if names `side`, which nothing binds above it (Typst stops: unknown variable: side)")]);
440 Ok(())
441}
442
443// Guard scope, by position: a conditional resolves its names in the bindings and imports in force where it
444// stands, as Typst's scope does. Each fixture is one the Typst 0.15.1 oracle was run on.
445
446/// Every text run set on every page, with the spaces taken out, so a kerning split or a line break hides no word.
447fn words(rendered: &Rendered) -> String {
448 runs(rendered).into_iter().flat_map(|(t, _)| t.chars().filter(|c| !c.is_whitespace()).collect::<Vec<_>>()).collect()
449}
450
451/// Does the squashed `text` hold `want`, taken as `words` takes it?
452fn has(text: &str, want: &str) -> bool {
453 text.contains(&want.replace(' ', ""))
454}
455
456/// The source map of a book whose root is `/b/book/main.typ`: `files` beside it, and the Libertinus faces a book
457/// reads from its `assets` directory.
458fn book_map(files: &[(&str, &str)]) -> Outcome<HashMap<PathBuf, Vec<u8>>> {
459 let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new();
460 let fonts = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fonts");
461 for f in ["LibertinusSerif-Regular.otf", "LibertinusSerif-Bold.otf", "LibertinusSerif-Italic.otf",
462 "LibertinusSerif-BoldItalic.otf", "LibertinusMono-Regular.otf"]
463 {
464 map.insert(PathBuf::from(fmt!("/b/assets/fonts/libertinus/{}", f)), res!(std::fs::read(fonts.join(f))));
465 }
466 for (p, b) in files {
467 map.insert(PathBuf::from(fmt!("/b/book/{}", p)), b.as_bytes().to_vec());
468 }
469 Ok(map)
470}
471
472/// The conditionals a compile refused, as `(file, line, column, message)`.
473fn if_sites(report: &Report) -> Vec<(String, usize, usize, String)> {
474 report.diagnostics.iter()
475 .filter(|d| d.message.contains("#if"))
476 .map(|d| (d.file.clone(), d.line, d.col, d.message.clone()))
477 .collect()
478}
479
480/// What a refused conditional says of a name nothing binds above it.
481fn unbound(name: &str) -> String {
482 fmt!("#if names `{n}`, which nothing binds above it (Typst stops: unknown variable: {n})", n = name)
483}
484
485const UNREAD: &str = "#if has a condition the reader does not evaluate, so no branch of it is set";
486
487/// A conditional on a name bound only below it is refused at its line, as Typst stops there with "unknown
488/// variable": a rebinding further down does not reach back to earlier guards, whether the guard stands on a
489/// line of its own or mid-paragraph.
490#[test]
491fn a_conditional_on_a_name_bound_only_below_it_is_refused_at_its_line() -> Outcome<()> {
492 let _turn = turn();
493 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"Intro.
494
495#if draft [DRAFTON] else [DRAFTOFF]
496
497#let draft = true
498"##)]));
499 let text = words(&rendered);
500 assert!(has(&text, "Intro.") && !text.contains("DRAFT"), "{}", text);
501 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 3, 1, unbound("draft"))]);
502
503 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"Alpha #if draft [YES] else [NO] omega.
504
505#let draft = true
506"##)]));
507 let text = words(&rendered);
508 assert!(has(&text, "Alpha") && has(&text, "omega.") && !text.contains("YES") && !text.contains("NO"), "{}", text);
509 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 1, 7, unbound("draft"))]);
510 Ok(())
511}
512
513/// An include guard on a name bound only below it is not followed: its include is dropped with the guard, which
514/// is refused at its line, in a book that imports a config and in a root that has none.
515#[test]
516fn a_walked_guard_on_a_name_bound_only_below_it_is_not_followed() -> Outcome<()> {
517 let _turn = turn();
518 let files = [("main.typ", r##"#import "config.typ": *
519= Book
520
521#if full [
522#include "a.typ"
523]
524
525#let full = true
526"##), ("config.typ", r##"#let format = "a5"
527#let media = "ebook"
528"##), ("a.typ", r##"= Chap A
529
530TEXTA.
531"##)];
532 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
533 let text = words(&rendered);
534 assert!(has(&text, "Book") && !text.contains("Chap A") && !text.contains("TEXTA"), "{}", text);
535 assert_eq!(if_sites(&report), [("/b/book/main.typ".to_string(), 4, 1, unbound("full"))]);
536
537 let files = [("/proj/main.typ", r##"#if draft [
538#include "inc.typ"
539]
540#let draft = true
541Tail.
542"##), ("/proj/inc.typ", r##"INCLUDED
543"##)];
544 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
545 let text = words(&rendered);
546 assert!(has(&text, "Tail.") && !text.contains("INCLUDED"), "{}", text);
547 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 1, 1, unbound("draft"))]);
548 Ok(())
549}
550
551/// A `#let` in a callout's body shadows the file's binding inside the callout and nowhere else: the guard in
552/// the body takes the body's value, and one below the callout takes the file's again.
553#[test]
554fn a_callouts_own_let_shadows_the_files_inside_the_callout_alone() -> Outcome<()> {
555 let _turn = turn();
556 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let styled-box(..args, body) = block(stroke: 0.5pt, inset: 4pt, body)
557#let media = "ebook"
558
559Intro.
560
561#styled-box[
562#let media = "print"
563#if media == "ebook" [BOXEBOOK] else [BOXPRINT]
564]
565
566Tail #if media == "ebook" [AFTEREB] else [AFTERPR] end.
567"##)]));
568 let text = words(&rendered);
569 for want in ["Intro.", "BOXPRINT", "AFTEREB"] {
570 assert!(has(&text, want), "{} is set: {}", want, text);
571 }
572 assert!(!text.contains("BOXEBOOK") && !text.contains("AFTERPR"), "{}", text);
573 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
574 Ok(())
575}
576
577/// A callout's own `#let` shadows the config a chapter imports, in a book: the guard in the callout takes the
578/// callout's value, not the config's.
579#[test]
580fn a_book_callouts_let_shadows_the_config_import() -> Outcome<()> {
581 let _turn = turn();
582 let files = [("main.typ", r##"#import "config.typ": *
583= Book
584
585#include "ch.typ"
586"##), ("config.typ", r##"#let format = "a5"
587#let media = "ebook"
588"##), ("ch.typ", r##"#import "config.typ": *
589#let styled-box(..args, body) = block(stroke: 0.5pt, inset: 4pt, body)
590
591= Chapter
592
593Lead.
594
595#styled-box[
596#let media = "print"
597Callout #if media == "ebook" [CALLEBOOK] else [CALLPRINT] end.
598]
599"##)];
600 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
601 let text = words(&rendered);
602 assert!(has(&text, "Lead.") && has(&text, "CALLPRINT") && !text.contains("CALLEBOOK"), "{}", text);
603 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
604 Ok(())
605}
606
607/// A walked include guard's branch is a content block: its own `#let` holds to the branch's closer, so a
608/// guard inside it, before or after the include it holds, takes the branch's value, and a guard after the
609/// branch takes the config's again.
610#[test]
611fn a_walked_branchs_let_scopes_its_guards_to_the_branch() -> Outcome<()> {
612 let _turn = turn();
613 let files = [("main.typ", r##"#import "config.typ": *
614= Book
615
616#if media == "ebook" [
617#let media = "print"
618Walked #if media == "ebook" [INNEREB] else [INNERPR] text.
619#include "ch.typ"
620]
621
622After #if media == "ebook" [AFTEREB] else [AFTERPR] text.
623"##), ("config.typ", r##"#let format = "a5"
624#let media = "ebook"
625"##), ("ch.typ", r##"= Chap
626
627CHAPTEXT.
628"##)];
629 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
630 let text = words(&rendered);
631 for want in ["Walked INNERPR text.", "CHAPTEXT", "After AFTEREB text."] {
632 assert!(has(&text, want), "{} is set: {}", want, text);
633 }
634 assert!(!text.contains("INNEREB") && !text.contains("AFTERPR"), "{}", text);
635 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
636 Ok(())
637}
638
639/// A rebinding holds from its own line down and never reaches back: the guards above `#let media = "print"`
640/// still take the earlier value, so a chapter and a line each follow the branch Typst follows.
641#[test]
642fn a_rebinding_holds_from_its_own_line_down() -> Outcome<()> {
643 let _turn = turn();
644 let files = [("main.typ", r##"#import "config.typ": *
645#let media = "ebook"
646= Book
647
648#if media == "ebook" [
649#include "a.typ"
650]
651
652Mid1 #if media == "ebook" [RB1E] else [RB1P] q.
653
654#let media = "print"
655
656#if media == "print" [
657#include "b.typ"
658]
659
660Mid2 #if media == "ebook" [RB2E] else [RB2P] q.
661"##), ("config.typ", r##"#let format = "a5"
662"##), ("a.typ", r##"= Chap A
663
664TEXTA.
665"##), ("b.typ", r##"= Chap B
666
667TEXTB.
668"##)];
669 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
670 let text = words(&rendered);
671 for want in ["Chap A", "TEXTA.", "Mid1 RB1E q.", "Chap B", "TEXTB.", "Mid2 RB2P q."] {
672 assert!(has(&text, want), "{} is set: {}", want, text);
673 }
674 assert!(!text.contains("RB1P") && !text.contains("RB2E"), "{}", text);
675 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
676 Ok(())
677}
678
679/// A name the config binds twice holds the later value from there down, as Typst's import brings it in: the
680/// guard on it is evaluated, where a name bound to two values was once refused.
681#[test]
682fn a_name_bound_twice_in_the_config_takes_the_later() -> Outcome<()> {
683 let _turn = turn();
684 let files = [("main.typ", r##"#import "config.typ": *
685= Book
686
687#if draft [
688#include "a.typ"
689]
690"##), ("config.typ", r##"#let format = "a5"
691#let draft = false
692#let draft = true
693"##), ("a.typ", r##"= Chap A
694
695TEXTA.
696"##)];
697 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
698 let text = words(&rendered);
699 assert!(has(&text, "Chap A") && has(&text, "TEXTA."), "{}", text);
700 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
701 Ok(())
702}
703
704/// A chapter's own `#let` after its `#import` of the config beats the config's binding, for the guard that
705/// takes whole lines and for the one mid-paragraph.
706#[test]
707fn a_chapters_let_after_its_import_wins() -> Outcome<()> {
708 let _turn = turn();
709 let files = [("main.typ", r##"#import "config.typ": *
710= Book
711
712#include "ch.typ"
713"##), ("config.typ", r##"#let format = "a5"
714#let media = "ebook"
715"##), ("ch.typ", r##"#import "config.typ": *
716#let media = "print"
717
718= Chapter
719
720Lead para.
721
722#if media == "ebook" [
723EBOOKBRANCH
724] else [
725PRINTBRANCH
726]
727
728Mid #if media == "ebook" [EBMID] else [PRMID] end.
729"##)];
730 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
731 let text = words(&rendered);
732 assert!(has(&text, "PRINTBRANCH") && has(&text, "Mid PRMID end."), "{}", text);
733 assert!(!text.contains("EBOOKBRANCH") && !text.contains("EBMID"), "{}", text);
734 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
735 Ok(())
736}
737
738/// A chapter that imports a name from a file other than the config gets that file's value, not the config's.
739#[test]
740fn an_import_of_another_file_binds_its_value() -> Outcome<()> {
741 let _turn = turn();
742 let files = [("main.typ", r##"#import "config.typ": *
743= Book
744
745#include "ch.typ"
746"##), ("config.typ", r##"#let format = "a5"
747#let media = "ebook"
748"##), ("other.typ", r##"#let media = "print"
749"##), ("ch.typ", r##"#import "other.typ": media
750
751= Chapter
752
753Lead.
754
755#if media == "ebook" [
756OTHEREB
757] else [
758OTHERPR
759]
760"##)];
761 let (rendered, report) = res!(compile_map("/b/book/main.typ", res!(book_map(&files))));
762 let text = words(&rendered);
763 assert!(has(&text, "OTHERPR") && !text.contains("OTHEREB"), "{}", text);
764 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
765 Ok(())
766}
767
768/// A lone file's guard on a name it imports from a config of its own evaluates: the import is read from the
769/// file's own directory, with no book behind it.
770#[test]
771fn a_lone_file_guard_on_an_imported_name_evaluates() -> Outcome<()> {
772 let _turn = turn();
773 let files = [("/proj/main.typ", r##"#import "config.typ": *
774
775Intro.
776
777#if media == "ebook" [
778LONEEBOOK
779] else [
780LONEPRINT
781]
782
783Mid #if draft [LONEDRAFT] else [LONEFINAL] q.
784"##), ("/proj/config.typ", r##"#let media = "ebook"
785#let draft = true
786"##)];
787 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
788 let text = words(&rendered);
789 assert!(has(&text, "LONEEBOOK") && has(&text, "Mid LONEDRAFT q."), "{}", text);
790 assert!(!text.contains("LONEPRINT") && !text.contains("LONEFINAL"), "{}", text);
791 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
792 Ok(())
793}
794
795/// An `#import` lists the names it brings in, each under its own name or an alias, and a name the import does
796/// not list is not in scope: the guard testing it is refused as unbound.
797#[test]
798fn an_import_brings_in_the_names_it_lists_and_no_other() -> Outcome<()> {
799 let _turn = turn();
800 let files = [("/proj/main.typ", r##"#import "config.typ": media as m, media2
801
802#if m == "ebook" [ALIASEB] else [ALIASPR]
803
804#if media2 == "print" [LISTEDPR] else [LISTEDEB]
805"##), ("/proj/config.typ", r##"#let media = "ebook"
806#let media2 = "print"
807"##)];
808 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
809 let text = words(&rendered);
810 assert!(has(&text, "ALIASEB") && has(&text, "LISTEDPR"), "{}", text);
811 assert!(!text.contains("ALIASPR") && !text.contains("LISTEDEB"), "{}", text);
812 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
813
814 let files = [("/proj/main.typ", r##"#import "config.typ": media2
815
816Before.
817
818#if media == "ebook" [UNLISTEDEB] else [UNLISTEDPR]
819"##), ("/proj/config.typ", r##"#let media = "ebook"
820#let media2 = "print"
821"##)];
822 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
823 let text = words(&rendered);
824 assert!(has(&text, "Before.") && !text.contains("UNLISTED"), "{}", text);
825 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 5, 1, unbound("media"))]);
826 Ok(())
827}
828
829/// A conditional after an `#import` the reader cannot open is refused as unread, not as unbound: the file may
830/// bring any name in, so the name is not known to be missing.
831#[test]
832fn an_import_the_reader_cannot_open_leaves_a_name_unread_not_unbound() -> Outcome<()> {
833 let _turn = turn();
834 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#import "missing.typ": *
835
836Before.
837
838#if media == "x" [UNREADA] else [UNREADB]
839"##)]));
840 let text = words(&rendered);
841 assert!(has(&text, "Before.") && !text.contains("UNREAD"), "{}", text);
842 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 5, 1, UNREAD.to_string())]);
843 Ok(())
844}
845
846/// A content binding's conditionals are read where the binding is written, as Typst evaluates its body there:
847/// a rebinding of the name after the definition does not change the branch a later use sets.
848#[test]
849fn a_content_binding_reads_its_guards_where_it_is_defined() -> Outcome<()> {
850 let _turn = turn();
851 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let m = "a"
852#let c = [#if m == "a" [DEF] else [CALL]]
853#let m = "b"
854
855P
856
857#c
858"##)]));
859 let text = words(&rendered);
860 assert!(has(&text, "DEF") && !text.contains("CALL"), "{}", text);
861 assert!(if_sites(&report).is_empty(), "{:?}", report.diagnostics);
862 Ok(())
863}
864
865/// A string tested bare is refused, as Typst refuses it ("expected boolean, found string"): neither branch is
866/// set, and the site is the conditional's.
867#[test]
868fn a_string_tested_bare_is_refused_as_typst_refuses_it() -> Outcome<()> {
869 let _turn = turn();
870 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let m = "a"
871#if m [BARE] else [NOTBARE]
872"##)]));
873 let text = words(&rendered);
874 assert!(!text.contains("BARE"), "{}", text);
875 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 2, 1, UNREAD.to_string())]);
876 Ok(())
877}
878
879/// Every text run set, joined by spaces.
880fn spaced_words(rendered: &Rendered) -> String {
881 runs(rendered).into_iter().map(|(t, _)| t).collect::<Vec<_>>().join(" ")
882}
883
884/// The size of the first text run holding `needle`.
885fn size_of(rendered: &Rendered, needle: &str) -> Outcome<f32> {
886 match runs(rendered).into_iter().find(|(t, _)| t.contains(needle)) {
887 Some((_, size)) => Ok(size),
888 None => Err(err!("no run holds {:?}: {:?}", needle, runs(rendered); Test, Missing)),
889 }
890}
891
892/// A `#!` line opening the file is a comment to its line's end, as Typst's lexer reads it: the `/*` in it
893/// opens no comment, so the heading and the `#include` after it stand, and the shebang is not set as prose.
894#[test]
895fn a_shebang_line_is_trivia_and_the_include_after_it_is_followed() -> Outcome<()> {
896 let _turn = turn();
897 let root = "#!/usr/bin/env typst /*\n= Root\n\n#include \"ch1.typ\"\n";
898 let files = [
899 ("/proj/main.typ", root),
900 ("/proj/ch1.typ", "= Chapter One\n\nINCLUDEDWORDS are set.\n"),
901 ];
902 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
903 let text = spaced_words(&rendered);
904 assert!(text.contains("Root") && text.contains("INCLUDEDWORDS"), "the heading and the chapter are set: {}", text);
905 assert!(!text.contains("#!") && !text.contains("usr/bin"), "the shebang is not prose: {}", text);
906 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
907 Ok(())
908}
909
910/// A rule in a list item, strong or emphasis ends with it, as Typst's does: it is not lowered for the whole
911/// document and not passed over, but refused where it stands, so the text after the item keeps its size and
912/// the heading its own.
913#[test]
914fn a_rule_in_an_item_strong_or_emphasis_ends_with_it() -> Outcome<()> {
915 let _turn = turn();
916 let cases = [
917 ("item", "= Root\n\n- item\n #set text(size: 20pt)\n\n= Next\n\nTAILWORDS.\n", 4),
918 ("strong", "= Root\n\n*bold\n#set text(size: 20pt)\nstill*\n\n= Next\n\nTAILWORDS.\n", 4),
919 ("emph", "= Root\n\n_emph\n#set text(size: 20pt)\nstill_\n\n= Next\n\nTAILWORDS.\n", 4),
920 ("show", "= Root\n\n- item\n #show heading: set text(size: 40pt)\n\n= Next\n\nTAILWORDS.\n", 4),
921 ];
922 for (name, src, line) in cases {
923 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
924 assert!(res!(size_of(&rendered, "TAILWORDS")) < 15.0, "{}: the tail keeps its size: {:?}", name, runs(&rendered));
925 assert!(res!(size_of(&rendered, "Next")) < 30.0, "{}: the heading keeps its size: {:?}", name, runs(&rendered));
926 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
927 assert_eq!(sites.len(), 1, "{}: one site: {:?}", name, sites);
928 assert_eq!(sites[0].0, line, "{}: at the rule: {:?}", name, sites);
929 assert!(sites[0].1.contains("inside a list item, strong or emphasis"), "{}: {:?}", name, sites);
930 }
931 Ok(())
932}
933
934/// An `#include` in a list item or in emphasis is that body's, not a chapter: gathered with it and refused
935/// where it stands, so the file makes no book, sets no contents page and follows nothing.
936#[test]
937fn an_include_in_an_item_or_emphasis_is_not_a_chapter() -> Outcome<()> {
938 let _turn = turn();
939 let cases = [
940 ("item", "= Root\n\n- item\n #include \"ch1.typ\"\n\nBody.\n", 4),
941 ("emph", "= Root\n\n_emph\n#include \"ch1.typ\"\nstill_\n\nTail.\n", 4),
942 ];
943 for (name, src, line) in cases {
944 let files = [
945 ("/proj/main.typ", src),
946 ("/proj/ch1.typ", "= Chapter One\n\nCHAPTERWORDS are set.\n"),
947 ];
948 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
949 let text = spaced_words(&rendered);
950 assert!(!text.contains("CHAPTERWORDS") && !text.contains("Chapter One"), "{}: not followed: {}", name, text);
951 assert_eq!(rendered.out.pages.len(), 1, "{}: no contents page, no new page: {}", name, text);
952 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
953 assert_eq!(sites, [(line, "skipped #include (inside a body, where it is not followed) (unsupported)")], "{}", name);
954 }
955 Ok(())
956}
957
958/// A line in a guard's branch is read as the file's own only with no list item, heading, strong or emphasis
959/// open around it there: an `#include` indented in an item in the branch is the item's, refused where it
960/// stands, while the file's own include still makes the book.
961#[test]
962fn an_include_in_an_item_in_a_guard_branch_is_not_a_chapter() -> Outcome<()> {
963 let _turn = turn();
964 let root = "#let media = \"ebook\"\n\n= Root\n\n#include \"ch0.typ\"\n\n#if media == \"ebook\" [\n- item\n \
965 #include \"ch1.typ\"\n]\n\nTail.\n";
966 let files = [
967 ("/proj/main.typ", root),
968 ("/proj/ch0.typ", "= Chapter Zero\n\nZEROWORDS are set.\n"),
969 ("/proj/ch1.typ", "= Chapter One\n\nONEWORDS are not.\n"),
970 ];
971 let (rendered, report) = res!(compile_of("/proj/main.typ", &files));
972 let text = spaced_words(&rendered);
973 assert!(text.contains("ZEROWORDS") && text.contains("Tail."), "the file's own include is followed: {}", text);
974 assert!(!text.contains("ONEWORDS"), "the item's is not: {}", text);
975 let names: Vec<&str> = report.diagnostics.iter().map(|d| d.message.as_str()).collect();
976 assert!(names.contains(&"skipped #include (inside a body, where it is not followed) (unsupported)"), "{:?}", names);
977 Ok(())
978}
979
980/// A bare content block `#[ ... ]` is set where it stands, joined into the markup around it: its brackets are
981/// not prose, and a `#set` in it governs the block alone, as Typst's does.
982#[test]
983fn a_bare_content_block_is_set_where_it_stands_and_scopes_its_rule() -> Outcome<()> {
984 let _turn = turn();
985 let src = "= Root\n\n#[\n#set text(size: 20pt)\nBIGWORDS in block.\n]\n\nThen tail words.\n";
986 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
987 let text = spaced_words(&rendered);
988 assert!(!text.contains("#[") && !text.contains(']'), "the block's brackets are not prose: {}", text);
989 assert!(res!(size_of(&rendered, "BIGWORDS")) > 18.0, "the rule governs the block: {:?}", runs(&rendered));
990 assert!(res!(size_of(&rendered, "tail")) < 15.0, "and ends with it: {:?}", runs(&rendered));
991 assert!(report.diagnostics.is_empty(), "{:?}", report.diagnostics);
992 Ok(())
993}
994
995/// A bare content block that opens inside a paragraph joins it in Typst; this reader sets it as the text it is
996/// written as, brackets and all, and reports it at its line rather than leaving the brackets unexplained.
997#[test]
998fn a_bare_content_block_inside_a_paragraph_is_reported() -> Outcome<()> {
999 let _turn = turn();
1000 let src = "= Root\n\nPara words\n#[\nin para\n]\nmore words\n";
1001 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
1002 assert!(spaced_words(&rendered).contains("in para"), "{}", spaced_words(&rendered));
1003 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
1004 assert_eq!(sites, [(4, "#[ stands inside a paragraph, so it is set as text, brackets and all")]);
1005 Ok(())
1006}
1007
1008// Conditionals and loops in every inline context, and a walked guard branch's rules (round 5, root 4a). Each
1009// fixture is one the Typst 0.15.1 oracle was run on (`austenite-r5-r4a-probe/cases`).
1010
1011/// What a compile reported for a loop or a conditional, as `(line, message)`.
1012fn flow_sites(report: &Report) -> Vec<(usize, String)> {
1013 report.diagnostics.iter()
1014 .filter(|d| d.message.starts_with("#if") || d.message.starts_with("#for") || d.message.starts_with("#while"))
1015 .map(|d| (d.line, d.message.clone()))
1016 .collect()
1017}
1018
1019/// A conditional in a table cell, a caption, a footnote, an emphasis and a strong call, mid-cell and alone,
1020/// sets its taken branch where it stands and nothing of the statement, as Typst sets it: none of an `#if`, an
1021/// untaken branch or a bracket reaches a run, and no site is reported.
1022#[test]
1023fn a_conditional_in_a_cell_a_caption_a_note_or_an_emphasis_is_read() -> Outcome<()> {
1024 let _turn = turn();
1025 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let a = true
1026
1027Intro.
1028
1029#table(columns: 2, [c1], [#if a [CELLA] else [CELLNA]])
1030
1031#table(columns: 2, [d1], [x #if a [CELLB] else [CELLNB] y])
1032
1033#figure(rect[r], caption: [Cap #if a [CAPA] else [CAPNA]])
1034
1035Note#footnote[Foot #if a [FOOTA] else [FOOTNA]].
1036
1037#emph[Emph #if a [EMA] else [EMNA]]
1038
1039Para #strong[Bold #if a [BA] else [BNA]] end.
1040
1041#table(columns: 1, [#if true [TRUECELL]])
1042"##)]));
1043 let text = words(&rendered);
1044 for want in ["CELLA", "x CELLB y", "Cap CAPA", "FOOTA", "Emph EMA", "Bold BA end.", "TRUECELL"] {
1045 assert!(has(&text, want), "{} is set: {}", want, text);
1046 }
1047 for leak in ["NA", "#if", "else", "[", "]"] {
1048 assert!(!text.replace("FOOTNOTE", "").contains(leak), "{} is not set: {}", leak, text);
1049 }
1050 assert!(flow_sites(&report).is_empty(), "{:?}", report.diagnostics);
1051 Ok(())
1052}
1053
1054/// A loop in a cell, a caption or a note is refused whole at its line, as is a conditional whose condition the
1055/// reader does not evaluate: its source is set nowhere and the cells round it are. A literal condition is
1056/// evaluated.
1057#[test]
1058fn a_loop_in_a_body_is_refused_at_its_site() -> Outcome<()> {
1059 let _turn = turn();
1060 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"Intro.
1061
1062#table(columns: 2, [c1], [#for x in (1, 2) [CELL#x]])
1063
1064#figure(rect[r], caption: [Cap #for x in (1,) [CAPL#x]])
1065
1066Note#footnote[Foot #while false [W]].
1067
1068#table(columns: 1, [#if true [TRUECELL]])
1069
1070#table(columns: 1, [#if false [FALSECELL] else [ELSECELL]])
1071"##)]));
1072 let text = words(&rendered);
1073 for want in ["Intro.", "c1", "Cap", "Foot", "TRUECELL", "ELSECELL"] {
1074 assert!(has(&text, want), "{} is set: {}", want, text);
1075 }
1076 for leak in ["#for", "#while", "CELL1CELL2", "CAPL", "FALSECELL", "[", "]", "(1,2)"] {
1077 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
1078 }
1079 let loop_ = |k: &str| fmt!("{} is a loop the reader does not run, so its body is not set", k);
1080 assert_eq!(flow_sites(&report), [(3, loop_("#for")), (5, loop_("#for")), (7, loop_("#while"))]);
1081 Ok(())
1082}
1083
1084/// A cell's own `#let` binds from its line to the cell's end, a name bound above the table is the table's,
1085/// and a rebinding after it reaches no earlier cell: each conditional resolves where it stands. The `#let`
1086/// is a binding, which sets nothing.
1087#[test]
1088fn a_cell_resolves_its_conditional_where_it_stands() -> Outcome<()> {
1089 let _turn = turn();
1090 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let a = true
1091
1092#table(columns: 2, [c1], [#let a = false
1093#if a [CELLA] else [CELLNA]])
1094
1095#table(columns: 2, [d1], [#if a [OUTA] else [OUTNA]])
1096
1097Note and #emph[#if a [EA] else [ENA]].
1098
1099#let a = false
1100
1101#table(columns: 1, [#if a [LATA] else [LATNA]])
1102"##)]));
1103 let text = words(&rendered);
1104 for want in ["c1 CELLNA", "d1 OUTA", "EA", "LATNA"] {
1105 assert!(has(&text, want), "{} is set: {}", want, text);
1106 }
1107 for leak in ["#let", "CELLA", "OUTNA", "ENA", "LATA"] {
1108 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
1109 }
1110 assert!(flow_sites(&report).is_empty(), "{:?}", report.diagnostics);
1111 Ok(())
1112}
1113
1114/// A content binding's conditionals are read where the binding is written, used inline in prose as on a line
1115/// of its own, and a function binding's parameter holds the literal it is given: `DEF` though the name is
1116/// rebound before the use, and `YESBR`, `NOBR` for the two arguments.
1117#[test]
1118fn an_expanded_binding_resolves_where_it_was_defined() -> Outcome<()> {
1119 let _turn = turn();
1120 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let a = true
1121#let blk = [#if a [DEF] else [USE]]
1122#let a = false
1123
1124Inline #blk and again.
1125
1126#blk
1127
1128#let note(x) = [Note #if x == "yes" [YESBR] else [NOBR] end]
1129
1130Using #note("yes") and #note("no") inline.
1131
1132#note("yes")
1133
1134#let c = [Bound #if a [BOUNDA] else [BOUNDNA] end]
1135
1136P #c.
1137"##)]));
1138 let text = words(&rendered);
1139 for want in ["Inline DEF and again.", "Using Note YESBR end and Note NOBR end inline.", "P Bound BOUNDNA end."] {
1140 assert!(has(&text, want), "{} is set: {}", want, text);
1141 }
1142 assert_eq!(text.matches("DEF").count(), 2, "{}", text);
1143 assert_eq!(text.matches("YESBR").count(), 2, "{}", text);
1144 for leak in ["USE", "#if", "else", "BOUNDA", "[", "]"] {
1145 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
1146 }
1147 assert!(flow_sites(&report).is_empty(), "{:?}", report.diagnostics);
1148 Ok(())
1149}
1150
1151/// A conditional in a data array's cell, which a table spreads, is read where the array is written.
1152#[test]
1153fn a_conditional_in_a_data_array_cell_is_read() -> Outcome<()> {
1154 let _turn = turn();
1155 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let a = true
1156#let data = ([h1], [#if a [ARRA] else [ARRNA]], [h3], [x #if a [ARRB] y])
1157
1158#table(columns: 2, ..data.flatten())
1159"##)]));
1160 let text = words(&rendered);
1161 assert!(has(&text, "h1 ARRA h3 x ARRB y"), "{}", text);
1162 assert!(!text.contains("ARRNA") && !text.contains("#if"), "{}", text);
1163 assert!(flow_sites(&report).is_empty(), "{:?}", report.diagnostics);
1164 Ok(())
1165}
1166
1167/// A conditional in an equation sets its taken branch, plain words, as upright text after the maths before it,
1168/// as Typst does; one whose branch is markup, and a loop, are refused at the item, never set as source.
1169#[test]
1170fn a_conditional_in_maths_sets_its_plain_branch_as_text() -> Outcome<()> {
1171 let _turn = turn();
1172 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", r##"#let a = true
1173
1174P6 $x #if a [MX] else [MY]$ q.
1175
1176P7 $x #if a [M7 *z*] else [N7]$ q.
1177
1178P8 $x #for k in (1,) [K]$ q.
1179
1180P9 $ y #if a [DISP] else [NDISP] $
1181"##)]));
1182 let text = words(&rendered);
1183 for want in ["P6", "MX", "q.", "DISP"] {
1184 assert!(has(&text, want), "{} is set: {}", want, text);
1185 }
1186 for leak in ["MY", "#if", "#for", "M7", "NDISP", "N7"] {
1187 assert!(!text.contains(leak), "{} is not set: {}", leak, text);
1188 }
1189 let sites = flow_sites(&report);
1190 assert_eq!(sites.len(), 2, "{:?}", sites);
1191 assert_eq!(sites[0], (5, "#if takes a branch of markup the reader does not set in an equation, so no branch of it is set".to_string()));
1192 assert_eq!(sites[1], (7, "#for is a loop the reader does not run, so its body is not set".to_string()));
1193 Ok(())
1194}
1195
1196/// The book whose root `main.typ` holds an include guard whose taken branch is `branch`, the chapter `ch.typ`
1197/// and a config setting `media` to `"ebook"`.
1198fn walked(root: &str) -> Outcome<(Rendered, Report)> {
1199 let files = [("main.typ", root), ("config.typ", "#let format = \"a5\"\n#let media = \"ebook\"\n"),
1200 ("ch.typ", "= Chap\n\nCHAPTEXT.\n")];
1201 compile_map("/b/book/main.typ", res!(book_map(&files)))
1202}
1203
1204/// The number the contents list sets before the heading `title`: the run ahead of the first run that is the
1205/// title alone.
1206fn numbered(rendered: &Rendered, title: &str) -> Option<String> {
1207 let all: Vec<String> = runs(rendered).into_iter().map(|(t, _)| t).collect();
1208 let at = all.iter().position(|t| t == title)?;
1209 at.checked_sub(1).map(|k| all[k].clone())
1210}
1211
1212/// A `#set` in a walked guard's taken branch governs the branch from there, and the file it includes: the
1213/// chapter and a heading after the rule are numbered by its pattern, one before the rule and one after the
1214/// branch by the file's own. Typst: `II. Before` under the file's pattern, `3. Chap` and `4. Inner` under the
1215/// branch's, `e. Deep` under the rule after them, and `VI. After` under the file's again.
1216#[test]
1217fn a_walked_branchs_set_scopes_the_branch_and_its_includes() -> Outcome<()> {
1218 let _turn = turn();
1219 let (rendered, report) = res!(walked(r##"#import "config.typ": *
1220#set heading(numbering: "I.")
1221= Book
1222
1223#if media == "ebook" [
1224= Before
1225
1226#set heading(numbering: "1.")
1227Walked text.
1228#include "ch.typ"
1229= Inner
1230
1231INNERTEXT.
1232#set heading(numbering: "a.")
1233= Deep
1234]
1235
1236= After
1237
1238AFTERTEXT.
1239"##));
1240 let want = [("Book", "I."), ("Before", "II."), ("Chap", "3."), ("Inner", "4."), ("Deep", "e."), ("After", "VI.")];
1241 for (title, number) in want {
1242 assert_eq!(numbered(&rendered, title).as_deref(), Some(number), "{}", title);
1243 }
1244 assert!(flow_sites(&report).is_empty(), "{:?}", report.diagnostics);
1245 Ok(())
1246}
1247
1248/// A walked branch's `#show` rule, which the rule engine applies from the root's top level alone, is refused at
1249/// its line, with the include still followed: nothing of it is dropped without a site.
1250#[test]
1251fn a_walked_branchs_show_rule_is_refused_at_its_line() -> Outcome<()> {
1252 let _turn = turn();
1253 let (rendered, report) = res!(walked(r##"#import "config.typ": *
1254= Book
1255
1256#if media == "ebook" [
1257#show heading: set text(fill: red)
1258Walked text.
1259#include "ch.typ"
1260]
1261
1262= After
1263"##));
1264 let text = words(&rendered);
1265 for want in ["Walked text.", "CHAPTEXT.", "After"] {
1266 assert!(has(&text, want), "{} is set: {}", want, text);
1267 }
1268 let sites: Vec<(usize, &str)> = report.diagnostics.iter().map(|d| (d.line, d.message.as_str())).collect();
1269 assert!(sites.contains(&(5, "skipped #show heading (inside an include guard's branch, where it is not applied) (fixed-point)")),
1270 "{:?}", sites);
1271 Ok(())
1272}
1273
1274/// A `#set` at a file's own top level numbers every heading after it, an included chapter's among them.
1275#[test]
1276fn a_top_level_set_numbers_every_heading() -> Outcome<()> {
1277 let _turn = turn();
1278 let (rendered, _) = res!(walked("#import \"config.typ\": *\n#set heading(numbering: \"1.\")\n= Book\n\n#include \"ch.typ\"\n"));
1279 assert_eq!(numbered(&rendered, "Book").as_deref(), Some("1."));
1280 assert_eq!(numbered(&rendered, "Chap").as_deref(), Some("2."));
1281 Ok(())
1282}
1283
1284/// A bare content block `#[ ... ]` is a scope of its own: a conditional in it, and one after its closing
1285/// bracket on the same line, resolves in the bindings in force where it stands, a `#let` in the block shadows
1286/// the file's inside it alone, and a name nothing binds is refused at its line as Typst stops there (`a1`,
1287/// `a2` of the Typst 0.15.1 oracle run: "Root INBLOCK ELSEIN x TAILSET y TAILEMPH OUTSIDE", and "unknown variable").
1288#[test]
1289fn a_bare_content_block_resolves_its_conditionals_where_it_stands() -> Outcome<()> {
1290 let _turn = turn();
1291 let src = "#let on = true\n= Root\n\n#[\n#if on [INBLOCK]\n]\n\n#[\n#let on = false\n#if on [NOTSHOWN] else [ELSEIN]\n]\n\n#[ x ] #if on [TAILSET]\n\n#[ y ] #emph[#if on [TAILEMPH]]\n\n#if on [OUTSIDE]\n";
1292 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
1293 let text = words(&rendered);
1294 for want in ["INBLOCK", "ELSEIN", "x", "TAILSET", "TAILEMPH", "OUTSIDE"] {
1295 assert!(has(&text, want), "{} is set: {}", want, text);
1296 }
1297 assert!(!text.contains("NOTSHOWN"), "{}", text);
1298 assert_eq!(if_sites(&report), []);
1299
1300 let src = "= Root\n\n#[\n#if nothing [HIDDENBLOCK] else [ELSEBLOCK]\n]\n";
1301 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
1302 let text = words(&rendered);
1303 assert!(!text.contains("HIDDENBLOCK") && !text.contains("ELSEBLOCK"), "{}", text);
1304 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 4, 1, unbound("nothing"))]);
1305 Ok(())
1306}
1307
1308/// A `$` whose maths never closes is a character and the markup after it is read as usual, by the guard scope
1309/// as by every other scan: the callout it stands in closes at its own bracket, so a `#let` in the callout is its
1310/// own and a conditional after it, on that name, is refused as one on a name nothing binds. Read with the
1311/// `$` as maths, the bracket would close nothing and the name would reach past the callout.
1312#[test]
1313fn a_dollar_that_never_closes_leaves_a_callout_its_bracket_for_the_guard_scope() -> Outcome<()> {
1314 let _turn = turn();
1315 let src = "= Root\n\n#styled-box[\nCosts 5$ only.\n#let on = true\n#if on [INBOX] else [NOTSHOWN]\n]\n\n#if on [AFTERBOX]\n";
1316 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src)]));
1317 let text = words(&rendered);
1318 assert!(has(&text, "INBOX") && !text.contains("NOTSHOWN") && !text.contains("AFTERBOX"), "{}", text);
1319 assert_eq!(if_sites(&report), [("/proj/main.typ".to_string(), 9, 1, unbound("on"))]);
1320 let lone: Vec<(usize, usize)> = report.diagnostics.iter()
1321 .filter(|d| d.message.contains("inline maths")).map(|d| (d.line, d.col)).collect();
1322 assert_eq!(lone, [(4, 8)], "{:?}", report.diagnostics);
1323 Ok(())
1324}
1325
1326/// A `#let` or an `#import` written mid-line in prose binds a name and sets nothing, whether or not the
1327/// paragraph holds a conditional: no run holds its source and the paragraph is reported once for it, where
1328/// Typst sets `Bold still here.` (oracle probes `s2_let_mid_para_no_if` and `s1_binding_body_own_let`). A
1329/// binding body's own `#let` is read the same once the block pass has taken the conditional beside it, and a
1330/// conditional that stays in the paragraph still resolves a name the line binds.
1331#[test]
1332fn a_binding_written_mid_line_in_prose_is_not_set() -> Outcome<()> {
1333 let _turn = turn();
1334 let one = |src: &str| -> Outcome<(String, Vec<String>)> {
1335 let (rendered, report) = res!(compile_of("/proj/main.typ", &[("/proj/main.typ", src), ("/proj/x.typ", "#let q = 1\n")]));
1336 let names = report.diagnostics.iter().map(|d| d.message.clone()).collect();
1337 Ok((words(&rendered), names))
1338 };
1339 let one_site = ["skipped #let (fixed-point)".to_string()];
1340
1341 // Alone in a paragraph, and twice in one, in strong and in an item.
1342 let (text, names) = res!(one("Bold #let a = true; still here.\n\nPlain paragraph.\n"));
1343 assert!(has(&text, "Bold still here.Plain paragraph."), "{}", text);
1344 assert!(!text.contains("#let") && !text.contains("true"), "{}", text);
1345 assert_eq!(names, one_site);
1346 let (text, names) = res!(one("A #let a = 1; b #let c = 2; d.\n"));
1347 assert!(has(&text, "A b d."), "{}", text);
1348 assert!(!text.contains("#let") && !text.contains('='), "{}", text);
1349 assert_eq!(names, ["skipped #let (fixed-point)", "skipped #let (fixed-point)"]);
1350 let (text, names) = res!(one("Some *bold #let a = true; inner* text.\n\n- item #let c = 3; tail\n"));
1351 assert!(has(&text, "Some bold inner text.") && has(&text, "item tail"), "{}", text);
1352 assert!(!text.contains("#let") && !text.contains("true"), "{}", text);
1353 assert_eq!(names, ["skipped #let (fixed-point)", "skipped #let (fixed-point)"]);
1354
1355 // An import brings names in and sets nothing either.
1356 let (text, names) = res!(one("Text #import \"x.typ\": q; more here.\n\nNext.\n"));
1357 assert!(has(&text, "Text more here.Next."), "{}", text);
1358 assert!(!text.contains("#import") && !text.contains("x.typ"), "{}", text);
1359 assert_eq!(names, ["skipped #import (fixed-point)".to_string()]);
1360
1361 // With a conditional in the paragraph, which resolves the name the line binds.
1362 let (text, names) = res!(one("Bold #let a = true; and #if a [YES] else [NO] here.\n"));
1363 assert!(has(&text, "Bold and YES here."), "{}", text);
1364 assert!(!text.contains("#let") && !text.contains("NO"), "{}", text);
1365 assert_eq!(names, one_site);
1366
1367 // A binding body's own `#let`, whose conditional the block pass has taken: the block and the inline
1368 // expansion set the same words.
1369 let src = "#let n = [N: #let z = true; #if z [Z] else [NZ].]\n\n#n\n\nPara #n end.\n";
1370 let (text, names) = res!(one(src));
1371 assert!(has(&text, "N: Z.Para N: Z. end."), "{}", text);
1372 assert!(!text.contains("#let") && !text.contains("true") && !text.contains("NZ"), "{}", text);
1373 assert!(!names.is_empty() && names.iter().all(|n| *n == one_site[0]), "{:?}", names);
1374 Ok(())
1375}