flm_core/stdlib/features/defterm/rules.rs
1//! The general lowering rules of the [`defterm`](super) feature, each the
2//! default on every backend: a term definition becomes a block that opens
3//! with its lead-in ([`DefinitionRule`]), and a term link becomes a link to
4//! its term definition ([`TermRule`]).
5//!
6//! # A term definition
7//!
8//! [`DefinitionRule`] writes a term definition as a
9//! [`flm.pres.block`](crate::stdlib::backends::pres::BLOCK) of role
10//! [`DEFTERM`], around the term definition's body laid out as blocks. The
11//! block carries the anchor of the term definition's reference point where
12//! the references feature computed one. The lead-in is placed at the start of
13//! the body's first paragraph (or in a paragraph of its own, where the body
14//! opens with another block or is empty) as a run-in decoration, which each
15//! backend sets as it sets a run-in heading (see [`lead_in`](super::lead_in)
16//! and [decorations](crate::stdlib::backends::pres::Decoration)). The
17//! term definition's fields, `\label{…}` and `\aliasterm{…}`, label it and are
18//! not written.
19//!
20//! # A term link
21//!
22//! [`TermRule`] writes the text of a term link (what its author wrote in the
23//! braces, lowered as inline content) in one of three ways:
24//!
25//! - inside the definition of its own term
26//! ([`in_own_definition`](super::in_own_definition)), as when a term
27//! definition uses its own term: a
28//! [`flm.pres.span`](crate::stdlib::backends::pres::SPAN) of role
29//! [`TERM_ROLE`], and no link, because it is the term being defined;
30//! - elsewhere, where the references feature resolved it: a
31//! [`flm.pres.link`](crate::stdlib::backends::pres::LINK) of the kind
32//! [`TERM_LINK_KIND`] to the term definition's anchor;
33//! - where nothing resolved it: a span styled as an unresolved reference,
34//! which the references feature has already reported as
35//! `flm.refs.unresolved`.
36//!
37//! Where the registry holds no references feature there is no resolution to
38//! read, and a term link outside its own term's definition is its text alone.
39
40use std::sync::Arc;
41
42use techy::core::node::{BuildId, NodeRef};
43use techy::error::Diagnostic;
44
45use crate::core::lowering::{
46 DefaultMark, Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl, LoweringRule,
47};
48use crate::core::run::MissingEntry;
49use crate::lang::Flm;
50use crate::model::aspects::PointId;
51use crate::model::names::{CapName, ElementName, Name};
52use crate::stdlib::backends::lowering::{lower_arg_named_or_nothing, lower_blocks_with_edges};
53use crate::stdlib::backends::pres::{
54 self, BlockPayload, LinkPayload, SpanPayload, SpanStyle, spelling_identity,
55};
56use crate::stdlib::features::refs::{ANCHORS, REF_RESOLUTIONS, Resolution, SiteId};
57
58use super::diagnostics::EmptyTerm;
59use super::html::STYLE;
60use super::elements::{
61 DEFTERM, SHOWN_ARG, TERM, TERM_ARG, decide_term,
62};
63use super::lead_in::{LeadIn, stage_lead_in};
64
65/// The name of the term definition's general lowering rule,
66/// `flm.defterm.lower.default` ([`DefinitionRule`]).
67pub const DEFINITION_RULE: &str = "flm.defterm.lower.default";
68
69/// The name of the term link's general lowering rule,
70/// `flm.term.lower.default` ([`TermRule`]).
71pub const TERM_RULE: &str = "flm.term.lower.default";
72
73/// The kind written on the link that a term link produces, `term`: it tells
74/// a backend, and a stylesheet, that the link leads to the definition of a
75/// term.
76pub const TERM_LINK_KIND: &str = "term";
77
78/// The role of the span that a term link inside the definition of its own
79/// term is written as, `flm.defterm.term`.
80pub const TERM_ROLE: &str = "flm.defterm.term";
81
82/// The lowering rule [`DEFINITION_RULE`]: a term definition as a block
83/// opening with its lead-in. See the [module
84/// documentation](self#a-term-definition).
85///
86/// A term definition whose term is empty or only whitespace (`~` and `\ ` are
87/// part of a term as written) is reported as [`EmptyTerm`] and still written.
88///
89/// The rule requires the feature's style identifier [`STYLE`]
90/// (`flm.defterm.style`) at every term definition it stages, which each
91/// backend resolves as it resolves requirements: the stylesheet on the `html`
92/// backend, the definition pieces delivering it on the `latex-rendered`
93/// backend, nothing on the `text` backend.
94#[derive(Debug)]
95pub struct DefinitionRule {
96 lead_in: Arc<LeadIn>,
97}
98
99impl Lower for DefinitionRule {
100 fn lower(
101 &self,
102 node: NodeRef<'_, Flm>,
103 cx: &mut LowerCx<'_>,
104 lw: &mut dyn Lowerer,
105 ) -> Result<Lowering, LowerError> {
106 let term = node.argument_content_nodes_named(TERM_ARG).ok().flatten();
107 if term.is_none_or(|content| spelling_identity(content.iter()).is_empty()) {
108 lw.error(EmptyTerm { what: String::from("defterm") }, node.span().clone());
109 }
110 // The anchors table is absent in a registry holding no references
111 // feature: the definition is written with no anchor.
112 let point = PointId { addr: lw.addr(), index: 0 };
113 let anchor = lw.get(ANCHORS)?.and_then(|anchors| anchors.id(point)).map(String::from);
114 lw.require(&Name::from(STYLE));
115 let lead_in = stage_lead_in(&self.lead_in, &node, cx, lw)?;
116 let body: Vec<NodeRef<'_, Flm>> =
117 node.body().map(|body| body.iter().collect()).unwrap_or_default();
118 let children = lower_blocks_with_edges(cx, lw, &body, lead_in, Vec::new())?;
119 let payload = BlockPayload {
120 role: Some(Name::from(DEFTERM)),
121 kinds: Vec::new(),
122 anchor,
123 doc_role: None,
124 };
125 let block = lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, children)?;
126 Ok(Lowering::Emit(vec![block]))
127 }
128}
129
130/// The term definition's general lowering rule, [`DEFINITION_RULE`], the
131/// default on every backend, writing the lead-in that `lead_in` configures.
132/// The rule declares that it produces the decoration and the span around the
133/// lead-in only where a lead-in is configured, so that a registry in which
134/// none can occur does not require its backend to render them.
135pub(super) fn definition_rule(lead_in: Arc<LeadIn>) -> LoweringRule {
136 let mut decl =
137 LoweringDecl::new().reads_opt(ANCHORS).produces(pres::BLOCK).produces(pres::PAR);
138 if lead_in.is_set() {
139 decl = decl.produces(pres::SPAN).produces(pres::DECO_RUNIN);
140 }
141 LoweringRule::new(
142 DEFINITION_RULE,
143 DEFTERM,
144 decl,
145 Arc::new(DefinitionRule { lead_in }),
146 DefaultMark::Everywhere,
147 )
148 .docs(
149 "a term definition lowers to `flm.pres.block` of role `flm.defterm` carrying its \
150 anchor, around its body's blocks; the lead-in is a `flm.pres.deco.runin` decoration \
151 at the start of the first paragraph",
152 )
153}
154
155/// Stages `body` inside a span carrying `payload`.
156fn span(
157 cx: &mut LowerCx<'_>,
158 lw: &mut dyn Lowerer,
159 payload: SpanPayload,
160 body: Vec<BuildId>,
161) -> Result<Vec<BuildId>, LowerError> {
162 Ok(vec![lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?])
163}
164
165/// The lowering rule [`TERM_RULE`]: a term link as a link to its term
166/// definition. See the [module documentation](self#a-term-link).
167///
168/// A term link whose term is empty or only whitespace (`~` and `\ ` are part
169/// of a term as written) is reported as [`EmptyTerm`] and shows its text
170/// marked as unresolved. A term link whose term holds a placeholder in the
171/// template of a kept definition ([kept
172/// definitions](crate::stdlib::features::userdefs::kept)) shows its text and reports
173/// nothing. A resolution that the resolutions table does not hold (content
174/// that nobody resolved, or a synthesized value that its consumer did not
175/// bring up to date through [value
176/// catch-up](crate::guide::concepts_overview#value-catch-up)) is reported at
177/// the node as `flm.run.missing-entry`, and the rule then fails.
178///
179/// Where the term link is inside the definition of its own term, the rule
180/// requires the feature's style identifier [`STYLE`]
181/// (`flm.defterm.style`), which each backend resolves as it resolves
182/// requirements: the stylesheet on the `html` backend, the definition pieces
183/// delivering it on the `latex-rendered` backend, nothing on the `text`
184/// backend.
185#[derive(Debug, Default, Clone, Copy)]
186pub struct TermRule;
187
188impl Lower for TermRule {
189 fn lower(
190 &self,
191 node: NodeRef<'_, Flm>,
192 cx: &mut LowerCx<'_>,
193 lw: &mut dyn Lowerer,
194 ) -> Result<Lowering, LowerError> {
195 let decision = decide_term(&node);
196 // The author's text is what this shows in every case, so it is
197 // lowered once, before anything is looked up. A text a parse recovery
198 // left absent lowers to nothing and is not reported a second time.
199 let shown = lower_arg_named_or_nothing(cx, lw, &node, SHOWN_ARG)?;
200 let unresolved = || SpanPayload {
201 style: Some(SpanStyle::UnresolvedReference),
202 ..SpanPayload::default()
203 };
204 let Some(decision) = decision else {
205 // A template kept rather than expanded may hold a placeholder
206 // where the term stands: that names nothing and is not
207 // reported. Anything else naming nothing is an empty term.
208 let written = |name: &str| node.argument_content_nodes_named(name).ok().flatten();
209 let blank = [super::elements::REF_ARG, SHOWN_ARG].iter().all(|name| {
210 written(name).is_none_or(|content| spelling_identity(content.iter()).is_empty())
211 });
212 if !blank {
213 return Ok(Lowering::Emit(shown));
214 }
215 lw.error(EmptyTerm { what: String::from("\\term") }, node.span().clone());
216 return Ok(Lowering::Emit(span(cx, lw, unresolved(), shown)?));
217 };
218 if decision.in_own_definition {
219 lw.require(&Name::from(STYLE));
220 let payload = SpanPayload { role: Some(Name::from(TERM_ROLE)), ..SpanPayload::default() };
221 return Ok(Lowering::Emit(span(cx, lw, payload, shown)?));
222 }
223 let site = SiteId { addr: lw.addr(), index: 0 };
224 let resolution = match lw.get(REF_RESOLUTIONS)? {
225 // No references feature: nothing resolves, and nothing is a
226 // fault. The link is its text.
227 None => return Ok(Lowering::Emit(shown)),
228 Some(table) => table.site(site).cloned(),
229 };
230 let staged = match resolution {
231 Some(Resolution::Resolved { href, .. }) => {
232 let payload = LinkPayload {
233 href,
234 kind: TERM_LINK_KIND.into(),
235 doc_role: None,
236 label: None,
237 shows_target: false,
238 };
239 vec![lw.pres_with(cx, &ElementName::from(pres::LINK), payload, shown)?]
240 }
241 Some(Resolution::Unresolved { .. }) => span(cx, lw, unresolved(), shown)?,
242 None => {
243 let table = CapName::from(REF_RESOLUTIONS.name());
244 let producer = lw
245 .producer_of(&table)
246 .map(|stage| stage.to_string())
247 .unwrap_or_else(|| "nobody".to_string());
248 lw.diagnose(Diagnostic::error(
249 MissingEntry { table: table.to_string(), producer, element: TERM.to_string() },
250 node.span().clone(),
251 ));
252 return Err(LowerError::structure("the term link has no resolution entry"));
253 }
254 };
255 Ok(Lowering::Emit(staged))
256 }
257}
258
259/// The declaration of every rule that writes a term link as [`TermRule`]
260/// does: it reads the references feature's resolutions table optionally and
261/// produces a link or a span.
262pub(super) fn term_decl() -> LoweringDecl {
263 LoweringDecl::new().reads_opt(REF_RESOLUTIONS).produces(pres::LINK).produces(pres::SPAN)
264}
265
266/// The term link's general lowering rule, [`TERM_RULE`], the default on
267/// every backend. It reads the references feature's resolutions table
268/// optionally, so that a registry without that feature still renders a term
269/// link, as its text.
270pub(super) fn term_rule() -> LoweringRule {
271 LoweringRule::new(
272 TERM_RULE,
273 TERM,
274 term_decl(),
275 Arc::new(TermRule),
276 DefaultMark::Everywhere,
277 )
278 .docs(
279 "a resolved term link lowers to `flm.pres.link` of kind `term` around the text written \
280 for it, an unresolved one to an unresolved-styled `flm.pres.span`, one inside the \
281 definition of its own term to `flm.pres.span` of role `flm.defterm.term`",
282 )
283}