Oregami
Repositories/oxedyne/fe2o3

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

38.7 KiB, 108 runs

created by r1870400018:63514, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1// U4 owns this file. The chain is `Arc`-linked rather than borrowed (`&Styles` links, as the design first
2// sketched) so a realised element can carry its chain into flow, the fixpoint cache and the memo without a
3// lifetime.
4//
5// Folding follows Typst's `Fold` implementations, keyed on the schema's `Fold`: `Add` is `text.size`'s
6// em-relative accumulation (and concatenation for arrays, key overlay for dictionaries); `Merge` is the
7// part-wise fold of strokes, sides and corners. A schema cannot yet say which parts a `Merge` field has, so
8// `radius` folds as corners, `first-line-indent` as an `amount` dictionary and every other `Merge` field as
9// sides. A fold that meets values it cannot combine lets the inner value win, as `Replace` would.
10
11use crate::diag::{
12 Diagnostic,
13 DiagnosticKind,
14};
15use crate::eval::args::Args;
16use crate::eval::content::{
17 self,
18 Content,
19 ElemKind,
20 FieldId,
21 FieldSpec,
22 FieldType,
23 Fold,
24};
25use crate::eval::fp::{
26 self,
27 Kept,
28 Shared,
29};
30use crate::eval::func::Func;
31use crate::eval::ops;
32use crate::eval::select::Selector;
33use crate::eval::value::{
34 Dash,
35 DashItem,
36 Dict,
37 FromValue,
38 Length,
39 LineCap,
40 LineJoin,
41 Paint,
42 Stroke,
43 Value,
44};
45use crate::eval::{
46 Context,
47 Engine,
48};
49use crate::syntax::Span;
50
51use oxedyne_fe2o3_core::prelude::*;
52use oxedyne_fe2o3_hash::fingerprint::Fingerprint;
53use oxedyne_fe2o3_hash::fingerprint::Fingerprinter;
54use oxedyne_fe2o3_hash::fingerprint::LazyFingerprint;
55
56use std::sync::{
57 Arc,
58 OnceLock,
59};
60
61pub const DEFAULT_FONT_SIZE_PT: f64 = 11.0; // Typst's `text.size` default
62
63#[derive(Clone, Debug)]
64pub struct Property {
65 pub elem: ElemKind,
66 pub field: FieldId,
67 pub value: Value,
68 pub span: Span,
69 pub liftable: bool, // set by a set rule: may be lifted to the page level
70 pub outside: bool, // applied outside any show rule or container
71}
72
73impl Property {
74 pub fn new(elem: ElemKind, field: FieldId, value: Value, span: Span) -> Self {
75 Self { elem, field, value, span, liftable: false, outside: false }
76 }
77}
78
79/// What a show rule does to a matched element.
80#[derive(Clone, Debug)]
81pub enum Transformation {
82 Content(Content), // `show sel: [replacement]`
83 Func(Func), // `show sel: it => ..`, and `show: f`
84 Style(Styles), // `show sel: set ..`
85}
86
87/// The identity of a recipe for the guard set: its position counted from the root of the chain (the
88/// outermost recipe is 1), so it stays put while the chain grows inwards.
89#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
90pub struct RecipeIndex(pub usize);
91
92#[derive(Clone, Debug)]
93pub struct Recipe {
94 pub selector: Option<Selector>, // None: `show: f`, wrapping the rest of the scope
95 pub transform: Transformation,
96 pub span: Span,
97 pub outside: bool, // applied outside any show rule or container
98}
99
100impl Recipe {
101 /// Is this a show-set rule, whose styles are collected rather than applied as a step?
102 pub fn is_show_set(&self) -> bool { matches!(self.transform, Transformation::Style(_)) }
103
104 /// Does the recipe's selector match the target? A selector-less recipe matches nothing here: it
105 /// transforms the rest of its scope when it is applied, not individual elements.
106 pub fn applicable(&self, target: &Content, styles: &StyleChain) -> Outcome<bool> {
107 match &self.selector {
108 Some(sel) => sel.matches(target, Some(styles)),
109 None => Ok(false),
110 }
111 }
112}
113
114/// One entry of a `Styles` list. A `Revocation` switches the recipe with that index off for everything
115/// styled beneath it; realisation uses it so a text rule's output is not matched by the same rule.
116#[derive(Clone, Debug)]
117pub enum Style {
118 Property(Property),
119 Recipe(Arc<Recipe>),
120 Revocation(RecipeIndex),
121}
122
123impl Style {
124 /// The element a style concerns: a property's element, or a recipe's selected element. Grouping is
125 /// interrupted by styles on the grouped elements.
126 pub fn element(&self) -> Option<ElemKind> {
127 match self {
128 Style::Property(p) => Some(p.elem),
129 Style::Recipe(r) => match &r.selector {
130 Some(Selector::Elem(k, _)) => Some(*k),
131 _ => None,
132 },
133 Style::Revocation(_) => None,
134 }
135 }
136
137 pub fn span(&self) -> Span {
138 match self {
139 Style::Property(p) => p.span,
140 Style::Recipe(r) => r.span,
141 Style::Revocation(_) => Span::detached(),
142 }
143 }
144
145 /// Was the style applied outside any show rule or container, so that it may reach the page level?
146 pub fn outside(&self) -> bool {
147 match self {
148 Style::Property(p) => p.outside,
149 Style::Recipe(r) => r.outside,
150 Style::Revocation(_) => false,
151 }
152 }
153
154 /// May the style be lifted to the page level? Only a set rule's properties and any recipe may.
155 pub fn liftable(&self) -> bool {
156 match self {
157 Style::Property(p) => p.liftable,
158 Style::Recipe(_) => true,
159 Style::Revocation(_) => false,
160 }
161 }
162
163 /// Is this the style `other` was copied from? Two styles from one rule share their element, field and
164 /// span; a value is not compared.
165 pub fn same(&self, other: &Style) -> bool {
166 match (self, other) {
167 (Style::Property(a), Style::Property(b)) => a.elem == b.elem && a.field == b.field && a.span == b.span
168 && a.outside == b.outside && a.liftable == b.liftable,
169 (Style::Recipe(a), Style::Recipe(b)) => a.span == b.span && a.outside == b.outside,
170 (Style::Revocation(a), Style::Revocation(b)) => a == b,
171 _ => false,
172 }
173 }
174}
175
176/// A list of styles from one `set` or `show`, or several merged. Later entries are inner: they win.
177#[derive(Clone, Debug, Default)]
178pub struct Styles(Shared<StyleList>);
179
180// The list and its fingerprint cell, shared by every clone of a `Styles`, so the list is hashed once.
181#[derive(Clone, Debug, Default)]
182struct StyleList {
183 v: Vec<Style>,
184 fp: LazyFingerprint,
185}
186
187impl Kept for StyleList {
188 fn cell(&mut self) -> &mut LazyFingerprint { &mut self.fp }
189}
190
191impl Styles {
192 pub fn new() -> Self { Self::default() }
193
194 pub fn from_style(s: Style) -> Self { Self::from_vec(vec![s]) }
195
196 pub fn from_vec(v: Vec<Style>) -> Self { Styles(Shared::new(StyleList { v, fp: LazyFingerprint::new() })) }
197
198 pub fn is_empty(&self) -> bool { self.0.v.is_empty() }
199
200 pub fn len(&self) -> usize { self.0.v.len() }
201
202 /// Do both share one list?
203 pub fn ptr_eq(&self, other: &Styles) -> bool { Shared::ptr_eq(&self.0, &other.0) }
204
205 pub fn push(&mut self, s: Style) { self.0.edit().v.push(s); }
206
207 pub fn iter(&self) -> impl Iterator<Item = &Style> { self.0.v.iter() }
208
209 pub fn as_slice(&self) -> &[Style] { &self.0.v }
210
211 /// Appends `other`'s styles after this one's, as consecutive `set` rules accumulate.
212 pub fn extend(&mut self, other: &Styles) {
213 self.0.edit().v.extend(other.iter().cloned());
214 }
215
216 /// Puts `outer` before these styles, so these keep precedence: Typst's `Styles::apply`.
217 pub fn apply_outer(&mut self, outer: &Styles) {
218 if outer.is_empty() {
219 return;
220 }
221 let mut v = outer.as_slice().to_vec();
222 v.extend(self.iter().cloned());
223 *self = Styles::from_vec(v);
224 }
225
226 /// The styles marked as applied outside any show rule or container.
227 pub fn outside(&self) -> Styles {
228 Styles::from_vec(self.iter().cloned().map(|mut s| {
229 match &mut s {
230 Style::Property(p) => p.outside = true,
231 Style::Recipe(r) => if !r.outside { Arc::make_mut(r).outside = true; },
232 Style::Revocation(_) => (),
233 }
234 s
235 }).collect())
236 }
237
238 /// The styles marked as liftable to the page level, as a `set` rule's are.
239 pub fn liftable(&self) -> Styles {
240 Styles::from_vec(self.iter().cloned().map(|mut s| {
241 if let Style::Property(p) = &mut s {
242 p.liftable = true;
243 }
244 s
245 }).collect())
246 }
247
248 /// The styles of content at the root, outside what the author laid out: page furniture and footnote
249 /// entries. Typst's `Styles::root`: the styles every child shares (else those in force at the start),
250 /// of which only an outside style that was in force at the start or is liftable stays, so a set rule
251 /// at the top of the document reaches the furniture but a heading's own styling or a `text` call's
252 /// does not.
253 pub fn root<'a, I: IntoIterator<Item = &'a StyleChain>>(children: I, initial: &StyleChain) -> Styles {
254 let mut chains = children.into_iter().peekable();
255 let base = if chains.peek().is_some() { StyleChain::trunk(chains) } else { initial.clone() };
256 let base = base.flatten();
257 let init = initial.flatten();
258 let kept = init.iter().zip(base.iter()).take_while(|(a, b)| a.same(b)).count();
259 Styles::from_vec(base.into_iter().enumerate()
260 .filter(|(i, s)| s.outside() && (*i < kept || s.liftable()))
261 .map(|(_, s)| s.clone())
262 .collect())
263 }
264
265 /// The fingerprint of the list, span-free.
266 pub fn fingerprint(&self) -> Fingerprint { self.0.fp.get_or_init(|| fp::styles_fp(self)) }
267
268 /// Does any style set a property of `kind`?
269 pub fn has_property_of(&self, kind: ElemKind) -> bool {
270 self.iter().any(|s| matches!(s, Style::Property(p) if p.elem == kind))
271 }
272}
273
274/// A recipe in force at a link, with its root-relative index.
275#[derive(Clone, Debug)]
276pub struct RecipeSlot {
277 pub index: RecipeIndex,
278 pub recipe: Arc<Recipe>,
279}
280
281/// A 128-slot Bloom filter over the `(element, field)` keys of properties: one bit per key, so a link can
282/// say "no property of this key lies here" without a scan. A clear bit is exact; a set bit may be a clash.
283#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
284struct KeyBits(u128);
285
286impl KeyBits {
287 const NONE: KeyBits = KeyBits(0);
288
289 fn of(elem: ElemKind, field: FieldId) -> Self {
290 // A multiplicative hash; its top seven bits pick the slot.
291 let k = (((elem as u32) << 8) | field.0 as u32).wrapping_mul(0x9E37_79B1);
292 KeyBits(1u128 << (k >> 25))
293 }
294
295 fn has(self, key: KeyBits) -> bool { self.0 & key.0 != 0 }
296
297 fn with(self, other: KeyBits) -> KeyBits { KeyBits(self.0 | other.0) }
298}
299
300// A link is immutable once made, so the figures it caches cannot go stale. Its fields are private and no
301// method takes `&mut self`; `styles` is copy-on-write behind an `Arc` that the link holds, so a later edit
302// to any `Styles` the link was made from copies and leaves the link's list as it was; and `parent` is an
303// `Arc` link, itself immutable. Every cached figure -- `own`, `reach`, `total`, `plain`, the recipe list
304// in `force` and the fingerprint in `fp` -- is a pure function of `styles` and the parent's figures, both fixed at construction. A
305// different style is a different link, with a different identity and a cold cache.
306#[derive(Debug)]
307pub struct ChainLink {
308 styles: Styles,
309 parent: Option<Arc<ChainLink>>,
310 own: KeyBits, // keys of the properties in `styles`
311 reach: KeyBits, // keys of the properties in this link and every one above
312 total: usize, // recipes in this link and every one above
313 plain: bool, // no recipe and no revocation in `styles`
314 force: OnceLock<Arc<[RecipeSlot]>>, // the recipes in force here, filled on first use
315 fp: LazyFingerprint,
316}
317
318impl ChainLink {
319 pub fn styles(&self) -> &Styles { &self.styles }
320
321 pub fn parent(&self) -> Option<&Arc<ChainLink>> { self.parent.as_ref() }
322
323 /// The link's styles and its parents', span-free.
324 pub fn fingerprint(&self) -> Fingerprint {
325 self.fp.get_or_init(|| {
326 let mut h = Fingerprinter::new();
327 h.write_fingerprint(self.styles.fingerprint());
328 match &self.parent {
329 Some(p) => { h.write_u8(1); h.write_fingerprint(p.fingerprint()); }
330 None => h.write_u8(0),
331 }
332 h.finish()
333 })
334 }
335
336 pub fn new(styles: Styles, parent: Option<Arc<ChainLink>>) -> Self {
337 let mut own = KeyBits::NONE;
338 let mut recipes = 0;
339 let mut plain = true;
340 for s in styles.as_slice() {
341 match s {
342 Style::Property(p) => own = own.with(KeyBits::of(p.elem, p.field)),
343 Style::Recipe(_) => { recipes += 1; plain = false; },
344 Style::Revocation(_) => plain = false,
345 }
346 }
347 let (above, total) = match &parent {
348 Some(p) => (p.reach, p.total),
349 None => (KeyBits::NONE, 0),
350 };
351 Self { styles, parent, own, reach: own.with(above), total: total + recipes, plain, force: OnceLock::new(), fp: LazyFingerprint::new() }
352 }
353
354 /// The recipes in force at this link, innermost first, none that a revocation further in switched off.
355 /// A plain link adds nothing to its parent's list, so it shares the list of the nearest link above that
356 /// is not plain, and a chain of plain links costs no allocation.
357 fn slots(&self) -> &[RecipeSlot] {
358 let mut link = self;
359 while link.plain {
360 match link.parent.as_deref() {
361 Some(p) => link = p,
362 None => return &[],
363 }
364 }
365 link.force.get_or_init(|| link.build())
366 }
367
368 fn build(&self) -> Arc<[RecipeSlot]> {
369 let mut out = Vec::new();
370 let mut revoked: Vec<RecipeIndex> = Vec::new();
371 let mut r = 0;
372 for s in self.styles.as_slice().iter().rev() {
373 match s {
374 Style::Recipe(recipe) => {
375 let index = RecipeIndex(self.total - r);
376 r += 1;
377 if !revoked.contains(&index) {
378 out.push(RecipeSlot { index, recipe: recipe.clone() });
379 }
380 }
381 Style::Revocation(i) => revoked.push(*i),
382 Style::Property(_) => (),
383 }
384 }
385 // Every revocation here lies inside everything the parent holds.
386 if let Some(p) = self.parent.as_deref() {
387 out.extend(p.slots().iter().filter(|slot| !revoked.contains(&slot.index)).cloned());
388 }
389 out.into()
390 }
391}
392
393/// The values set for one `(element, field)`, innermost first. It skips the links whose figures rule the
394/// key out and reads only those that may hold it.
395struct Values<'a> {
396 link: Option<&'a ChainLink>,
397 elem: ElemKind,
398 field: FieldId,
399 key: KeyBits,
400 pos: usize, // styles of `link` still to read, counting down
401}
402
403impl<'a> Values<'a> {
404 fn new(head: Option<&'a ChainLink>, elem: ElemKind, field: FieldId) -> Self {
405 let mut v = Values { link: None, elem, field, key: KeyBits::of(elem, field), pos: 0 };
406 v.enter(head);
407 v
408 }
409
410 // Nothing from a link whose reach lacks the key, nor from any above it.
411 fn enter(&mut self, link: Option<&'a ChainLink>) {
412 match link {
413 Some(l) if l.reach.has(self.key) => {
414 self.pos = if l.own.has(self.key) { l.styles.len() } else { 0 };
415 self.link = Some(l);
416 }
417 _ => self.link = None,
418 }
419 }
420}
421
422impl<'a> Iterator for Values<'a> {
423 type Item = &'a Value;
424
425 fn next(&mut self) -> Option<&'a Value> {
426 loop {
427 let l = self.link?;
428 while self.pos > 0 {
429 self.pos -= 1;
430 if let Style::Property(p) = &l.styles.as_slice()[self.pos] {
431 if p.elem == self.elem && p.field == self.field {
432 return Some(&p.value);
433 }
434 }
435 }
436 self.enter(l.parent.as_deref());
437 }
438 }
439}
440
441/// The styles in force at a point, innermost first. Cloning is a reference-count bump.
442#[derive(Clone, Debug, Default)]
443pub struct StyleChain {
444 pub head: Option<Arc<ChainLink>>,
445}
446
447impl StyleChain {
448 pub fn root() -> Self { Self::default() }
449
450 /// This chain with `styles` pushed innermost.
451 pub fn chain(&self, styles: &Styles) -> StyleChain {
452 if styles.is_empty() {
453 return self.clone();
454 }
455 StyleChain { head: Some(Arc::new(ChainLink::new(styles.clone(), self.head.clone()))) }
456 }
457
458 /// The links, innermost first.
459 pub fn links(&self) -> Vec<&Arc<ChainLink>> {
460 let mut links = Vec::new();
461 let mut cur = self.head.as_ref();
462 while let Some(l) = cur {
463 links.push(l);
464 cur = l.parent.as_ref();
465 }
466 links
467 }
468
469 pub fn depth(&self) -> usize { self.links().len() }
470
471 /// The fingerprint of the chain, link for link, span-free.
472 pub fn fingerprint(&self) -> Fingerprint {
473 match &self.head {
474 Some(l) => l.fingerprint(),
475 None => Fingerprinter::new().finish(),
476 }
477 }
478
479 /// Are both the same chain, link for link? Two chains built separately from equal styles are not.
480 pub fn ptr_eq(&self, other: &StyleChain) -> bool {
481 match (&self.head, &other.head) {
482 (None, None) => true,
483 (Some(a), Some(b)) => Arc::ptr_eq(a, b),
484 _ => false,
485 }
486 }
487
488 /// Every style, outermost first: Typst's `to_map`.
489 pub fn flatten(&self) -> Vec<&Style> {
490 self.links().into_iter().rev().flat_map(|l| l.styles.iter()).collect()
491 }
492
493 /// Every style, innermost first.
494 pub fn walk(&self) -> impl Iterator<Item = &Style> {
495 self.links().into_iter().flat_map(|l| l.styles.as_slice().iter().rev())
496 }
497
498 /// Every recipe with its index, innermost first, skipping those a revocation further in switched off.
499 /// The list is built once per link and shared by every chain that has the link at its head.
500 pub fn recipes(&self) -> &[RecipeSlot] {
501 match self.head.as_deref() {
502 Some(l) => l.slots(),
503 None => &[],
504 }
505 }
506
507 /// The chain of the longest link sequence every chain shares, counted from the root: Typst's trunk,
508 /// under which realisation places a group built from differently styled members.
509 pub fn trunk<'a, I: IntoIterator<Item = &'a StyleChain>>(chains: I) -> StyleChain {
510 let mut trunk: Option<Vec<Arc<ChainLink>>> = None;
511 for c in chains {
512 let mut outer_first: Vec<Arc<ChainLink>> = c.links().into_iter().cloned().collect();
513 outer_first.reverse();
514 trunk = Some(match trunk {
515 None => outer_first,
516 Some(t) => {
517 let n = t.iter().zip(outer_first.iter()).take_while(|(a, b)| Arc::ptr_eq(a, b)).count();
518 t.into_iter().take(n).collect()
519 }
520 });
521 }
522 StyleChain { head: trunk.and_then(|t| t.last().cloned()) }
523 }
524
525 /// The styles of the links above the innermost `depth`-deep trunk, merged outer to inner: what must
526 /// be reapplied locally when content moves under the trunk.
527 pub fn suffix(&self, depth: usize) -> Styles {
528 let links = self.links();
529 let keep = links.len().saturating_sub(depth);
530 let mut out = Styles::new();
531 for l in links.into_iter().take(keep).rev() {
532 out.extend(&l.styles);
533 }
534 out
535 }
536
537 /// Every value set for `elem.field`, innermost first, for a unit that folds a `Fold::Custom` field
538 /// itself.
539 pub fn values(&self, elem: ElemKind, field: FieldId) -> Vec<&Value> {
540 self.value_iter(elem, field).collect()
541 }
542
543 fn value_iter(&self, elem: ElemKind, field: FieldId) -> Values<'_> {
544 Values::new(self.head.as_deref(), elem, field)
545 }
546
547 /// Runs `f` on the values set for `elem.field`, innermost first. Nothing allocates for none or one
548 /// value, which is nearly every lookup.
549 fn with_values<R>(&self, elem: ElemKind, field: FieldId, f: impl FnOnce(&[&Value]) -> R) -> R {
550 let mut it = self.value_iter(elem, field);
551 let first = match it.next() {
552 Some(v) => v,
553 None => return f(&[]),
554 };
555 match it.next() {
556 None => f(&[first]),
557 Some(second) => {
558 let mut all = vec![first, second];
559 all.extend(it);
560 f(&all)
561 }
562 }
563 }
564
565 /// The value of `elem.field` in force: the set values folded by the field's schema rule onto the
566 /// schema default, the innermost set value for `Replace`, and the owning family's fold for `Custom`.
567 pub fn get(&self, elem: ElemKind, field: FieldId) -> Outcome<Option<Value>> {
568 self.with_values(elem, field, |values| match elem.field_spec(field) {
569 Some(s) if s.fold == Fold::Custom => fold_custom_all(elem, s, values),
570 Some(s) => Ok(fold_all(s, values)),
571 None => Ok(values.first().map(|v| (*v).clone())),
572 })
573 }
574
575 pub fn get_as<T: FromValue>(&self, elem: ElemKind, field: FieldId) -> Outcome<Option<T>> {
576 match res!(self.get(elem, field)) {
577 Some(v) => Ok(Some(res!(T::from_value(v)))),
578 None => Ok(None),
579 }
580 }
581
582 /// The value for an element in hand: its own field if set -- folded onto the chain's value for a
583 /// folding field, as `rect(stroke: 2pt)` under `set rect(stroke: red)` is a red 2pt stroke -- else the
584 /// chain's.
585 pub fn resolve(&self, elem: &Content, field: FieldId) -> Outcome<Option<Value>> {
586 let kind = match elem.kind() {
587 Some(k) => k,
588 None => return Ok(elem.get(field).cloned()),
589 };
590 let own = match elem.get(field) {
591 Some(own) => own,
592 None => return self.get(kind, field),
593 };
594 let spec = match kind.field_spec(field) {
595 Some(s) if s.fold != Fold::Replace => s,
596 _ => return Ok(Some(own.clone())),
597 };
598 let outer = match res!(self.get(kind, field)) {
599 Some(o) => o,
600 None => return Ok(Some(own.clone())),
601 };
602 if spec.fold == Fold::Custom {
603 return Ok(Some(res!(content::fold_custom(kind, spec.name, own.clone(), outer))));
604 }
605 let is_def = self.value_iter(kind, field).next().is_none();
606 Ok(Some(fold(spec, own, &outer, is_def)))
607 }
608
609 /// The font size in force, in points: `text.size` folded, Typst's 11pt when the schema is silent.
610 pub fn font_size(&self) -> f64 {
611 // `text.size` folds by `Add`, which cannot fail.
612 let size = ElemKind::Text.field_id("size").and_then(|id| match ElemKind::Text.field_spec(id) {
613 Some(s) if s.fold != Fold::Custom => self.with_values(ElemKind::Text, id, |vs| fold_all(s, vs)),
614 _ => None,
615 });
616 match size {
617 Some(Value::Length(l)) => l.abs + l.em * DEFAULT_FONT_SIZE_PT,
618 _ => DEFAULT_FONT_SIZE_PT,
619 }
620 }
621
622 /// A length in points, its em part resolved against the font size in force.
623 pub fn resolve_length(&self, l: Length) -> f64 {
624 if l.em == 0.0 {
625 return l.abs;
626 }
627 l.resolve(self.font_size())
628 }
629}
630
631// Folding
632
633/// The value of a field set to `values` (innermost first) on top of its schema default: folded by the
634/// field's rule, or the innermost value for `Replace` (and for `Custom`, which `fold_custom_all` folds).
635pub fn fold_all(spec: &FieldSpec, values: &[&Value]) -> Option<Value> {
636 let default = spec.default.to_value();
637 if matches!(spec.fold, Fold::Replace | Fold::Custom) {
638 return match values.first() {
639 Some(v) => Some((*v).clone()),
640 None => default,
641 };
642 }
643 let mut acc: Option<(Value, bool)> = default.map(|d| (d, true));
644 for v in values.iter().rev() {
645 acc = Some(match acc {
646 None => ((*v).clone(), false),
647 Some((o, is_def)) => (fold(spec, v, &o, is_def), false),
648 });
649 }
650 acc.map(|(v, _)| v)
651}
652
653/// A `Custom` field's values (innermost first) folded outward-in by the owning family onto the schema
654/// default.
655fn fold_custom_all(kind: ElemKind, spec: &FieldSpec, values: &[&Value]) -> Outcome<Option<Value>> {
656 let mut acc = spec.default.to_value();
657 for v in values.iter().rev() {
658 acc = Some(match acc {
659 None => (*v).clone(),
660 Some(o) => res!(content::fold_custom(kind, spec.name, (*v).clone(), o)),
661 });
662 }
663 Ok(acc)
664}
665
666/// Folds an inner value onto an outer one by the field's rule. `outer_default` says the outer value is
667/// the schema default rather than a set value: a `none` default contributes no parts to a sides fold,
668/// as Typst's `Sides<Option<T>>` default has none.
669pub fn fold(spec: &FieldSpec, inner: &Value, outer: &Value, outer_default: bool) -> Value {
670 match spec.fold {
671 Fold::Replace | Fold::Custom => inner.clone(),
672 Fold::Add => fold_add(inner, outer),
673 Fold::Sides => fold_merge(Shape::Sides, inner, outer, outer_default),
674 Fold::Corners => fold_merge(Shape::Corners, inner, outer, outer_default),
675 Fold::Keyed(key) => fold_merge(Shape::Keyed(key), inner, outer, outer_default),
676 Fold::Stroke => fold_stroke(inner, outer),
677 }
678}
679
680fn fold_add(inner: &Value, outer: &Value) -> Value {
681 match (inner, outer) {
682 // Typst's `TextSize` fold: the inner em part is resolved against the outer size.
683 (Value::Length(i), Value::Length(o)) => Value::Length(Length {
684 abs: i.abs + i.em * o.abs,
685 em: i.em * o.em,
686 }),
687 (Value::Array(i), Value::Array(o)) => {
688 let mut v = (**o).clone();
689 v.extend(i.iter().cloned());
690 Value::array(v)
691 }
692 (Value::Dict(i), Value::Dict(o)) => Value::dict(overlay(o, i)),
693 _ => inner.clone(),
694 }
695}
696
697/// The parts a part-wise field folds by.
698#[derive(Clone, Copy, Debug, PartialEq, Eq)]
699enum Shape {
700 Sides,
701 Corners,
702 Keyed(&'static str), // a dictionary whose bare-value form is this key (`first-line-indent`'s amount)
703}
704
705const SIDE_KEYS: &[&str] = &["left", "top", "right", "bottom", "x", "y", "rest", "inside", "outside"];
706const CORNER_KEYS: &[&str] = &["top-left", "top-right", "bottom-right", "bottom-left",
707 "left", "top", "right", "bottom", "rest"];
708const STROKE_KEYS: &[&str] = &["paint", "thickness", "cap", "join", "dash", "miter-limit"];
709
710fn fold_merge(shape: Shape, inner: &Value, outer: &Value, outer_default: bool) -> Value {
711 if matches!(inner, Value::None | Value::Auto) {
712 return inner.clone();
713 }
714 match shape {
715 Shape::Keyed(key) => match (inner, outer) {
716 (Value::Dict(i), Value::Dict(o)) => Value::dict(overlay(o, i)),
717 (Value::Dict(i), o) if !matches!(o, Value::None | Value::Auto) => {
718 let mut base = Dict::new();
719 base.insert(key, o.clone());
720 Value::dict(overlay(&base, i))
721 }
722 (i, Value::Dict(o)) => {
723 let mut top = Dict::new();
724 top.insert(key, i.clone());
725 Value::dict(overlay(o, &top))
726 }
727 _ => inner.clone(),
728 },
729 Shape::Sides | Shape::Corners => {
730 let ip = parts(shape, inner);
731 let op = parts(shape, outer);
732 if ip.is_none() && op.is_none() {
733 return fold_part(inner, outer);
734 }
735 let named = ip.as_ref().map(|p| p.two_sided).unwrap_or(false)
736 || op.as_ref().map(|p| p.two_sided).unwrap_or(false);
737 let ip = match ip {
738 Some(p) => p.parts,
739 None => uniform(shape, Some(inner)),
740 };
741 let op = match op {
742 Some(p) => p.parts,
743 None if outer_default && outer.is_none() => uniform(shape, None),
744 None => uniform(shape, Some(outer)),
745 };
746 let merged: Vec<Option<Value>> = ip.into_iter().zip(op).map(|(i, o)| match (i, o) {
747 (Some(i), Some(o)) => Some(fold_part(&i, &o)),
748 (Some(i), None) => Some(i),
749 (None, o) => o,
750 }).collect();
751 collapse(shape, merged, named)
752 }
753 }
754}
755
756// One stroke: `none` and `auto` replace, anything else folds part-wise.
757fn fold_stroke(inner: &Value, outer: &Value) -> Value {
758 if matches!(inner, Value::None | Value::Auto) {
759 return inner.clone();
760 }
761 fold_part(inner, outer)
762}
763
764/// Folds one part: strokes part-wise, anything else inner-wins.
765fn fold_part(inner: &Value, outer: &Value) -> Value {
766 if is_stroke_like(inner) && is_stroke_like(outer)
767 && !(matches!(inner, Value::Length(_)) && matches!(outer, Value::Length(_)))
768 {
769 if let (Some(i), Some(o)) = (to_stroke(inner), to_stroke(outer)) {
770 return Value::Stroke(Arc::new(merge_stroke(i, o)));
771 }
772 }
773 inner.clone()
774}
775
776struct Parts {
777 parts: Vec<Option<Value>>, // sides: left, top, right, bottom; corners: tl, tr, br, bl
778 two_sided: bool, // written with `inside`/`outside`
779}
780
781fn is_parts_dict(shape: Shape, d: &Dict) -> bool {
782 let keys = match shape {
783 Shape::Corners => CORNER_KEYS,
784 _ => SIDE_KEYS,
785 };
786 d.keys().all(|k| keys.contains(&k))
787}
788
789fn parts(shape: Shape, v: &Value) -> Option<Parts> {
790 let d = match v {
791 Value::Dict(d) if is_parts_dict(shape, d) => d,
792 _ => return None,
793 };
794 let get = |k: &str| d.get(k).cloned();
795 match shape {
796 Shape::Corners => {
797 let rest = get("rest");
798 let left = get("left").or_else(|| rest.clone());
799 let top = get("top").or_else(|| rest.clone());
800 let right = get("right").or_else(|| rest.clone());
801 let bottom = get("bottom").or_else(|| rest.clone());
802 Some(Parts { parts: vec![
803 get("top-left").or_else(|| top.clone()).or_else(|| left.clone()),
804 get("top-right").or_else(|| top.clone()).or_else(|| right.clone()),
805 get("bottom-right").or_else(|| bottom.clone()).or_else(|| right.clone()),
806 get("bottom-left").or_else(|| bottom.clone()).or_else(|| left.clone()),
807 ], two_sided: false })
808 }
809 _ => {
810 let rest = get("rest");
811 let x = get("x").or_else(|| rest.clone());
812 let y = get("y").or_else(|| rest.clone());
813 let two_sided = d.contains("inside") || d.contains("outside");
814 let left = get("left").or_else(|| get("inside")).or_else(|| x.clone());
815 let right = get("right").or_else(|| get("outside")).or_else(|| x.clone());
816 Some(Parts { parts: vec![
817 left,
818 get("top").or_else(|| y.clone()),
819 right,
820 get("bottom").or_else(|| y.clone()),
821 ], two_sided })
822 }
823 }
824}
825
826fn uniform(_shape: Shape, v: Option<&Value>) -> Vec<Option<Value>> {
827 vec![v.cloned(), v.cloned(), v.cloned(), v.cloned()]
828}
829
830/// Back to a value: one value when every part is present and equal, else a dictionary of the parts
831/// present, in Typst's order.
832fn collapse(shape: Shape, parts: Vec<Option<Value>>, two_sided: bool) -> Value {
833 let all_same = match parts.first() {
834 Some(Some(first)) => parts.iter().all(|p| match p {
835 Some(v) => same(v, first),
836 None => false,
837 }),
838 _ => false,
839 };
840 if all_same && !two_sided {
841 if let Some(Some(v)) = parts.into_iter().next() {
842 return v;
843 }
844 return Value::None;
845 }
846 let names: [&str; 4] = match shape {
847 Shape::Corners => ["top-left", "top-right", "bottom-right", "bottom-left"],
848 _ if two_sided => ["inside", "top", "outside", "bottom"],
849 _ => ["left", "top", "right", "bottom"],
850 };
851 let mut d = Dict::new();
852 for (name, p) in names.iter().zip(parts) {
853 if let Some(v) = p {
854 d.insert(name, v);
855 }
856 }
857 Value::dict(d)
858}
859
860fn overlay(outer: &Dict, inner: &Dict) -> Dict {
861 let mut d = outer.clone();
862 for (k, v) in inner.iter() {
863 d.insert(k, v.clone());
864 }
865 d
866}
867
868fn same(a: &Value, b: &Value) -> bool {
869 match (a, b) {
870 (Value::Stroke(x), Value::Stroke(y)) => stroke_eq(x, y),
871 (Value::Color(x), Value::Color(y)) => x == y,
872 _ => ops::equal(a, b),
873 }
874}
875
876fn stroke_eq(a: &Stroke, b: &Stroke) -> bool {
877 let paint_eq = match (&a.paint, &b.paint) {
878 (None, None) => true,
879 (Some(Paint::Color(x)), Some(Paint::Color(y))) => x == y,
880 (Some(Paint::Gradient(x)), Some(Paint::Gradient(y))) => x == y,
881 (Some(Paint::Tiling(x)), Some(Paint::Tiling(y))) => Arc::ptr_eq(x, y),
882 _ => false,
883 };
884 paint_eq && a.thickness == b.thickness && a.cap == b.cap && a.join == b.join
885 && a.dash == b.dash && a.miter_limit == b.miter_limit
886}
887
888fn is_stroke_like(v: &Value) -> bool {
889 match v {
890 Value::Stroke(_) | Value::Length(_) | Value::Color(_) | Value::Gradient(_) | Value::Tiling(_) => true,
891 Value::Dict(d) => !d.is_empty() && d.keys().all(|k| STROKE_KEYS.contains(&k)),
892 _ => false,
893 }
894}
895
896/// A stroke from any value Typst accepts as one: a stroke, a length (thickness), a paint, or a
897/// dictionary of stroke parts. `None` when the value is none of these or a part is malformed.
898pub fn to_stroke(v: &Value) -> Option<Stroke> {
899 match v {
900 Value::Stroke(s) => Some((**s).clone()),
901 Value::Length(l) => Some(Stroke { thickness: Some(*l), ..Stroke::default() }),
902 Value::Color(c) => Some(Stroke { paint: Some(Paint::Color(*c)), ..Stroke::default() }),
903 Value::Gradient(g) => Some(Stroke { paint: Some(Paint::Gradient(g.clone())), ..Stroke::default() }),
904 Value::Tiling(t) => Some(Stroke { paint: Some(Paint::Tiling(t.clone())), ..Stroke::default() }),
905 Value::Dict(d) => {
906 let mut s = Stroke::default();
907 for (k, v) in d.iter() {
908 match k {
909 "paint" => s.paint = Some(match v {
910 Value::Color(c) => Paint::Color(*c),
911 Value::Gradient(g) => Paint::Gradient(g.clone()),
912 Value::Tiling(t) => Paint::Tiling(t.clone()),
913 _ => return None,
914 }),
915 "thickness" => s.thickness = Some(match v {
916 Value::Length(l) => *l,
917 _ => return None,
918 }),
919 "cap" => s.cap = Some(match v {
920 Value::Str(x) if x.as_str() == "butt" => LineCap::Butt,
921 Value::Str(x) if x.as_str() == "round" => LineCap::Round,
922 Value::Str(x) if x.as_str() == "square" => LineCap::Square,
923 _ => return None,
924 }),
925 "join" => s.join = Some(match v {
926 Value::Str(x) if x.as_str() == "miter" => LineJoin::Miter,
927 Value::Str(x) if x.as_str() == "round" => LineJoin::Round,
928 Value::Str(x) if x.as_str() == "bevel" => LineJoin::Bevel,
929 _ => return None,
930 }),
931 "dash" => s.dash = Some(match to_dash(v) {
932 Some(d) => d,
933 None => return None,
934 }),
935 "miter-limit" => s.miter_limit = Some(match v {
936 Value::Int(i) => *i as f64,
937 Value::Float(f) => *f,
938 _ => return None,
939 }),
940 _ => return None,
941 }
942 }
943 Some(s)
944 }
945 _ => None,
946 }
947}
948
949/// A dash from `none`, a named pattern, an array of lengths and `"dot"`, or `(array:, phase:)`.
950/// `Some(None)` is an explicit solid line.
951fn to_dash(v: &Value) -> Option<Option<Dash>> {
952 let pt = |x: f64| DashItem::Len(Length::pt(x));
953 let pattern = |items: Vec<DashItem>| Some(Some(Dash { array: items, phase: Length::zero() }));
954 match v {
955 Value::None => Some(None),
956 Value::Str(s) => match s.as_str() {
957 "solid" => Some(None),
958 "dotted" => pattern(vec![DashItem::Dot, pt(2.0)]),
959 "densely-dotted" => pattern(vec![DashItem::Dot, pt(1.0)]),
960 "loosely-dotted" => pattern(vec![DashItem::Dot, pt(4.0)]),
961 "dashed" => pattern(vec![pt(3.0), pt(3.0)]),
962 "densely-dashed" => pattern(vec![pt(3.0), pt(2.0)]),
963 "loosely-dashed" => pattern(vec![pt(3.0), pt(6.0)]),
964 "dash-dotted" => pattern(vec![pt(3.0), pt(2.0), DashItem::Dot, pt(2.0)]),
965 "densely-dash-dotted" => pattern(vec![pt(3.0), pt(1.0), DashItem::Dot, pt(1.0)]),
966 "loosely-dash-dotted" => pattern(vec![pt(3.0), pt(4.0), DashItem::Dot, pt(4.0)]),
967 _ => None,
968 },
969 Value::Array(a) => {
970 let mut items = Vec::new();
971 for x in a.iter() {
972 items.push(match x {
973 Value::Length(l) => DashItem::Len(*l),
974 Value::Str(s) if s.as_str() == "dot" => DashItem::Dot,
975 _ => return None,
976 });
977 }
978 pattern(items)
979 }
980 Value::Dict(d) => {
981 let array = match d.get("array").map(to_dash) {
982 Some(Some(Some(dash))) => dash.array,
983 _ => return None,
984 };
985 let phase = match d.get("phase") {
986 Some(Value::Length(l)) => *l,
987 None => Length::zero(),
988 _ => return None,
989 };
990 Some(Some(Dash { array, phase }))
991 }
992 _ => None,
993 }
994}
995
996fn merge_stroke(inner: Stroke, outer: Stroke) -> Stroke {
997 Stroke {
998 paint: inner.paint.or(outer.paint),
999 thickness: inner.thickness.or(outer.thickness),
1000 cap: inner.cap.or(outer.cap),
1001 join: inner.join.or(outer.join),
1002 dash: inner.dash.or(outer.dash),
1003 miter_limit: inner.miter_limit.or(outer.miter_limit),
1004 }
1005}
1006
1007// Set rules
1008
1009/// "A, B, or C", as Typst lists the types a cast accepts.
1010fn list_types(ts: &[&str]) -> String {
1011 match ts.len() {
1012 0 => String::new(),
1013 1 => ts[0].to_string(),
1014 2 => fmt!("{} or {}", ts[0], ts[1]),
1015 n => fmt!("{}, or {}", ts[..n - 1].join(", "), ts[n - 1]),
1016 }
1017}
1018
1019/// The message for a value a field does not accept.
1020pub fn expected_message(ty: FieldType, found: &Value) -> String {
1021 let expected = match ty {
1022 FieldType::Keyword(_, choices) => return fmt!("expected {}, found {}", choices, found.ty().long_name()),
1023 FieldType::Any => "any value".to_string(),
1024 FieldType::Of(t) => t.long_name().to_string(),
1025 FieldType::OneOf(ts) => list_types(&ts.iter().map(|t| t.long_name()).collect::<Vec<_>>()),
1026 FieldType::Content => "content".to_string(),
1027 };
1028 fmt!("expected {}, found {}", expected, found.ty().long_name())
1029}
1030
1031/// `set elem(args)`: the settable fields given, as styles, in schema order. A positional settable field
1032/// takes the first positional argument its type accepts; a named one the last argument of its name.
1033/// Anything left over -- a required field, a synthesised one, an unknown name -- is "unexpected argument".
1034pub fn set_rule(engine: &mut Engine, kind: ElemKind, mut args: Args) -> Outcome<Styles> {
1035 let mut styles = Styles::new();
1036 // A shorthand stands for the fields it names, behind any of them given outright: `set grid(gutter: g)`
1037 // is `column-gutter: g, row-gutter: g`, as Typst's grid parses it.
1038 for (short, targets) in content::shorthands(kind) {
1039 let mut j = 0;
1040 while j < args.items.len() {
1041 if args.items[j].name.as_deref() == Some(*short) {
1042 let a = args.items.remove(j);
1043 for (k, t) in targets.iter().enumerate() {
1044 let mut b = a.clone();
1045 b.name = Some(t.to_string());
1046 args.items.insert(k, b);
1047 }
1048 j += targets.len();
1049 } else {
1050 j += 1;
1051 }
1052 }
1053 }
1054 for (i, spec) in kind.fields().iter().enumerate() {
1055 if !spec.settable || spec.synthesised || spec.required {
1056 continue;
1057 }
1058 let id = FieldId(i as u8);
1059 // The last argument of the field's name, else for a positional field the first unnamed one that
1060 // casts to it: Typst's `named_or_find`, so `set page("a4")` finds its paper by name.
1061 let mut taken = None;
1062 let mut j = 0;
1063 while j < args.items.len() {
1064 if args.items[j].name.as_deref() == Some(spec.name) {
1065 taken = Some(args.items.remove(j));
1066 } else {
1067 j += 1;
1068 }
1069 }
1070 if taken.is_none() && spec.positional {
1071 if let Some(p) = args.items.iter().position(|a| a.name.is_none() && spec.ty.castable(&a.value)
1072 && content::cast_field(kind, spec.name, spec.ty.cast(a.value.clone())).is_ok())
1073 {
1074 taken = Some(args.items.remove(p));
1075 }
1076 }
1077 if let Some(mut arg) = taken {
1078 if !spec.ty.castable(&arg.value) {
1079 let msg = expected_message(spec.ty, &arg.value);
1080 return Err(engine.error(DiagnosticKind::Type, arg.span, msg));
1081 }
1082 arg.value = spec.ty.cast(arg.value);
1083 // Cast as construction casts, so `set` refuses at the rule what the element would refuse.
1084 let value = match content::cast_field(kind, spec.name, arg.value) {
1085 Ok(v) => v,
1086 Err(e) => return Err(engine.error(DiagnosticKind::Type, arg.span, crate::diag::message_of(&e))),
1087 };
1088 if kind == ElemKind::Text && spec.name == "font" {
1089 res!(crate::eval::lib::text::check_font_list(engine, &value, arg.value_span));
1090 }
1091 styles.push(Style::Property(Property::new(kind, id, value, arg.span)));
1092 }
1093 }
1094 if let Some(a) = args.items.first() {
1095 let span = if a.span.is_detached() { args.span } else { a.span };
1096 let msg = match &a.name {
1097 Some(n) => fmt!("unexpected argument: {}", n),
1098 None => "unexpected argument".to_string(),
1099 };
1100 return Err(engine.error(DiagnosticKind::Type, span, msg));
1101 }
1102 Ok(styles)
1103}
1104
1105// Applying recipes
1106
1107/// `content` under a recipe, as a `show` statement leaves the rest of its scope: a selector-less recipe
1108/// (`show: f`) is applied at once, as Typst does, and any other is attached as a style for realisation.
1109pub fn styled_with_recipe(engine: &mut Engine, content: Content, recipe: Recipe) -> Outcome<Content> {
1110 if recipe.selector.is_none() {
1111 let chain = match &engine.context.styles {
1112 Some(s) => s.clone(),
1113 None => StyleChain::root(),
1114 };
1115 return apply_recipe(engine, &recipe, content, &chain);
1116 }
1117 Ok(content.styled(Styles::from_style(Style::Recipe(Arc::new(recipe)))))
1118}
1119
1120/// Applies one recipe to its target. A function recipe runs with the target's location and `chain` as
1121/// its context and receives the target as its one argument; its result is displayed as content.
1122pub fn apply_recipe(engine: &mut Engine, recipe: &Recipe, target: Content, chain: &StyleChain) -> Outcome<Content> {
1123 match &recipe.transform {
1124 Transformation::Content(c) => Ok(c.clone()),
1125 Transformation::Style(s) => Ok(target.styled(s.clone())),
1126 Transformation::Func(f) => {
1127 let span = target.span();
1128 let name = match target.kind() {
1129 Some(k) => k.name(),
1130 None => "content",
1131 };
1132 let mut args = Args::new(recipe.span);
1133 args.push(span, Value::Content(target.clone()));
1134 let saved = std::mem::replace(&mut engine.context, Context {
1135 location: target.location(),
1136 styles: Some(chain.clone()),
1137 });
1138 let before = engine.diags.len();
1139 let result = engine.call_func(f, args);
1140 engine.context = saved;
1141 match result {
1142 Ok(v) => content::display(engine, v, span),
1143 Err(e) => {
1144 if recipe.selector.is_some() {
1145 let note = fmt!("error occurred while applying show rule to this {}", name);
1146 for d in engine.diags[before..].iter_mut().filter(|d| d.is_error()) {
1147 d.trace.push((span, note.clone()));
1148 }
1149 }
1150 Err(e)
1151 }
1152 }
1153 }
1154 }
1155}
1156
1157/// Records an error with several hints and returns it.
1158pub(crate) fn error_hints(
1159 engine: &mut Engine,
1160 kind: DiagnosticKind,
1161 span: Span,
1162 message: &str,
1163 hints: &[&str],
1164)
1165 -> Error<ErrTag>
1166{
1167 let mut d = Diagnostic::error(kind, span, message);
1168 for h in hints {
1169 d = d.with_hint(*h);
1170 }
1171 engine.diags.push(d);
1172 err!("{}", message; Input, Invalid)
1173}