Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/src/eval/lib/model/mod.rs

15.7 KiB, 3 runs

created by r1870400018:63272, 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// SPDX-License-Identifier: Apache-2.0
2// Original work copyright (c) the Typst project authors (typst-library `model/mod.rs`, version 0.15.1).
3// Modified for Austenite: the element's fields, defaults and default show, ported to Hematite's types, IR and error handling.
4//! Contract (U0, 2026-09-23; U5 owns this directory): the model family. Each element's schema and
5//! native show live in the submodule named for it, and this file only dispatches by `ElemKind`. A native
6//! show reproduces Typst's own default (heading sizes, list indents, figure supplement), never Austenite's
7//! old `Theme`; `par` and `parbreak` are primitives flow sets, so their show is `None`.
8//!
9//! Beyond the contract's `fields`/`construct`/`show`, the family answers the hooks Typst's element traits
10//! give it, each a plain function realisation and introspection call by kind: `cast` (a field's value
11//! check, as `construct` and `set` apply it), `default_value` (the defaults no `static` can hold),
12//! `synthesise` (Typst's `Synthesize`), `show_set` (`ShowSet`, the built-in styles a show rule sees),
13//! `count_step` (`Count`) and `method` (functions scoped to an element, `outline.entry.indented`).
14//! Schemas list Typst's public fields in Typst's order; a Typst-internal field (`list`'s depth) is marked
15//! `internal`, so it is never set, constructed, materialised or shown by `fields()` and `repr`.
16
17pub mod bibliography;
18pub mod common;
19pub mod divider;
20pub mod document;
21pub mod emph;
22pub mod figure;
23pub mod footnote;
24pub mod heading;
25pub mod link;
26pub mod list;
27pub mod local;
28pub mod lookup;
29pub mod outline;
30pub mod par;
31pub mod quote;
32pub mod raw;
33pub mod reference;
34
35use crate::diag::DiagnosticKind;
36use crate::eval::args::Args;
37use crate::eval::content::{
38 Content,
39 ElemKind,
40 FieldId,
41 FieldSpec,
42};
43use crate::eval::scope::Scope;
44use crate::eval::styles::{
45 StyleChain,
46 Styles,
47};
48use crate::eval::value::Value;
49use crate::eval::Engine;
50use crate::syntax::Span;
51
52use common::CastErr;
53
54use oxedyne_fe2o3_core::prelude::*;
55
56native_fns! {
57 pub enum ModelFn {
58 EntryIndented => "indented",
59 EntryPrefix => "prefix",
60 EntryInner => "inner",
61 EntryBody => "body",
62 EntryPage => "page",
63 }
64}
65
66pub fn define(_scope: &mut Scope) {}
67
68pub fn call(f: ModelFn, engine: &mut Engine, args: Args) -> Outcome<Value> {
69 match f {
70 ModelFn::EntryIndented | ModelFn::EntryPrefix | ModelFn::EntryInner | ModelFn::EntryBody
71 | ModelFn::EntryPage => outline::call(f, engine, args),
72 }
73}
74
75/// The function scoped to an element that a method call on such content reaches:
76/// `it.indented(it.prefix(), it.inner())` on an `outline.entry`.
77pub fn method(kind: ElemKind, name: &str) -> Option<ModelFn> {
78 match kind {
79 ElemKind::OutlineEntry => outline::method(name),
80 _ => None,
81 }
82}
83
84pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
85 match kind {
86 ElemKind::Par | ElemKind::ParLine | ElemKind::Parbreak => par::fields(kind),
87 ElemKind::Strong | ElemKind::Emph => emph::fields(kind),
88 ElemKind::Raw | ElemKind::RawLine => raw::fields(kind),
89 ElemKind::Heading | ElemKind::Title => heading::fields(kind),
90 ElemKind::List | ElemKind::ListItem | ElemKind::Enum | ElemKind::EnumItem
91 | ElemKind::Terms | ElemKind::TermItem => list::fields(kind),
92 ElemKind::Link => link::fields(kind),
93 ElemKind::Ref | ElemKind::Cite => reference::fields(kind),
94 ElemKind::Footnote | ElemKind::FootnoteEntry => footnote::fields(kind),
95 ElemKind::Figure | ElemKind::FigureCaption => figure::fields(kind),
96 ElemKind::Outline | ElemKind::OutlineEntry => outline::fields(kind),
97 ElemKind::Quote => quote::fields(kind),
98 ElemKind::Bibliography | ElemKind::CiteGroup => bibliography::fields(kind),
99 ElemKind::Document => document::fields(kind),
100 _ => &[],
101 }
102}
103
104/// A field's default: the schema's, or the one the model computes where no `static` can hold it (a
105/// list's marker array, `terms`'s separator, `outline`'s target selector).
106pub fn default_value(kind: ElemKind, name: &str) -> Option<Value> {
107 let computed = match kind {
108 ElemKind::Par | ElemKind::ParLine => par::default_value(kind, name),
109 ElemKind::List | ElemKind::Enum | ElemKind::Terms => list::default_value(kind, name),
110 ElemKind::FootnoteEntry => footnote::default_value(kind, name),
111 ElemKind::Raw => raw::default_value(kind, name),
112 ElemKind::FigureCaption => figure::default_value(kind, name),
113 ElemKind::Outline | ElemKind::OutlineEntry => outline::default_value(kind, name),
114 _ => None,
115 };
116 if computed.is_some() {
117 return computed;
118 }
119 kind.field_id(name).and_then(|id| kind.field_spec(id)).and_then(|s| s.default.to_value())
120}
121
122/// Checks, and where Typst does normalises, a value given for a field: what `construct` applies to an
123/// argument and a `set` rule should apply to its value.
124pub fn cast(kind: ElemKind, name: &str, v: Value) -> Result<Value, CastErr> {
125 match kind {
126 ElemKind::Par | ElemKind::ParLine | ElemKind::Parbreak => par::cast(kind, name, v),
127 ElemKind::Strong | ElemKind::Emph => emph::cast(kind, name, v),
128 ElemKind::Raw | ElemKind::RawLine => raw::cast(kind, name, v),
129 ElemKind::Heading | ElemKind::Title => heading::cast(kind, name, v),
130 ElemKind::List | ElemKind::ListItem | ElemKind::Enum | ElemKind::EnumItem
131 | ElemKind::Terms | ElemKind::TermItem => list::cast(kind, name, v),
132 ElemKind::Link => link::cast(kind, name, v),
133 ElemKind::Ref | ElemKind::Cite => reference::cast(kind, name, v),
134 ElemKind::Footnote | ElemKind::FootnoteEntry => footnote::cast(kind, name, v),
135 ElemKind::Figure | ElemKind::FigureCaption => figure::cast(kind, name, v),
136 ElemKind::Outline | ElemKind::OutlineEntry => outline::cast(kind, name, v),
137 ElemKind::Quote => quote::cast(kind, name, v),
138 ElemKind::Bibliography => bibliography::cast(kind, name, v),
139 ElemKind::Document => document::cast(kind, name, v),
140 ElemKind::CiteGroup => bibliography::cast_group(name, v),
141 _ => Ok(v),
142 }
143}
144
145/// A `set` rule's value for a field, checked as the constructor checks it.
146pub fn cast_field(kind: ElemKind, name: &str, v: Value) -> Outcome<Value> {
147 match cast(kind, name, v) {
148 Ok(v) => Ok(v),
149 Err(e) => Err(err!("{}", e.message(); Input, Invalid)),
150 }
151}
152
153/// Folds a `Fold::Custom` field: `par.justification-limits`, whose `spacing` and `tracking` are each
154/// kept from the outer value where the inner one does not give them.
155pub fn fold(kind: ElemKind, field: &str, inner: Value, outer: Value) -> Outcome<Value> {
156 match (kind, field, &inner, &outer) {
157 (ElemKind::Par, "justification-limits", Value::Dict(i), Value::Dict(o)) => {
158 let mut d = (**o).clone();
159 for (k, v) in i.iter() {
160 d.insert(k, v.clone());
161 }
162 Ok(Value::dict(d))
163 }
164 _ => Ok(inner),
165 }
166}
167
168pub fn construct(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Option<Content>> {
169 match kind {
170 ElemKind::ParLine => Err(engine.error(DiagnosticKind::Type, args.span, "cannot be constructed manually")),
171 ElemKind::Link => link::construct(engine, args).map(Some),
172 ElemKind::Bibliography => bibliography::construct(engine, args).map(Some),
173 ElemKind::Cite => reference::construct_cite(engine, args).map(Some),
174 _ => construct_schema(engine, kind, args).map(Some),
175 }
176}
177
178/// Typst's generated constructor: required positionals in order, an optional positional from the
179/// first argument of a castable type, variadics from the rest, named fields by name; then anything left
180/// over is an unexpected argument. Each value passes the field's `cast`.
181pub fn construct_schema(engine: &mut Engine, kind: ElemKind, args: &mut Args) -> Outcome<Content> {
182 let span = args.span;
183 let mut fields = Vec::new();
184 for (i, spec) in kind.fields().iter().enumerate() {
185 if spec.synthesised || spec.internal {
186 continue;
187 }
188 let id = FieldId(i as u8);
189 if spec.variadic {
190 let mut items = Vec::new();
191 while let Some(p) = args.items.iter().position(|a| a.name.is_none()) {
192 let a = args.items.remove(p);
193 items.push(res!(cast_arg(engine, kind, spec.name, a.value, a.span)));
194 }
195 fields.push((id, Value::array(items)));
196 } else if spec.positional && spec.required {
197 let a = match args.items.iter().position(|a| a.name.is_none()) {
198 Some(p) => args.items.remove(p),
199 None => return Err(engine.error(DiagnosticKind::Type, span, fmt!("missing argument: {}", spec.name))),
200 };
201 fields.push((id, res!(cast_arg(engine, kind, spec.name, a.value, a.span))));
202 } else if spec.positional {
203 let mut taken = None;
204 let mut p = 0;
205 while p < args.items.len() {
206 if args.items[p].name.is_none() {
207 let v = args.items[p].value.clone();
208 match cast(kind, spec.name, v) {
209 Err(CastErr::Type(_)) => (),
210 Err(CastErr::Value(m)) => return Err(engine.error(DiagnosticKind::Type, args.items[p].span, m)),
211 Ok(v) => {
212 taken = Some(v);
213 args.items.remove(p);
214 break;
215 }
216 }
217 }
218 p += 1;
219 }
220 if let Some(v) = taken {
221 fields.push((id, v));
222 }
223 } else {
224 let mut found = None;
225 let mut p = 0;
226 while p < args.items.len() {
227 if args.items[p].name.as_deref() == Some(spec.name) {
228 found = Some(args.items.remove(p));
229 } else {
230 p += 1;
231 }
232 }
233 if let Some(a) = found {
234 fields.push((id, res!(cast_arg(engine, kind, spec.name, a.value, a.span))));
235 }
236 }
237 }
238 res!(finish(engine, args));
239 Ok(Content::new(kind, fields, span))
240}
241
242fn cast_arg(engine: &mut Engine, kind: ElemKind, name: &str, v: Value, span: Span) -> Outcome<Value> {
243 // Typst still takes an array as an enumeration or term list item, with a warning.
244 if matches!(v, Value::Array(_)) && name == "children" {
245 match kind {
246 ElemKind::Enum => engine.warn(DiagnosticKind::Lint, span, "implicit conversion from array to `enum.item` is deprecated"),
247 ElemKind::Terms => engine.warn(DiagnosticKind::Lint, span, "implicit conversion from array to `terms.item` is deprecated"),
248 _ => (),
249 }
250 }
251 match cast(kind, name, v) {
252 Ok(v) => Ok(v),
253 Err(e) => Err(engine.error(DiagnosticKind::Type, span, e.message())),
254 }
255}
256
257/// Refuses any argument left: Typst's `Args::finish`.
258pub fn finish(engine: &mut Engine, args: &mut Args) -> Outcome<()> {
259 match args.items.first() {
260 None => Ok(()),
261 Some(a) => {
262 let span = if a.span.is_detached() { args.span } else { a.span };
263 let msg = match &a.name {
264 Some(n) => fmt!("unexpected argument: {}", n),
265 None => "unexpected argument".to_string(),
266 };
267 Err(engine.error(DiagnosticKind::Type, span, msg))
268 }
269 }
270}
271
272/// Typst's `Synthesize`: fills the fields a show rule sees that only realisation can know (a heading's
273/// resolved level and supplement, a figure's kind and counter, a reference's target). Realisation calls
274/// it once the element has its location and its unset fields are materialised from `styles`.
275pub fn synthesise(engine: &mut Engine, elem: &mut Content, styles: &StyleChain) -> Outcome<()> {
276 // A default no schema constant holds is materialised here, as the chain cannot supply it.
277 if let (Some(kind), Content::Elem(e)) = (elem.kind(), &mut *elem) {
278 let e = e.edit();
279 for (i, spec) in kind.fields().iter().enumerate() {
280 let id = FieldId(i as u8);
281 if !spec.settable || spec.default != crate::eval::content::FieldDefault::Computed
282 || e.fields.iter().any(|(f, _)| *f == id)
283 {
284 continue;
285 }
286 if let Some(v) = default_value(kind, spec.name) {
287 e.fields.push((id, v));
288 }
289 }
290 }
291 match elem.kind() {
292 Some(ElemKind::Heading) => heading::synthesise(engine, elem, styles),
293 Some(ElemKind::Figure) => figure::synthesise(engine, elem, styles),
294 Some(ElemKind::FigureCaption) => figure::synthesise_caption(elem, styles),
295 Some(ElemKind::Ref) => reference::synthesise(engine, elem, styles),
296 Some(ElemKind::Raw) => raw::synthesise(elem, styles),
297 _ => Ok(()),
298 }
299}
300
301/// [`content::derived_field`] for a model element: a heading's `level`, a figure's `kind`.
302pub fn derived_field(elem: &Content, field: FieldId, styles: &StyleChain) -> Outcome<Option<Value>> {
303 let kind = match elem.kind() {
304 Some(k) => k,
305 None => return Ok(None),
306 };
307 let name = match kind.field_spec(field) {
308 Some(spec) => spec.name,
309 None => return Ok(None),
310 };
311 match (kind, name) {
312 (ElemKind::Heading, "level") => Ok(Some(Value::Int(res!(heading::level(elem, styles))))),
313 (ElemKind::Figure, "kind") => Ok(Some(res!(figure::resolved_kind(elem, styles)))),
314 _ => Ok(None),
315 }
316}
317
318/// Typst's `ShowSet`: the styles an element's own default applies to it and its show-rule output,
319/// visible inside a user's `show` rule for it (a heading's size and weight).
320pub fn show_set(elem: &Content, styles: &StyleChain) -> Outcome<Styles> {
321 match elem.kind() {
322 Some(ElemKind::Heading) => heading::show_set(elem, styles),
323 Some(ElemKind::Title) => heading::show_set_title(),
324 Some(ElemKind::Raw) => raw::show_set(elem, styles),
325 Some(ElemKind::Link) => link::show_set(),
326 Some(ElemKind::FootnoteEntry) => footnote::show_set_entry(),
327 Some(ElemKind::Figure) => figure::show_set(),
328 Some(ElemKind::Outline) => outline::show_set(elem, styles),
329 Some(ElemKind::Quote) => quote::show_set(elem, styles),
330 Some(ElemKind::Bibliography) => bibliography::show_set(),
331 Some(ElemKind::Divider) => divider::show_set(),
332 _ => Ok(Styles::new()),
333 }
334}
335
336/// Typst's `Count`: the level at which a realised element steps its own counter, if it does. A heading
337/// steps at its level, a numbered figure, footnote or equation at level one.
338pub fn count_step(elem: &Content) -> Option<usize> {
339 match elem.kind() {
340 Some(ElemKind::Heading) => {
341 if matches!(elem.field("numbering"), None | Some(Value::None)) {
342 return None;
343 }
344 match elem.field("level") {
345 Some(Value::Int(l)) if *l > 0 => Some(*l as usize),
346 _ => {
347 let depth = match elem.field("depth") { Some(Value::Int(d)) => *d, _ => 1 };
348 let offset = match elem.field("offset") { Some(Value::Int(o)) => *o, _ => 0 };
349 Some((depth + offset).max(1) as usize)
350 }
351 }
352 }
353 Some(ElemKind::Figure) => match elem.field("numbering") {
354 None | Some(Value::None) => None,
355 Some(_) => Some(1),
356 },
357 // Only a numbered block equation counts.
358 Some(ElemKind::Equation) => {
359 let block = matches!(elem.field("block"), Some(Value::Bool(true)));
360 match elem.field("numbering") {
361 Some(n) if block && !n.is_none() => Some(1),
362 _ => None,
363 }
364 }
365 Some(ElemKind::Footnote) => match elem.field("body") {
366 Some(Value::Label(_)) => None,
367 _ => Some(1),
368 },
369 _ => None,
370 }
371}
372
373pub fn show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
374 let kind = match elem.kind() {
375 Some(k) => k,
376 None => return Ok(None),
377 };
378 match kind {
379 ElemKind::Par | ElemKind::ParLine | ElemKind::Parbreak => Ok(None),
380 ElemKind::Strong | ElemKind::Emph => emph::show(engine, elem, styles),
381 ElemKind::Raw | ElemKind::RawLine => raw::show(engine, elem, styles),
382 ElemKind::Heading | ElemKind::Title => heading::show(engine, elem, styles),
383 ElemKind::List | ElemKind::ListItem | ElemKind::Enum | ElemKind::EnumItem
384 | ElemKind::Terms | ElemKind::TermItem => list::show(engine, elem, styles),
385 ElemKind::Link => link::show(engine, elem, styles),
386 ElemKind::Ref | ElemKind::Cite => reference::show(engine, elem, styles),
387 ElemKind::Footnote | ElemKind::FootnoteEntry => footnote::show(engine, elem, styles),
388 ElemKind::Figure | ElemKind::FigureCaption => figure::show(engine, elem, styles),
389 ElemKind::Outline | ElemKind::OutlineEntry => outline::show(engine, elem, styles),
390 ElemKind::Quote => quote::show(engine, elem, styles),
391 ElemKind::Bibliography | ElemKind::CiteGroup => bibliography::show(engine, elem, styles),
392 ElemKind::Document => document::show(engine, elem, styles),
393 ElemKind::Divider => divider::show(elem),
394 _ => Err(err!("{} is not a model element", kind.path(); Bug)),
395 }
396}