Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/content.rs

33.9 KiB, 59 runs

created by r1870400018:63202, 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// U0 owns this file. The `ElemKind` list is closed: an element Typst has and this list lacks is added
2// here (one line in the table below) by agreement, never worked around. Each element's field schema,
3// custom constructor and native show live with the unit that lays it out, reached through `Family`.
4
5use crate::diag::DiagnosticKind;
6use crate::eval::args::Args;
7use crate::eval::fp::{
8 self,
9 Kept,
10 Shared,
11};
12use crate::eval::lib;
13use crate::eval::locate::{
14 Location,
15 Place,
16};
17use crate::eval::styles::{
18 RecipeIndex,
19 StyleChain,
20 Styles,
21};
22use crate::eval::value::{
23 FromValue,
24 Label,
25 Value,
26 Type,
27};
28use crate::eval::Engine;
29use crate::syntax::Span;
30
31use oxedyne_fe2o3_core::prelude::*;
32use oxedyne_fe2o3_hash::fingerprint::Fingerprint;
33use oxedyne_fe2o3_hash::fingerprint::LazyFingerprint;
34
35/// Which unit's files hold an element's schema, constructor and native show.
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
37pub enum Family {
38 Text, // lib/text.rs, U6a
39 Model, // lib/model/, U5
40 Layout, // lib/layout.rs, U6b
41 Grid, // lib/grid.rs, U6c
42 Visual, // lib/visual.rs, U6d
43 Math, // lib/math.rs, U7
44 Intro, // lib/intro.rs, U8
45 Realise, // realise.rs, U4: what realisation itself makes (tags) and the kinds of plain content
46}
47
48macro_rules! elem_kinds {
49 ($($v:ident => ($path:literal, $fam:ident, $loc:literal),)*) => {
50 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
51 pub enum ElemKind {
52 $($v,)*
53 }
54
55 impl ElemKind {
56 pub const ALL: &'static [ElemKind] = &[$(ElemKind::$v,)*];
57
58 /// The dotted path Typst code reaches the element function by: `heading`, `list.item`,
59 /// `math.frac`.
60 pub fn path(self) -> &'static str {
61 match self {
62 $(ElemKind::$v => $path,)*
63 }
64 }
65
66 pub fn family(self) -> Family {
67 match self {
68 $(ElemKind::$v => Family::$fam,)*
69 }
70 }
71
72 /// Does realisation give every instance a location, labelled or not?
73 pub fn locatable(self) -> bool {
74 match self {
75 $(ElemKind::$v => $loc,)*
76 }
77 }
78 }
79 };
80}
81
82impl ElemKind {
83 /// Does the element lay a body of its own out, which may be laid out again and must realise to the same
84 /// locations each time? Such an element is given a [`Place`] when it is realised. The text and maths
85 /// kinds are inline atoms; the model kinds other than the paragraph and the bullet and numbered lists are shown as elements
86 /// that have a place themselves, and `layout` is the one introspection element that lays out a body.
87 pub fn has_place(self) -> bool {
88 match self.family() {
89 Family::Layout | Family::Grid | Family::Visual => true,
90 Family::Model => matches!(self,
91 ElemKind::Par | ElemKind::List | ElemKind::Enum),
92 Family::Intro => self == ElemKind::Layout,
93 Family::Text | Family::Math | Family::Realise => false,
94 }
95 }
96}
97
98elem_kinds! {
99 // Text (U6a)
100 Text => ("text", Text, false),
101 Space => ("space", Text, false),
102 Linebreak => ("linebreak", Text, false),
103 SmartQuote => ("smartquote", Text, false),
104 Smallcaps => ("smallcaps", Text, false),
105 Underline => ("underline", Text, true),
106 Overline => ("overline", Text, true),
107 Strike => ("strike", Text, true),
108 Highlight => ("highlight", Text, true),
109 Super => ("super", Text, false),
110 Sub => ("sub", Text, false),
111 Symbol => ("symbol", Text, false),
112 // Model (U5)
113 Par => ("par", Model, true),
114 ParLine => ("par.line", Model, true),
115 Parbreak => ("parbreak", Model, false),
116 Strong => ("strong", Model, true),
117 Emph => ("emph", Model, true),
118 Raw => ("raw", Model, true),
119 RawLine => ("raw.line", Model, false),
120 Heading => ("heading", Model, true),
121 Title => ("title", Model, true),
122 List => ("list", Model, true),
123 ListItem => ("list.item", Model, false),
124 Enum => ("enum", Model, true),
125 EnumItem => ("enum.item", Model, false),
126 Terms => ("terms", Model, true),
127 TermItem => ("terms.item", Model, false),
128 Link => ("link", Model, true),
129 Ref => ("ref", Model, true),
130 Cite => ("cite", Model, true),
131 Footnote => ("footnote", Model, true),
132 FootnoteEntry => ("footnote.entry", Model, true),
133 Figure => ("figure", Model, true),
134 FigureCaption => ("figure.caption", Model, true),
135 Outline => ("outline", Model, true),
136 OutlineEntry => ("outline.entry", Model, true),
137 Quote => ("quote", Model, true),
138 Bibliography => ("bibliography", Model, true),
139 CiteGroup => ("cite-group", Model, true),
140 Document => ("document", Model, true),
141 Divider => ("divider", Model, false),
142 // Layout (U6b)
143 Box => ("box", Layout, false),
144 Block => ("block", Layout, false),
145 Align => ("align", Layout, false),
146 Pad => ("pad", Layout, false),
147 Stack => ("stack", Layout, false),
148 H => ("h", Layout, false),
149 V => ("v", Layout, false),
150 Place => ("place", Layout, true),
151 PlaceFlush => ("place.flush", Layout, false),
152 Columns => ("columns", Layout, false),
153 Colbreak => ("colbreak", Layout, false),
154 Pagebreak => ("pagebreak", Layout, false),
155 Page => ("page", Layout, false),
156 // Grid and table (U6c)
157 Grid => ("grid", Grid, false),
158 GridCell => ("grid.cell", Grid, false),
159 GridHeader => ("grid.header", Grid, false),
160 GridFooter => ("grid.footer", Grid, false),
161 GridHLine => ("grid.hline", Grid, false),
162 GridVLine => ("grid.vline", Grid, false),
163 Table => ("table", Grid, true),
164 TableCell => ("table.cell", Grid, false),
165 TableHeader => ("table.header", Grid, false),
166 TableFooter => ("table.footer", Grid, false),
167 TableHLine => ("table.hline", Grid, false),
168 TableVLine => ("table.vline", Grid, false),
169 // Visual (U6d)
170 Image => ("image", Visual, true),
171 Line => ("line", Visual, false),
172 Rect => ("rect", Visual, false),
173 Square => ("square", Visual, false),
174 Circle => ("circle", Visual, false),
175 Ellipse => ("ellipse", Visual, false),
176 Polygon => ("polygon", Visual, false),
177 Curve => ("curve", Visual, false),
178 CurveMove => ("curve.move", Visual, false),
179 CurveLine => ("curve.line", Visual, false),
180 CurveQuad => ("curve.quad", Visual, false),
181 CurveCubic => ("curve.cubic", Visual, false),
182 CurveClose => ("curve.close", Visual, false),
183 Path => ("path", Visual, false),
184 Move => ("move", Visual, false),
185 Scale => ("scale", Visual, false),
186 Rotate => ("rotate", Visual, false),
187 Skew => ("skew", Visual, false),
188 Hide => ("hide", Visual, false),
189 Repeat => ("repeat", Visual, false),
190 // Maths (U7)
191 Equation => ("math.equation", Math, true),
192 MathAlignPoint => ("math.align-point", Math, false),
193 MathAttach => ("math.attach", Math, false),
194 MathScripts => ("math.scripts", Math, false),
195 MathLimits => ("math.limits", Math, false),
196 MathPrimes => ("math.primes", Math, false),
197 MathFrac => ("math.frac", Math, false),
198 MathBinom => ("math.binom", Math, false),
199 MathLr => ("math.lr", Math, false),
200 MathMid => ("math.mid", Math, false),
201 MathMat => ("math.mat", Math, false),
202 MathVec => ("math.vec", Math, false),
203 MathCases => ("math.cases", Math, false),
204 MathRoot => ("math.root", Math, false),
205 MathAccent => ("math.accent", Math, false),
206 MathOp => ("math.op", Math, false),
207 MathClass => ("math.class", Math, false),
208 MathCancel => ("math.cancel", Math, false),
209 MathStretch => ("math.stretch", Math, false),
210 MathUnderline => ("math.underline", Math, false),
211 MathOverline => ("math.overline", Math, false),
212 MathUnderbrace => ("math.underbrace", Math, false),
213 MathOverbrace => ("math.overbrace", Math, false),
214 MathUnderbracket => ("math.underbracket", Math, false),
215 MathOverbracket => ("math.overbracket", Math, false),
216 MathUnderparen => ("math.underparen", Math, false),
217 MathOverparen => ("math.overparen", Math, false),
218 MathUndershell => ("math.undershell", Math, false),
219 MathOvershell => ("math.overshell", Math, false),
220 // Introspection (U8)
221 Metadata => ("metadata", Intro, true),
222 CounterUpdate => ("counter.update", Intro, true),
223 StateUpdate => ("state.update", Intro, true),
224 Context => ("context", Intro, true),
225 Layout => ("layout", Intro, true),
226 // Realisation (U4)
227 Sequence => ("sequence", Realise, false),
228 Styled => ("styled", Realise, false),
229 Tag => ("tag", Realise, false),
230}
231
232impl ElemKind {
233 /// The last path segment, what `repr` of the element function prints (`item` for `list.item`).
234 pub fn name(self) -> &'static str {
235 let p = self.path();
236 match p.rfind('.') {
237 Some(i) => &p[i + 1..],
238 None => p,
239 }
240 }
241
242 /// The element reached as a top-level global (`heading`), not through a parent (`list.item`) or the
243 /// `math` module (`math.frac`). Typst binds no global to `space`, to its internal cite groups, tags,
244 /// sequences and styled content, keeps `context` as a keyword, and gives the names `symbol` and `path`
245 /// to types, so those elements are reached only as values.
246 pub fn is_global(self) -> bool {
247 !self.path().contains('.') && !matches!(self,
248 ElemKind::Space | ElemKind::Symbol | ElemKind::Path | ElemKind::Context | ElemKind::CiteGroup
249 | ElemKind::Sequence | ElemKind::Styled | ElemKind::Tag)
250 }
251
252 /// Can a user's `query`, `locate` or selector name the element? Typst locates `place` for the flow's
253 /// float bookkeeping, yet refuses it in a query: "place is not locatable".
254 pub fn queryable(self) -> bool {
255 self.locatable() && !matches!(self, ElemKind::Place)
256 }
257
258 /// The element scoped under this one's function: `ElemKind::List.scoped("item")` is `ListItem`.
259 pub fn scoped(self, name: &str) -> Option<ElemKind> {
260 let parent = self.path();
261 ElemKind::ALL.iter().copied().find(|k| {
262 let p = k.path();
263 p.len() == parent.len() + 1 + name.len()
264 && p.starts_with(parent)
265 && p.as_bytes().get(parent.len()) == Some(&b'.')
266 && p.ends_with(name)
267 })
268 }
269
270 /// The element's field schema, from the owning unit.
271 pub fn fields(self) -> &'static [FieldSpec] {
272 match self.family() {
273 Family::Text => lib::text::fields(self),
274 Family::Model => lib::model::fields(self),
275 Family::Layout => lib::layout::fields(self),
276 Family::Grid => lib::grid::fields(self),
277 Family::Visual => lib::visual::fields(self),
278 Family::Math => lib::math::fields(self),
279 Family::Intro => lib::intro::fields(self),
280 Family::Realise => crate::eval::realise::fields(self),
281 }
282 }
283
284 pub fn field_id(self, name: &str) -> Option<FieldId> {
285 self.fields().iter().position(|f| f.name == name).map(|i| FieldId(i as u8))
286 }
287
288 pub fn field_spec(self, id: FieldId) -> Option<&'static FieldSpec> {
289 self.fields().get(id.0 as usize)
290 }
291}
292
293// Field schema
294
295/// A field's index into its element's schema slice. Stable for a build, never serialised.
296#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
297pub struct FieldId(pub u8);
298
299/// What a field accepts. `Any` defers checking to the owning unit's typed accessor.
300#[derive(Clone, Copy, Debug, PartialEq, Eq)]
301pub enum FieldType {
302 Any,
303 Of(Type),
304 OneOf(&'static [Type]),
305 Content, // content, str, symbol or number, displayed
306 Keyword(&'static [Type], &'static str), // a closed set of strings and Typst's words for it; no symbol cast
307}
308
309impl FieldType {
310 pub fn accepts(self, v: &Value) -> bool {
311 match self {
312 FieldType::Any => true,
313 FieldType::Of(t) => v.ty() == t,
314 FieldType::OneOf(ts) => ts.contains(&v.ty()),
315 FieldType::Content => matches!(v.ty(),
316 Type::Content | Type::Str | Type::Symbol | Type::Int | Type::Float | Type::None),
317 FieldType::Keyword(ts, _) => matches!(v, Value::Str(_)) || ts.contains(&v.ty()),
318 }
319 }
320
321 /// Does the field take the value once Typst's casts are made? A symbol is taken where a string is.
322 pub fn castable(self, v: &Value) -> bool {
323 self.accepts(v) || (matches!(v, Value::Symbol(_)) && self.takes_str())
324 }
325
326 /// The value as the field keeps it: a symbol a string field takes is stored as the string it casts to.
327 pub fn cast(self, v: Value) -> Value {
328 if !self.accepts(&v) && self.castable(&v) { v.symbol_as_str() } else { v }
329 }
330
331 fn takes_str(self) -> bool {
332 match self {
333 FieldType::Of(t) => t == Type::Str,
334 FieldType::OneOf(ts) => ts.contains(&Type::Str),
335 FieldType::Any | FieldType::Content | FieldType::Keyword(..) => false,
336 }
337 }
338}
339
340/// A default a `static` schema can hold. `Computed` means the owning unit resolves it in code (Typst's
341/// heading `numbering` depends on nothing static, `text.lang`'s region on the language, and so on).
342#[derive(Clone, Copy, Debug, PartialEq)]
343pub enum FieldDefault {
344 None,
345 Auto,
346 Bool(bool),
347 Int(i64),
348 Float(f64),
349 Pt(f64),
350 Em(f64),
351 Ratio(f64),
352 Str(&'static str),
353 EmptyContent,
354 EmptyArray,
355 Computed,
356 Required, // no default: construction fails without it
357}
358
359/// How successive `set` values of a field combine along the style chain.
360#[derive(Clone, Copy, Debug, PartialEq, Eq)]
361pub enum Fold {
362 Replace, // innermost wins
363 Add, // accumulates, e.g. `text.size` em-relative
364 Sides, // side by side, each side's stroke part-wise (`inset`, `margin`, `rect.stroke`)
365 Corners, // corner by corner (`radius`)
366 Stroke, // one stroke, part-wise (`line.stroke`)
367 Keyed(&'static str), // a dictionary whose bare-value form is this key (`first-line-indent`'s amount)
368 Custom, // the owning unit folds it in code
369}
370
371#[derive(Clone, Copy, Debug, PartialEq)]
372pub struct FieldSpec {
373 pub name: &'static str,
374 pub ty: FieldType,
375 pub default: FieldDefault,
376 pub fold: Fold,
377 pub positional: bool,
378 pub required: bool,
379 pub variadic: bool, // takes all remaining positional arguments (`list(..children)`)
380 pub settable: bool,
381 pub synthesised: bool, // filled during realisation, never passed (`heading.level` when auto, `counter`)
382 pub internal: bool, // Typst-internal: hidden from `fields()`, field access, `repr`, `set` and construction
383}
384
385impl FieldSpec {
386 /// A settable, named, optional field: the common case.
387 pub const fn named(name: &'static str, ty: FieldType, default: FieldDefault) -> Self {
388 Self { name, ty, default, fold: Fold::Replace, positional: false, required: false,
389 variadic: false, settable: true, synthesised: false, internal: false }
390 }
391
392 /// A required positional field, not settable: a body, a text, a destination.
393 pub const fn required(name: &'static str, ty: FieldType) -> Self {
394 Self { name, ty, default: FieldDefault::Required, fold: Fold::Replace, positional: true,
395 required: true, variadic: false, settable: false, synthesised: false, internal: false }
396 }
397
398 pub const fn fold(mut self, fold: Fold) -> Self { self.fold = fold; self }
399 pub const fn positional(mut self) -> Self { self.positional = true; self }
400 pub const fn variadic(mut self) -> Self { self.variadic = true; self.positional = true; self }
401 pub const fn unsettable(mut self) -> Self { self.settable = false; self }
402 pub const fn synthesised(mut self) -> Self { self.synthesised = true; self.settable = false; self }
403 pub const fn internal(mut self) -> Self { self.internal = true; self.settable = false; self }
404}
405
406impl FieldDefault {
407 /// The default as a value, `None` for one only code can compute or a required field.
408 pub fn to_value(self) -> Option<Value> {
409 use crate::eval::value::{
410 Length,
411 Ratio,
412 };
413 match self {
414 FieldDefault::None => Some(Value::None),
415 FieldDefault::Auto => Some(Value::Auto),
416 FieldDefault::Bool(b) => Some(Value::Bool(b)),
417 FieldDefault::Int(i) => Some(Value::Int(i)),
418 FieldDefault::Float(f) => Some(Value::Float(f)),
419 FieldDefault::Pt(p) => Some(Value::Length(Length::pt(p))),
420 FieldDefault::Em(e) => Some(Value::Length(Length::em(e))),
421 FieldDefault::Ratio(r) => Some(Value::Ratio(Ratio(r))),
422 FieldDefault::Str(s) => Some(Value::str(s)),
423 FieldDefault::EmptyContent => Some(Value::Content(Content::empty())),
424 FieldDefault::EmptyArray => Some(Value::array(Vec::new())),
425 FieldDefault::Computed => None,
426 FieldDefault::Required => None,
427 }
428 }
429}
430
431// Content
432
433/// One element instance. `guards` are the recipes already applied to it, Typst's defence against a
434/// show rule re-matching its own output.
435#[derive(Clone, Debug)]
436pub struct Elem {
437 pub kind: ElemKind,
438 pub fields: Vec<(FieldId, Value)>,
439 pub label: Option<Label>,
440 pub location: Option<Location>,
441 pub span: Span,
442 pub guards: Vec<RecipeIndex>,
443 pub prepared: bool, // synthesised fields filled and location assigned
444 pub place: Option<Place>, // where the body it lays out is realised, given when it is first met
445 fp: LazyFingerprint, // private: only a `Shared` handle's `edit` may change an element
446}
447
448impl Elem {
449 /// An element with the given fields: no label, location, guards or place, and not yet prepared.
450 pub fn new(kind: ElemKind, fields: Vec<(FieldId, Value)>, span: Span) -> Self {
451 Self {
452 kind, fields, label: None, location: None, span, guards: Vec::new(), prepared: false, place: None,
453 fp: LazyFingerprint::new(),
454 }
455 }
456}
457
458impl Kept for Elem {
459 fn cell(&mut self) -> &mut LazyFingerprint { &mut self.fp }
460}
461
462/// Content in order. A labelled sequence is located and guarded as an element is, so show rules on
463/// its label apply once and it can be found by its location.
464#[derive(Clone, Debug)]
465pub struct Sequence {
466 pub children: Vec<Content>,
467 pub label: Option<Label>,
468 pub span: Span,
469 pub location: Option<Location>,
470 pub guards: Vec<RecipeIndex>,
471 fp: LazyFingerprint,
472}
473
474impl Sequence {
475 pub fn new(children: Vec<Content>) -> Self {
476 Self {
477 children, label: None, span: Span::detached(), location: None, guards: Vec::new(),
478 fp: LazyFingerprint::new(),
479 }
480 }
481}
482
483impl Kept for Sequence {
484 fn cell(&mut self) -> &mut LazyFingerprint { &mut self.fp }
485}
486
487#[derive(Clone, Debug)]
488pub struct Styled {
489 pub child: Content,
490 pub styles: Styles,
491 fp: LazyFingerprint,
492}
493
494impl Styled {
495 pub fn new(child: Content, styles: Styles) -> Self { Self { child, styles, fp: LazyFingerprint::new() } }
496}
497
498impl Kept for Styled {
499 fn cell(&mut self) -> &mut LazyFingerprint { &mut self.fp }
500}
501
502/// Typst's `content` value: an element, a sequence of content, or content under local styles.
503#[derive(Clone, Debug)]
504pub enum Content {
505 Elem(Shared<Elem>),
506 Sequence(Shared<Sequence>),
507 Styled(Shared<Styled>),
508}
509
510impl Default for Content {
511 fn default() -> Self { Content::empty() }
512}
513
514impl Content {
515 pub fn empty() -> Self {
516 Content::Sequence(Shared::new(Sequence::new(Vec::new())))
517 }
518
519 pub fn new(kind: ElemKind, fields: Vec<(FieldId, Value)>, span: Span) -> Self {
520 Content::Elem(Shared::new(Elem::new(kind, fields, span)))
521 }
522
523 pub fn from_elem(e: Elem) -> Self { Content::Elem(Shared::new(e)) }
524
525 /// A text element. By contract `text`'s field 0 is its string (`lib/text.rs`).
526 pub fn text(s: &str) -> Self {
527 Content::new(ElemKind::Text, vec![(FieldId(0), Value::str(s))], Span::detached())
528 }
529
530 /// A symbol element, what Typst makes of a symbol value, an escape, a shorthand or one maths
531 /// character. By contract `symbol`'s field 0 is its text (`lib/text.rs`).
532 pub fn symbol(s: &str) -> Self {
533 Content::new(ElemKind::Symbol, vec![(FieldId(0), Value::str(s))], Span::detached())
534 }
535
536 /// An element with no fields set, for markers such as `parbreak()` and `linebreak()`.
537 pub fn marker(kind: ElemKind, span: Span) -> Self { Content::new(kind, Vec::new(), span) }
538
539 pub fn sequence(children: Vec<Content>) -> Self {
540 if children.len() == 1 {
541 if let Some(c) = children.into_iter().next() {
542 return c;
543 }
544 return Content::empty();
545 }
546 Content::Sequence(Shared::new(Sequence::new(children)))
547 }
548
549 pub fn styled(self, styles: Styles) -> Self {
550 if styles.is_empty() {
551 return self;
552 }
553 Content::Styled(Shared::new(Styled::new(self, styles)))
554 }
555
556 pub fn kind(&self) -> Option<ElemKind> {
557 match self {
558 Content::Elem(e) => Some(e.kind),
559 _ => None,
560 }
561 }
562
563 pub fn is(&self, kind: ElemKind) -> bool { self.kind() == Some(kind) }
564
565 pub fn elem(&self) -> Option<&Elem> {
566 match self {
567 Content::Elem(e) => Some(e),
568 _ => None,
569 }
570 }
571
572 pub fn is_empty(&self) -> bool {
573 match self {
574 Content::Sequence(s) => s.children.iter().all(|c| c.is_empty()),
575 Content::Styled(s) => s.child.is_empty(),
576 Content::Elem(_) => false,
577 }
578 }
579
580 pub fn span(&self) -> Span {
581 match self {
582 Content::Elem(e) => e.span,
583 Content::Sequence(s) => s.span,
584 Content::Styled(s) => s.child.span(),
585 }
586 }
587
588 pub fn with_span(mut self, span: Span) -> Self {
589 match &mut self {
590 Content::Elem(e) => e.edit().span = span,
591 Content::Sequence(s) => s.edit().span = span,
592 Content::Styled(_) => (),
593 }
594 self
595 }
596
597 pub fn label(&self) -> Option<&Label> {
598 match self {
599 Content::Elem(e) => e.label.as_ref(),
600 Content::Sequence(s) => s.label.as_ref(),
601 Content::Styled(s) => s.child.label(),
602 }
603 }
604
605 pub fn labelled(mut self, label: Label) -> Self {
606 match &mut self {
607 Content::Elem(e) => e.edit().label = Some(label),
608 Content::Sequence(s) => s.edit().label = Some(label),
609 Content::Styled(s) => {
610 let st = s.edit();
611 st.child = st.child.clone().labelled(label);
612 }
613 }
614 self
615 }
616
617 pub fn location(&self) -> Option<Location> {
618 match self {
619 Content::Elem(e) => e.location,
620 Content::Sequence(s) => s.location,
621 Content::Styled(_) => None,
622 }
623 }
624
625 /// Where the element's body is realised, once the element has been met.
626 pub fn place(&self) -> Option<Place> {
627 match self {
628 Content::Elem(e) => e.place,
629 _ => None,
630 }
631 }
632
633 /// The kind `content.func()` reports: the element's, or `sequence` and `styled` for plain content.
634 pub fn func_kind(&self) -> ElemKind {
635 match self {
636 Content::Elem(e) => e.kind,
637 Content::Sequence(_) => ElemKind::Sequence,
638 Content::Styled(_) => ElemKind::Styled,
639 }
640 }
641
642 /// A field's stored value, `None` when unset (not the default; styles and schema supply that).
643 pub fn get(&self, id: FieldId) -> Option<&Value> {
644 match self {
645 Content::Elem(e) => e.fields.iter().find(|(f, _)| *f == id).map(|(_, v)| v),
646 _ => None,
647 }
648 }
649
650 pub fn get_as<T: FromValue>(&self, id: FieldId) -> Outcome<Option<T>> {
651 match self.get(id) {
652 Some(v) => Ok(Some(res!(T::from_value(v.clone())))),
653 None => Ok(None),
654 }
655 }
656
657 /// A field by name, as `it.body` reads it.
658 pub fn field(&self, name: &str) -> Option<&Value> {
659 match self {
660 Content::Elem(e) => e.kind.field_id(name).and_then(|id| self.get(id)),
661 _ => None,
662 }
663 }
664
665 /// Sets a field in place (copy on write); a no-op on a sequence or styled content.
666 pub fn set(&mut self, id: FieldId, value: Value) {
667 if let Content::Elem(e) = self {
668 let e = e.edit();
669 match e.fields.iter_mut().find(|(f, _)| *f == id) {
670 Some(slot) => slot.1 = value,
671 None => e.fields.push((id, value)),
672 }
673 }
674 }
675
676 /// Gives an element the place its body is realised at (copy on write); a no-op on a sequence or styled
677 /// content. A layouter that resolves its children itself, as a grid does its cells, gives each one.
678 pub fn set_place(&mut self, place: Place) {
679 if let Content::Elem(e) = self {
680 e.edit().place = Some(place);
681 }
682 }
683
684 /// What the content is, span-free: kind, label, fields, guards and styles, but not the span, the
685 /// location or the place. Equal text at a shifted offset has an equal fingerprint.
686 pub fn fingerprint(&self) -> Fingerprint {
687 match self {
688 Content::Elem(e) => e.fp.get_or_init(|| fp::elem_fp(e)),
689 Content::Sequence(s) => s.fp.get_or_init(|| fp::seq_fp(s)),
690 Content::Styled(s) => s.fp.get_or_init(|| fp::styled_fp(s)),
691 }
692 }
693
694 /// What the content is apart from what it holds: an element's kind, label and fields that hold no content,
695 /// a sequence's label, nothing for styled content. It keys the place of a body laid out
696 /// ([`Locator::next`](crate::eval::locate::Locator::next)), so an edit of what the content holds leaves the place.
697 pub fn shell(&self) -> Fingerprint {
698 match self {
699 Content::Elem(e) => fp::elem_shell_fp(e),
700 Content::Sequence(s) => fp::seq_shell_fp(s),
701 Content::Styled(_) => fp::styled_shell_fp(),
702 }
703 }
704
705 /// Direct children of a sequence or styled content; an element's body is a field, not a child.
706 pub fn children(&self) -> &[Content] {
707 match self {
708 Content::Sequence(s) => &s.children,
709 Content::Styled(s) => std::slice::from_ref(&s.child),
710 Content::Elem(_) => &[],
711 }
712 }
713
714 /// The text a reader would see, ignoring styles, as Typst's `plain-text` does for text, spaces and
715 /// breaks. Other elements contribute their `body` or `text` field when they have one.
716 pub fn plain_text(&self) -> String {
717 let mut s = String::new();
718 self.push_plain(&mut s);
719 s
720 }
721
722 fn push_plain(&self, s: &mut String) {
723 match self {
724 Content::Sequence(seq) => for c in &seq.children { c.push_plain(s); },
725 Content::Styled(st) => st.child.push_plain(s),
726 Content::Elem(e) => match e.kind {
727 ElemKind::Text | ElemKind::Symbol => if let Some(Value::Str(t)) = self.get(FieldId(0)) {
728 s.push_str(t);
729 },
730 ElemKind::Space | ElemKind::Linebreak => s.push(' '),
731 // A smart quote reads as the straight quote it was typed as.
732 ElemKind::SmartQuote => s.push(match self.field("double") {
733 Some(Value::Bool(false)) => '\'',
734 _ => '"',
735 }),
736 ElemKind::Parbreak => s.push_str("\n\n"),
737 _ => match self.field("body").or_else(|| self.field("text")) {
738 Some(Value::Content(c)) => c.push_plain(s),
739 Some(Value::Str(t)) => s.push_str(t),
740 _ => (),
741 },
742 },
743 }
744 }
745}
746
747/// Folds a `Fold::Custom` field's inner value onto its outer one, by the family that declared it. A
748/// family declaring a `Custom` field gains an arm here with its fold.
749pub fn fold_custom(kind: ElemKind, field: &str, inner: Value, outer: Value) -> Outcome<Value> {
750 match kind.family() {
751 Family::Visual => lib::visual::fold(kind, field, inner, outer),
752 Family::Text => lib::text::fold(kind, field, inner, outer),
753 Family::Model => lib::model::fold(kind, field, inner, outer),
754 _ => Err(err!(
755 "`{}.{}` is declared `Fold::Custom`, but its family has no fold in `content::fold_custom`",
756 kind.path(), field; Unimplemented)),
757 }
758}
759
760/// Typst's `Value::display`, how a value shows when placed in markup: numbers and versions as their
761/// `repr` in text, a string as text, a symbol as a symbol element, a module as its content, and
762/// anything else as its `repr` in inline `typc` raw.
763pub fn display(engine: &mut Engine, v: Value, span: Span) -> Outcome<Content> {
764 Ok(match v {
765 Value::None => Content::empty(),
766 // Numbers show with a typographic minus and a decimal as its digits, not as their `repr`.
767 Value::Int(_) | Value::Float(_) | Value::Decimal(_) | Value::Version(_)
768 => Content::text(&lib::foundations::display(&v).unwrap_or_default()).with_span(span),
769 Value::Str(s) => Content::text(&s).with_span(span),
770 Value::Symbol(s) => Content::symbol(&crate::eval::ops::symbol_text(&s)).with_span(span),
771 Value::Content(c) => if c.span().is_detached() { c.with_span(span) } else { c },
772 Value::Module(m) => m.content.clone(),
773 other => {
774 let text = lib::foundations::repr(&other);
775 res!(build(engine, ElemKind::Raw, vec![
776 ("text", Value::str(text)),
777 ("block", Value::Bool(false)),
778 ("lang", Value::str("typc")),
779 ], span))
780 }
781 })
782}
783
784/// Builds an element with its fields named as Typst names them. A name the owning unit's schema lacks
785/// is a contract fault, reported rather than dropped.
786pub fn build(engine: &mut Engine, kind: ElemKind, fields: Vec<(&str, Value)>, span: Span) -> Outcome<Content> {
787 let mut fv = Vec::with_capacity(fields.len());
788 for (name, v) in fields {
789 match kind.field_id(name) {
790 Some(id) => fv.push((id, v)),
791 None => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
792 "element `{}` has no field `{}` in its schema", kind.path(), name))),
793 }
794 }
795 Ok(Content::new(kind, fv, span))
796}
797
798// Family dispatch
799
800/// Builds an element from call arguments: the owning unit's custom constructor if it has one, else the
801/// generic schema walk (required positionals, optional positionals, variadics, then named fields).
802pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Content> {
803 let custom = match kind.family() {
804 Family::Text => res!(lib::text::construct(engine, kind, args)),
805 Family::Model => res!(lib::model::construct(engine, kind, args)),
806 Family::Layout => res!(lib::layout::construct(engine, kind, args)),
807 Family::Grid => res!(lib::grid::construct(engine, kind, args)),
808 Family::Visual => res!(lib::visual::construct(engine, kind, args)),
809 Family::Math => res!(lib::math::construct(engine, kind, args)),
810 Family::Intro => res!(lib::intro::construct(engine, kind, args)),
811 Family::Realise => res!(crate::eval::realise::construct(engine, kind, args)),
812 };
813 if let Some(c) = custom {
814 return Ok(c);
815 }
816 let span = args.span;
817 let mut fields = Vec::new();
818 for (i, spec) in kind.fields().iter().enumerate() {
819 let id = FieldId(i as u8);
820 if spec.synthesised || spec.internal {
821 continue;
822 }
823 let value = if spec.variadic {
824 Some(Value::array(res!(args.all::<Value>())))
825 } else if spec.positional && spec.required {
826 Some(res!(args.expect::<Value>(spec.name)))
827 } else if spec.positional {
828 res!(args.find::<Value>(|v| spec.ty.castable(v)))
829 } else {
830 res!(args.named::<Value>(spec.name))
831 };
832 if let Some(v) = value {
833 if !spec.ty.castable(&v) {
834 return Err(engine.error(DiagnosticKind::Type, span, crate::eval::styles::expected_message(spec.ty, &v)));
835 }
836 let v = spec.ty.cast(v);
837 fields.push((id, res!(cast_field(kind, spec.name, v))));
838 }
839 }
840 res!(std::mem::take(args).finish());
841 Ok(Content::new(kind, fields, span))
842}
843
844/// The element's native show: its default realisation into other elements, or `None` for a primitive
845/// that flow lays out itself.
846pub fn native_show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
847 let kind = match elem.kind() {
848 Some(k) => k,
849 None => return Ok(None),
850 };
851 match kind.family() {
852 Family::Text => lib::text::show(engine, elem, styles),
853 Family::Model => lib::model::show(engine, elem, styles),
854 Family::Layout => lib::layout::show(engine, elem, styles),
855 Family::Grid => lib::grid::show(engine, elem, styles),
856 Family::Visual => lib::visual::show(engine, elem, styles),
857 Family::Math => lib::math::show(engine, elem, styles),
858 Family::Intro => lib::intro::show(engine, elem, styles),
859 Family::Realise => Ok(None),
860 }
861}
862
863/// Casts a value into an element's field as its family casts it. Construction and `set` rules both
864/// cast through here, so a value one accepts the other accepts. A family whose fields need no more
865/// than their schema type takes the value as it is.
866/// The arguments an element takes that are not fields but stand for several: `(shorthand, fields)`.
867pub fn shorthands(kind: ElemKind) -> &'static [(&'static str, &'static [&'static str])] {
868 match kind {
869 ElemKind::Grid | ElemKind::Table => &[("gutter", &["column-gutter", "row-gutter"])],
870 _ => &[],
871 }
872}
873
874pub fn cast_field(kind: ElemKind, name: &str, v: Value) -> Outcome<Value> {
875 match kind.family() {
876 Family::Visual => lib::visual::cast_field(kind, name, v),
877 Family::Layout => lib::layout::cast_field(kind, name, v),
878 Family::Model => lib::model::cast_field(kind, name, v),
879 Family::Math => lib::math::cast_field(kind, name, v),
880 _ => Ok(v),
881 }
882}
883
884/// An element's built-in show-set styles, Typst's `ShowSet`: applied outside the user's own show-set
885/// rules when the element is prepared, so a heading's weight is visible to `show heading: it => ..`
886/// and a user rule still overrides it. The styles may depend on the element's own fields (a heading's
887/// level, an equation's block flag), so the element is passed. A family whose elements have them gains
888/// an arm here.
889pub fn show_set(elem: &Content, styles: &StyleChain) -> Outcome<Styles> {
890 let kind = match elem.kind() {
891 Some(k) => k,
892 None => return Ok(Styles::new()),
893 };
894 match kind.family() {
895 Family::Model => lib::model::show_set(elem, styles),
896 Family::Math => lib::math::show_set_of(elem, styles),
897 Family::Text | Family::Layout | Family::Grid | Family::Visual
898 | Family::Intro | Family::Realise => Ok(Styles::new()),
899 }
900}
901
902/// The value a settable field has where nothing sets it: the family's computed default (a list's marker array,
903/// a caption's position, the text font and fill), else the schema's. `None` where the schema holds none and
904/// no family computes one.
905pub fn default_field(kind: ElemKind, field: FieldId) -> Option<Value> {
906 let name = match kind.field_spec(field) {
907 Some(spec) => spec.name,
908 None => return None,
909 };
910 match kind.family() {
911 Family::Model => lib::model::default_value(kind, name),
912 Family::Text => lib::text::default_value(kind, name),
913 Family::Layout => lib::layout::default_value(kind, name),
914 Family::Grid => kind.field_spec(field).and_then(|s| s.default.to_value())
915 .or_else(|| lib::grid::read_default(kind, field)),
916 Family::Visual => lib::visual::default_value(kind, name),
917 Family::Math => lib::math::default_value(kind, name),
918 Family::Intro | Family::Realise
919 => kind.field_spec(field).and_then(|s| s.default.to_value()),
920 }
921}
922
923/// The value an `auto` field has once the element is prepared, worked out from the element and its styles
924/// without preparing it: a heading's level, a figure's kind. `None` where synthesis leaves the field as it is.
925/// A selector reads a field through this, so a rule for `heading.where(level: 1)` matches the heading `=`
926/// makes, whose level is its depth plus the offset in force, before realisation has synthesised it.
927pub fn derived_field(elem: &Content, field: FieldId, styles: &StyleChain) -> Outcome<Option<Value>> {
928 let family = match elem.kind() {
929 Some(k) => k.family(),
930 None => return Ok(None),
931 };
932 match family {
933 Family::Model => lib::model::derived_field(elem, field, styles),
934 Family::Text | Family::Layout | Family::Grid | Family::Visual | Family::Math
935 | Family::Intro | Family::Realise => Ok(None),
936 }
937}
938
939/// Fills an element's synthesised fields once its styles are known, Typst's `Synthesize`: a heading's
940/// resolved numbering, a figure's kind and supplement. A family with such fields gains an arm here.
941pub fn synthesise(engine: &mut Engine, elem: &mut Content, styles: &StyleChain) -> Outcome<()> {
942 let family = match elem.kind() {
943 Some(k) => k.family(),
944 None => return Ok(()),
945 };
946 match family {
947 Family::Model => lib::model::synthesise(engine, elem, styles),
948 Family::Text | Family::Layout | Family::Grid | Family::Visual | Family::Math
949 | Family::Intro | Family::Realise => Ok(()),
950 }
951}