flm_core/stdlib/features/annotations/lower.rs
1//! The lowering rules of the `annotations` feature that lower an annotation
2//! into the presentation vocabulary: the general rule, the default on every
3//! backend that has no rule of its own, and the `text` backend's rule.
4//!
5//! **The general rule** ([`RULE`](super::RULE), [`AnnotationRule`]) lowers an
6//! annotation, a node of an annotator's command or a cut part of one, to a
7//! `flm.pres.span` around inline content, or to a `flm.pres.block` around the
8//! one block that a cut part holds where the cut part is placed among blocks.
9//! The span or block has the role
10//! [`HIGHLIGHT_ROLE`](super::HIGHLIGHT_ROLE) or
11//! [`COMMENT_ROLE`](super::COMMENT_ROLE), according to the annotation's
12//! [form](super::form_of), and the two kind tokens `<command>` and
13//! `annotator-<n>`:
14//!
15//! ```text
16//! flm.pres.span { role: flm.annotations.highlight, kinds: [phf, annotator-0] }
17//! ├ flm.pres.deco.margin
18//! │ └ flm.pres.span { role: flm.annotations.initials, kinds: [phf, annotator-0] }
19//! │ └ "PhF"
20//! └ the passage, lowered
21//! ```
22//!
23//! A **cut part** of a cut annotation also carries the kind token
24//! `mark-continues` when it is not the last cut part, and `mark-continued`
25//! when it is not the first
26//! ([`MARK_CONTINUES_KIND`](super::MARK_CONTINUES_KIND),
27//! [`MARK_CONTINUED_KIND`](super::MARK_CONTINUED_KIND)), for a highlight and
28//! a comment alike; the initials' span does not carry them. A comment cut in
29//! two:
30//!
31//! ```text
32//! flm.pres.span { role: flm.annotations.comment, kinds: [phf, annotator-0, mark-continues] }
33//! ├ flm.pres.deco.margin …
34//! └ the first paragraph's part of the remark
35//! flm.pres.span { role: flm.annotations.comment, kinds: [phf, annotator-0, mark-continued] }
36//! └ the second paragraph's part of the remark
37//! ```
38//!
39//! The margin decoration that holds the **initials** is the first node of
40//! the span's or the block's own content. The lowering driver therefore
41//! moves it into the node's attached slot and leaves its decoration mark at
42//! the start of the content, where the annotation starts
43//! ([decorations](crate::guide::concepts_overview#decorations-roles-and-kinds)).
44//! The rule stages it when the annotator has initials and the node is a first
45//! cut part: a node that was not cut, or a cut part whose record says it is
46//! the first. Every cut part carries the annotator's kind tokens, so that an
47//! output colors every cut part alike.
48//!
49//! **The text backend's rule** ([`TEXT_RULE`](super::TEXT_RULE),
50//! [`AnnotationTextRule`]) lowers a highlight as the general rule does, and a
51//! comment with its brackets written as text and no decoration: `[`, the
52//! initials and `: ` before the remark, and `]` after it: `[PhF: fix this]`,
53//! or `[fix this]` for an annotator with no initials. A cut comment opens its
54//! bracket on its first cut part and closes it on its last.
55//!
56//! **Hidden.** When [`AnnotationsRenderOptions::hidden`] is true, both rules stage
57//! nothing of the annotation's own: a highlight lowers to its passage's
58//! lowered nodes, and a comment to nothing.
59//!
60//! **The style identifier.** Unless annotations are hidden, both rules
61//! require the feature's style identifier [`STYLE`]
62//! (`flm.annotations.style`) at every annotation they write; each backend
63//! resolves it as it resolves requirements (the stylesheet on the `html`
64//! backend, the definition pieces delivering it on the `latex-rendered`
65//! backend, nothing on the `text` backend).
66
67use techy::core::node::{BuildId, NodeRef};
68
69use crate::core::lowering::{Lower, LowerCx, LowerError, Lowerer, Lowering, LoweringDecl};
70use crate::lang::rewrites::blocks::stands_in_blocks;
71use crate::lang::Flm;
72use crate::model::aspects::{block_role_of, BlockRole};
73use crate::model::element::element_value;
74use crate::model::names::{ElementName, Name};
75use crate::stdlib::backends::pres::{self, BlockPayload, DecorationPayload, SpanPayload};
76use crate::stdlib::backends::pres::read::payload_of;
77
78use super::config::AnnotationsRenderOptions;
79use super::cut::AnnotationPiece;
80use super::html::STYLE;
81use super::parser::{form_of, Form};
82use super::{
83 annotator_kind, AnnotationElement, COMMENT_ROLE, MARK_CONTINUED_KIND, MARK_CONTINUES_KIND, HIGHLIGHT_ROLE, INITIALS_ROLE,
84 TEXT_ARG,
85};
86
87/// How a comment's brackets are written: the only difference between the
88/// general rule and the text backend's rule.
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90enum Brackets {
91 /// No bracket: the initials are a margin decoration. The general rule.
92 None,
93 /// `[`, the initials and `: ` as text before the remark, `]` after it,
94 /// and no decoration. The text backend's rule.
95 Text,
96}
97
98/// Returns the declaration shared by the rules that lower an annotation into
99/// the presentation vocabulary: they read the render option
100/// [`AnnotationsRenderOptions`], and produce the span, the block and the
101/// margin decoration.
102pub(super) fn decl() -> LoweringDecl {
103 LoweringDecl::new()
104 .option::<AnnotationsRenderOptions>()
105 .produces(pres::SPAN)
106 .produces(pres::BLOCK)
107 .produces(pres::DECO_MARGIN)
108}
109
110/// The implementation of the general rule [`RULE`](super::RULE), the default
111/// on every backend that has no rule of its own for an annotation.
112///
113/// It lowers an annotation, a node of an annotator's command or a cut part
114/// of one, to a `flm.pres.span` around inline content, or to a
115/// `flm.pres.block` around the one block that a cut part holds where the cut
116/// part is placed among blocks. The span or block has the role
117/// [`HIGHLIGHT_ROLE`] or [`COMMENT_ROLE`], according to the annotation's
118/// [form](form_of), and the two kind tokens `<command>` and `annotator-<n>`:
119///
120/// ```text
121/// flm.pres.span { role: flm.annotations.highlight, kinds: [phf, annotator-0] }
122/// ├ flm.pres.deco.margin
123/// │ └ flm.pres.span { role: flm.annotations.initials, kinds: [phf, annotator-0] }
124/// │ └ "PhF"
125/// └ the passage, lowered
126/// ```
127///
128/// A cut part of a cut annotation also carries the kind token
129/// [`MARK_CONTINUES_KIND`](super::MARK_CONTINUES_KIND) when it is not the
130/// last cut part, and [`MARK_CONTINUED_KIND`](super::MARK_CONTINUED_KIND)
131/// when it is not the first, so that a stylesheet can open a comment's
132/// brackets on its first cut part and close them on its last; a node that
133/// was not cut carries neither.
134///
135/// The margin decoration that holds the **initials** is the first node of the
136/// span's or the block's own content, so that the lowering driver moves it
137/// into the node's attached slot and leaves its decoration mark at the start
138/// of the content, where the annotation starts. The rule stages it when the
139/// annotator has initials and the node is a first cut part: a node that was
140/// not cut, or a cut part whose [record](super::AnnotationPiece) says it is
141/// the first. Every cut part carries the annotator's kind tokens, so that an
142/// output shows every cut part alike.
143///
144/// When [`AnnotationsRenderOptions::hidden`] is true, it stages nothing of the
145/// annotation's own: a highlight lowers to its passage's lowered nodes, and a
146/// comment to nothing.
147///
148/// # Errors
149///
150/// [`LowerError`] when the node carries no [`AnnotationElement`] or no
151/// argument group, and
152/// any error from reading the render option or lowering the content.
153#[derive(Debug, Default, Clone, Copy)]
154pub struct AnnotationRule;
155
156impl Lower for AnnotationRule {
157 fn lower(
158 &self,
159 node: NodeRef<'_, Flm>,
160 cx: &mut LowerCx<'_>,
161 lw: &mut dyn Lowerer,
162 ) -> Result<Lowering, LowerError> {
163 lower_annotation(&node, cx, lw, Brackets::None)
164 }
165}
166
167/// The implementation of the text backend's rule,
168/// [`TEXT_RULE`](super::TEXT_RULE), the default on that backend only.
169///
170/// It lowers a highlight as [`AnnotationRule`] does, and a comment to the
171/// same span or block, with its brackets written as text and no decoration:
172/// `[`, the initials and `: ` before the remark, and `]` after it:
173/// `[PhF: fix this]`, or `[fix this]` for an annotator with no initials. A
174/// cut comment opens its bracket on its first cut part and closes it on its
175/// last; the cut parts between them have no bracket. When
176/// [`AnnotationsRenderOptions::hidden`] is true, it stages what
177/// [`AnnotationRule`] stages.
178///
179/// # Errors
180///
181/// As [`AnnotationRule`].
182#[derive(Debug, Default, Clone, Copy)]
183pub struct AnnotationTextRule;
184
185impl Lower for AnnotationTextRule {
186 fn lower(
187 &self,
188 node: NodeRef<'_, Flm>,
189 cx: &mut LowerCx<'_>,
190 lw: &mut dyn Lowerer,
191 ) -> Result<Lowering, LowerError> {
192 lower_annotation(&node, cx, lw, Brackets::Text)
193 }
194}
195
196/// Lowers the annotation `node`, writing a comment's brackets as `brackets`
197/// says. Both rules of this module call it, so that what they write differs
198/// only in a comment's brackets.
199fn lower_annotation(
200 node: &NodeRef<'_, Flm>,
201 cx: &mut LowerCx<'_>,
202 lw: &mut dyn Lowerer,
203 brackets: Brackets,
204) -> Result<Lowering, LowerError> {
205 let value = element_value::<AnnotationElement>(node)
206 .ok_or_else(|| LowerError::structure("an annotation without its element's data"))?;
207 let form = form_of(node).ok_or_else(|| LowerError::structure("an annotation without its argument"))?;
208 let hidden = lw.option::<AnnotationsRenderOptions>()?.hidden;
209 if hidden {
210 return Ok(Lowering::Emit(match form {
211 Form::Highlight => lw.lower_arg_named(cx, node, TEXT_ARG)?,
212 Form::Comment => Vec::new(),
213 }));
214 }
215 lw.require(&Name::from(STYLE));
216 let record = payload_of::<AnnotationPiece>(node).copied();
217 let first = record.is_none_or(|piece| piece.is_first());
218 let last = record.is_none_or(|piece| piece.is_last());
219 let kinds = vec![Name::from(value.annotator.command.as_str()), annotator_kind(value.number)];
220 // The piece's own kinds: the annotator's, then where the piece stands in
221 // the cut annotation; the initials' span carries the annotator's alone.
222 let mut piece_kinds = kinds.clone();
223 if !last {
224 piece_kinds.push(Name::from(MARK_CONTINUES_KIND));
225 }
226 if !first {
227 piece_kinds.push(Name::from(MARK_CONTINUED_KIND));
228 }
229 let initials = if first { value.annotator.initials.as_deref() } else { None };
230 let mut body = Vec::new();
231 let mut trailing = Vec::new();
232 match (form, brackets) {
233 (Form::Comment, Brackets::Text) => {
234 if first {
235 let opening = match initials {
236 Some(initials) => format!("[{initials}: "),
237 None => String::from("["),
238 };
239 body.push(lw.text(cx, &opening)?);
240 }
241 if last {
242 trailing.push(lw.text(cx, "]")?);
243 }
244 }
245 (Form::Highlight, _) | (Form::Comment, Brackets::None) => {
246 if let Some(initials) = initials {
247 body.push(stage_initials(cx, lw, initials, &kinds)?);
248 }
249 }
250 }
251 body.extend(lw.lower_arg_named(cx, node, TEXT_ARG)?);
252 body.extend(trailing);
253 let role = Some(Name::from(match form {
254 Form::Highlight => HIGHLIGHT_ROLE,
255 Form::Comment => COMMENT_ROLE,
256 }));
257 let staged = if matches!(block_role_of(node), BlockRole::Block) && stands_in_blocks(node, lw.layout()) {
258 let payload = BlockPayload { role, kinds: piece_kinds, anchor: None, doc_role: None };
259 lw.pres_with(cx, &ElementName::from(pres::BLOCK), payload, body)?
260 } else {
261 let payload = SpanPayload { role, kinds: piece_kinds, ..SpanPayload::default() };
262 lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, body)?
263 };
264 Ok(Lowering::Emit(vec![staged]))
265}
266
267/// Stages the margin decoration that holds `initials`: a
268/// `flm.pres.deco.margin` holding one `flm.pres.span` of role
269/// [`INITIALS_ROLE`] with the annotation's kind tokens `kinds`, which holds
270/// the initials as text.
271fn stage_initials(
272 cx: &mut LowerCx<'_>,
273 lw: &mut dyn Lowerer,
274 initials: &str,
275 kinds: &[Name],
276) -> Result<BuildId, LowerError> {
277 let text = lw.text(cx, initials)?;
278 let payload = SpanPayload { role: Some(Name::from(INITIALS_ROLE)), kinds: kinds.to_vec(), ..SpanPayload::default() };
279 let span = lw.pres_with(cx, &ElementName::from(pres::SPAN), payload, vec![text])?;
280 lw.pres_with(cx, &ElementName::from(pres::DECO_MARGIN), DecorationPayload, vec![span])
281}