Oregami
Repositories/oxedyne/fe2o3

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

9.7 KiB, 3 runs

created by r1870400018:63282, 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/reference.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// U5 owns this file: ref and cite. A reference to a label that a bibliography holds is a citation; any
5// other is realised as the target's supplement and number, linked to it, as Typst's `RefElem::realize`.
6// The number is displayed with the target's numbering, trimmed of a pattern's first prefix and its suffix as
7// Typst trims it (`"1."` references as `1`, `"(1)"` as `1`).
8
9use crate::diag::DiagnosticKind;
10use crate::eval::args::Args;
11use crate::eval::content::{
12 Content,
13 ElemKind,
14 FieldDefault,
15 FieldSpec,
16 FieldType,
17};
18use crate::eval::intro::{
19 self,
20 Counter,
21};
22use crate::eval::lib::model::common::{
23 self,
24 choice,
25 expect,
26 to_content,
27 CastErr,
28 K,
29};
30use crate::eval::lib::model::{
31 bibliography,
32 heading,
33 link,
34 lookup,
35};
36use crate::eval::styles::StyleChain;
37use crate::eval::value::{
38 Label,
39 Type,
40 Value,
41};
42use crate::eval::Engine;
43use crate::syntax::Span;
44
45use oxedyne_fe2o3_core::prelude::*;
46
47const ANY: FieldType = FieldType::Any;
48
49static REF: [FieldSpec; 5] = [
50 FieldSpec::required("target", FieldType::Of(Type::Label)),
51 FieldSpec::named("supplement", ANY, FieldDefault::Auto),
52 FieldSpec::named("form", ANY, FieldDefault::Str("normal")),
53 FieldSpec::named("citation", ANY, FieldDefault::None).synthesised(),
54 FieldSpec::named("element", ANY, FieldDefault::None).synthesised(),
55];
56
57static CITE: [FieldSpec; 4] = [
58 FieldSpec::required("key", FieldType::Of(Type::Label)),
59 FieldSpec::named("supplement", ANY, FieldDefault::None),
60 FieldSpec::named("form", ANY, FieldDefault::Str("normal")),
61 FieldSpec::named("style", ANY, FieldDefault::Auto),
62];
63
64pub fn fields(kind: ElemKind) -> &'static [FieldSpec] {
65 match kind {
66 ElemKind::Ref => &REF,
67 ElemKind::Cite => &CITE,
68 _ => &[],
69 }
70}
71
72pub fn cast(kind: ElemKind, name: &str, v: Value) -> Result<Value, CastErr> {
73 match (kind, name) {
74 (ElemKind::Ref, "target") | (ElemKind::Cite, "key") => expect(&v, &[K::Label]).map(|_| v),
75 (ElemKind::Ref, "supplement") => heading::supplement(v),
76 (ElemKind::Ref, "form") => choice(&v, &["normal", "page"], false, false).map(|_| v),
77 (ElemKind::Cite, "supplement") => match v {
78 Value::None => Ok(v),
79 other => expect(&other, &[K::Content, K::None]).map(|_| to_content(other)),
80 },
81 (ElemKind::Cite, "form") => choice(&v, &["normal", "prose", "full", "author", "year"], false, true)
82 .map(|_| v),
83 (ElemKind::Cite, "style") => match &v {
84 Value::Auto => Ok(v),
85 Value::Str(s) => bibliography::style_name(s).map(|_| bibliography::style_value(s)),
86 other => Err(CastErr::Type(common::mismatch("string or auto", other))),
87 },
88 _ => Ok(v),
89 }
90}
91
92/// `cite(key, ..)`: the schema walk, with a named style checked against the styles Austenite sets.
93pub fn construct_cite(engine: &mut Engine, args: &mut Args) -> Outcome<Content> {
94 super::construct_schema(engine, ElemKind::Cite, args)
95}
96
97/// The citation a reference to a bibliography key stands for: `cite(target)`, with the reference's
98/// content supplement.
99fn citation(elem: &Content, styles: &StyleChain) -> Outcome<Content> {
100 let target = elem.field("target").cloned().unwrap_or(Value::None);
101 let supplement = match res!(common::get(elem, styles, "supplement")) {
102 Value::Content(c) => Value::Content(c),
103 _ => Value::None,
104 };
105 common::raw_elem(ElemKind::Cite, elem.span(), vec![("key", target), ("supplement", supplement)])
106}
107
108pub fn synthesise(engine: &mut Engine, elem: &mut Content, styles: &StyleChain) -> Outcome<()> {
109 let cite = res!(citation(elem, styles));
110 elem.set(res!(common::fid(ElemKind::Ref, "citation")), Value::Content(cite));
111 let mut found = Value::None;
112 if let Some(Value::Label(l)) = elem.field("target") {
113 let l = l.clone();
114 if !lookup::bib_has(engine, &l) {
115 // An absent or ambiguous label is the show's error to raise, not synthesis's.
116 let before = engine.diags.len();
117 match lookup::label_opt(engine, &l, elem.span()) {
118 Ok(Some(t)) => found = Value::Content(t),
119 Ok(None) => (),
120 Err(_) => engine.diags.truncate(before),
121 }
122 }
123 }
124 elem.set(res!(common::fid(ElemKind::Ref, "element")), found);
125 Ok(())
126}
127
128pub fn show(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Option<Content>> {
129 match elem.kind() {
130 Some(ElemKind::Cite) => bibliography::show_cite(engine, elem, styles).map(Some),
131 _ => show_ref(engine, elem, styles).map(Some),
132 }
133}
134
135fn show_ref(engine: &mut Engine, elem: &Content, styles: &StyleChain) -> Outcome<Content> {
136 let span = elem.span();
137 let target = match elem.field("target") {
138 Some(Value::Label(l)) => l.clone(),
139 _ => return Err(engine.error(DiagnosticKind::Type, span, "missing argument: target")),
140 };
141 let form = res!(common::get(elem, styles, "form"));
142 if matches!(&form, Value::Str(s) if s.as_str() == "page") {
143 // The page the target lies on, in the page numbering there, after the page's supplement.
144 let found = res!(lookup::label(engine, &target, span));
145 let loc = res!(located(engine, &found, span));
146 let page = crate::eval::intro::Counter { key: crate::eval::intro::CounterKey::Page };
147 let numbering = match res!(intro::page_numbering(engine, loc)) {
148 Value::None => return Err(engine.error_hint(DiagnosticKind::Type, span,
149 "cannot reference without page numbering",
150 "you can enable page numbering with `#set page(numbering: \"1\")`")),
151 n => n,
152 };
153 let numbers = res!(lookup::display_counter_trimmed(engine, &page, loc, &numbering, span));
154 let supplement = match res!(common::get(elem, styles, "supplement")) {
155 Value::Auto => common::text(common::local(styles, "page")),
156 other => res!(heading::resolve_supplement(engine, &other, styles, "page", &found))
157 .unwrap_or_else(Content::empty),
158 };
159 let content = if supplement.is_empty() {
160 numbers
161 } else {
162 common::seq(vec![supplement, common::text("\u{a0}"), numbers])
163 };
164 return link::to_location(common::spanned(content, span), loc);
165 }
166 if lookup::bib_has(engine, &target) {
167 let before = engine.diags.len();
168 let found = lookup::label_opt(engine, &target, span);
169 engine.diags.truncate(before);
170 if let Ok(Some(e)) = found {
171 let name = e.kind().map(|k| k.name()).unwrap_or("content");
172 return Err(engine.error_hint(DiagnosticKind::Type, span,
173 fmt!("label `<{}>` occurs both in the document and a bibliography", target.as_str()),
174 fmt!("change either the {}'s label or the bibliography key to resolve the ambiguity", name)));
175 }
176 return citation(elem, styles);
177 }
178 let found = res!(lookup::label(engine, &target, span));
179 let kind = match found.kind() {
180 Some(k) => k,
181 None => return Err(engine.error(DiagnosticKind::Type, span, "cannot reference sequence")),
182 };
183 if kind == ElemKind::Footnote {
184 // A reference to a footnote is the footnote's mark again, pointing at the same note.
185 let mut note = found.clone();
186 note.set(res!(common::fid(ElemKind::Footnote, "body")), Value::Label(target.clone()));
187 if let Content::Elem(e) = &mut note {
188 let e = e.edit();
189 e.location = None;
190 e.prepared = false;
191 e.label = None;
192 e.span = span;
193 }
194 return Ok(note);
195 }
196 let (counter, default_supplement) = match kind {
197 ElemKind::Heading | ElemKind::Figure => (res!(refable_counter(&found)), found.field("supplement").cloned()),
198 ElemKind::Equation => (lookup::elem_counter(ElemKind::Equation), found.field("supplement").cloned()),
199 ElemKind::Image | ElemKind::Table | ElemKind::Raw => return Err(engine.error(DiagnosticKind::Type, span, fmt!(
200 "cannot reference {} directly, try putting it into a figure", kind.name()))),
201 _ => return Err(engine.error(DiagnosticKind::Type, span, fmt!("cannot reference {}", kind.name()))),
202 };
203 let numbering = match found.field("numbering") {
204 Some(Value::None) | None => {
205 let set = if kind == ElemKind::Equation { "math.equation" } else { kind.name() };
206 return Err(engine.error_hint(DiagnosticKind::Type, span,
207 fmt!("cannot reference {} without numbering", kind.name()),
208 fmt!("you can enable {} numbering with `#set {}(numbering: \"1.\")`", kind.name(), set)));
209 }
210 Some(n) => n.clone(),
211 };
212 let default_supplement = match default_supplement {
213 Some(Value::Content(c)) => c,
214 Some(Value::Auto) | None if kind == ElemKind::Equation => common::text(common::local(styles, "equation")),
215 _ => Content::empty(),
216 };
217 let loc = res!(located(engine, &found, span));
218 let numbers = res!(lookup::display_counter_trimmed(engine, &counter, loc, &numbering, span));
219 let supplement = match res!(common::get(elem, styles, "supplement")) {
220 Value::Auto => default_supplement,
221 other => res!(heading::resolve_supplement(engine, &other, styles, "heading", &found))
222 .unwrap_or_else(Content::empty),
223 };
224 let mut content = numbers;
225 if !supplement.is_empty() {
226 content = common::seq(vec![supplement, common::text("\u{a0}"), content]);
227 }
228 link::to_location(common::spanned(content, span), loc)
229}
230
231fn located(engine: &mut Engine, e: &Content, span: Span) -> Outcome<crate::eval::locate::Location> {
232 match e.location() {
233 Some(l) => Ok(l),
234 None => Err(engine.error(DiagnosticKind::Type, span, "cannot reference an element without a location")),
235 }
236}
237
238/// The counter a referenceable element counts on: a figure's own (`figure.where(kind: ..)`), else its
239/// kind's.
240fn refable_counter(e: &Content) -> Outcome<Counter> {
241 if let Some(Value::Counter(c)) = e.field("counter") {
242 return Ok((**c).clone());
243 }
244 match e.kind() {
245 Some(k) => Ok(lookup::elem_counter(k)),
246 None => Err(err!("a referenced element has no kind"; Bug)),
247 }
248}
249
250/// Is `l` a bibliography key rather than a document label? For the quote attribution and citations.
251pub fn is_bib_key(engine: &mut Engine, l: &Label) -> bool { lookup::bib_has(engine, l) }