flm_core/stdlib/features/annotations/parser.rs
1//! The parser of an annotator's one argument, and the function that reads
2//! which form an annotation was written in.
3//!
4//! An annotator's command takes one argument, written in one of three forms
5//! that the parser tells apart by the first character after the command and
6//! any whitespace and source comments that follow it:
7//!
8//! - `{` — a braced group, `\phf{…}`: a **highlight** of what the braces hold;
9//! - `[` — a bracketed group, `\phf[…]`: a **comment**, the brackets holding
10//! the remark;
11//! - anything else — the content up to the command `\endphf` (`end` followed
12//! by the command's name), `\phf … \endphf`: a **highlight** of that
13//! content.
14//!
15//! In every form, the argument is built as **one group node** holding the
16//! content, and the group records the delimiters as they were read: `{` and
17//! `}`; `[` and `]`; or no opening delimiter and `\endphf` as the closing
18//! one. [`form_of`] reads the form from that record, and the recomposed
19//! LaTeX writes the delimiters back from it; both read the record with the
20//! same function ([`delimiters_of`]).
21
22use std::cell::Cell;
23use std::fmt;
24use std::sync::Arc;
25
26use techy::core::constructs::{
27 scan_argument_noise, ArgumentParser, ChildStateSpec, ConstructParserResult,
28 GroupArgumentParser, OptionalGroupArgumentParser, ParseContext, ParsedArgumentNodes,
29 StopCause, StopSpec, TokenStopKind,
30};
31use techy::core::node::{ContentNodes, GroupData, NodeBuildError, NodeKind, NodeRef};
32use techy::core::specs::ArgumentSpec;
33use techy::core::token::{GroupRule, Token, TokenKind, TokenReader};
34use techy::error::{HookFailed, ParseError};
35use techy::source::TextContent;
36
37use crate::lang::mint::{DefinitionShape, FlmArgumentParser};
38use crate::lang::{Flm, FlmGroupType, FlmOrigin, FlmSpan};
39
40use super::diagnostics::Unterminated;
41use super::TEXT_ARG;
42
43/// The name of the command that ends an environment, `\end{…}`: the
44/// language's environments are those of techy's built-in package, whose
45/// closing command is `end`.
46const ENVIRONMENT_END: &str = "end";
47
48/// The kind of an annotation, highlight or comment, as [`form_of`] reads it
49/// from the way its argument was written.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub enum Form {
52 /// A passage the annotator marks, which stays part of the text: written
53 /// `\phf{…}` or `\phf … \endphf`.
54 Highlight,
55 /// A remark the annotator writes, which is not part of the text: written
56 /// `\phf[…]`.
57 Comment,
58}
59
60/// Returns the form of the annotation `node` (a node of an annotator's
61/// command, or a cut part of one), read from the opening delimiter that its
62/// argument's group recorded: `[` makes a [comment](Form::Comment), and `{` or
63/// no delimiter at all (the passage closed by `\endphf`) a
64/// [highlight](Form::Highlight).
65///
66/// Every lowering rule of the element, on every backend, reads the form with
67/// this function, and so does the element's [`ApartFromText`] aspect.
68/// Returns `None` when `node` has no argument named `text` holding a group,
69/// which never happens for a node of the element.
70///
71/// [`ApartFromText`]: crate::model::aspects::ApartFromText
72///
73/// # Examples
74///
75/// ```
76/// use std::sync::Arc;
77/// use flm_core::core::registry::{PackageEntry, RegistryBuilder, RegistryInputs};
78/// use flm_core::lang::{parse_fragment, FlmSource, ParseOptions};
79/// use flm_core::model::doc::FragmentLayout;
80/// use flm_core::stdlib::features::annotations::{form_of, AnnotationsConfig, Annotator, Form};
81/// use flm_core::stdlib::{add_features, StdlibConfig};
82///
83/// let config = AnnotationsConfig::new().annotator(Annotator::new("phf").initials("PhF"));
84/// let mut builder = RegistryBuilder::new();
85/// builder.use_package(add_features(PackageEntry::new("std"), StdlibConfig::new().annotations(config)));
86/// builder.use_package(flm_core::math_passthrough::package());
87/// let registry = builder.build(&RegistryInputs::new())?;
88/// let source = Arc::new(FlmSource::new(r"\phf{a} \phf[b] \phf c\endphf"));
89/// let fragment = parse_fragment(registry.lang(), source, FragmentLayout::Inline, &ParseOptions::default())?;
90/// let forms: Vec<_> = fragment
91/// .tree()
92/// .root()
93/// .descendants()
94/// .filter(|node| node.name() == Some("phf"))
95/// .filter_map(|node| form_of(&node))
96/// .collect();
97/// assert_eq!(forms, [Form::Highlight, Form::Comment, Form::Highlight]);
98/// # Ok::<(), Box<dyn std::error::Error>>(())
99/// ```
100pub fn form_of(node: &NodeRef<'_, Flm>) -> Option<Form> {
101 let (open, _) = delimiters_of(node)?;
102 Some(if open == "[" { Form::Comment } else { Form::Highlight })
103}
104
105/// Returns the delimiters the argument of the annotation `node` was written
106/// with, as its group records them: `("{", "}")`, `("[", "]")`, or
107/// `("", "\endphf")` followed by the whitespace the closing command read
108/// (`("", "")` where the passage was not closed). Every cut part of a cut
109/// annotation carries its annotation's two delimiters.
110///
111/// [`form_of`] decides the form from these delimiters, and the recomposed
112/// LaTeX writes the invocation back with them. Returns `None` where
113/// [`form_of`] returns `None`.
114pub(super) fn delimiters_of<'t>(node: &NodeRef<'t, Flm>) -> Option<(&'t str, &'t str)> {
115 let region = node.arguments()?.get_named(TEXT_ARG)?.region.as_ref()?;
116 let group = node.tree().get(region.content_parent())?;
117 group.group_delimiters()
118}
119
120/// The parser of an annotator's one argument: a `{…}` group, a `[…]` group,
121/// or the passage up to the annotator's closing command, chosen by the first
122/// character after the command and any whitespace and source comments that
123/// follow it. The feature declares the argument [`TEXT_ARG`]
124/// of every annotator's command with this parser.
125///
126/// **Before the group.** As for a mandatory `{…}` argument of any command,
127/// whitespace and source comments may be written between the command and the
128/// opening `{` or `[`; they become the leading nodes of the argument. (A
129/// space right after the command's name belongs to the command, as it does
130/// after every command whose name is made of letters.) When neither `{` nor
131/// `[` follows them, they are not skipped: they are the start of the passage.
132///
133/// **The passage.** The third form reads document content, paragraph breaks
134/// and blocks included, up to the command `\end<command>` written at the
135/// passage's own level, which is consumed and closes the group. An
136/// `\end<command>` inside a group or an environment that the passage opened
137/// belongs to that group or environment, where it is not declared. When the
138/// input, or the group or environment enclosing the annotation, ends first
139/// (at the input's end, at a closing brace, or at an `\end` written at the
140/// passage's own level), the passage is what was read up to there, and the
141/// Error [`flm.annotations.unterminated`](super::Unterminated) is reported
142/// over it; the closing brace or the `\end` is left for the group or
143/// environment it closes, which stays intact. (An `\end` at the passage's own
144/// level can only close an environment the passage did not open: the body of
145/// an environment the passage opened is read by that environment, where the
146/// passage does not stop.)
147///
148/// **The groups.** A `[…]` group is read as an optional argument's group is,
149/// and an unclosed `{` or `[` is reported by the language as any unclosed
150/// group is. A `{…}` group alone inside the brackets is kept as a group of
151/// the remark, not unwrapped.
152///
153/// In every form, the argument is one group node holding the content, and
154/// the group records what was read as its delimiters ([`form_of`] reads
155/// them). The argument's parsing mode and scoped packages come from its
156/// declaration and apply to the whole content.
157pub struct AnnotationParser {
158 command: String,
159 end_command: String,
160 braces: GroupArgumentParser<Flm>,
161 brackets: OptionalGroupArgumentParser<Flm>,
162}
163
164impl AnnotationParser {
165 /// Returns the parser of the argument of the command `command` (without
166 /// the backslash), whose passage form closes at `\end<command>`.
167 pub fn new(command: &str) -> AnnotationParser {
168 let bracket = Arc::new(GroupRule {
169 group_type: FlmGroupType::Content,
170 open: String::from("["),
171 close: String::from("]"),
172 });
173 AnnotationParser {
174 command: command.to_string(),
175 end_command: format!("end{command}"),
176 braces: GroupArgumentParser::new(FlmGroupType::Content).with_expression_fallback(false),
177 brackets: OptionalGroupArgumentParser::new(bracket),
178 }
179 }
180
181 /// Reads the passage form: content up to `\end<command>`, built as one
182 /// group with no opening delimiter and the closing command as its closing
183 /// delimiter, or with no closing delimiter where the passage was not
184 /// closed, which is reported.
185 fn passage(
186 &self,
187 cx: &mut ParseContext<'_, '_, Flm>,
188 ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
189 let start = cx.tokens.position_here();
190 let state = Arc::clone(&cx.state);
191 // The run stops at the closing command, and at an environment's
192 // `\end` at this level, which closes an environment around the
193 // annotation (the body of one the passage opens is parsed by that
194 // environment, where this condition does not apply). Which of the two
195 // stopped the run is noted here for the match below.
196 let closed = Cell::new(false);
197 let stops_at = |token: &Token<Flm>, tokens: &dyn TokenReader<'_, Flm>| {
198 Ok(match tokens.token_kind(token) {
199 TokenKind::Command { name, .. } if name == self.end_command => {
200 closed.set(true);
201 true
202 }
203 TokenKind::Command { name, .. } => name == ENVIRONMENT_END,
204 _ => false,
205 })
206 };
207 let stop = StopSpec::at_token(TokenStopKind::Predicate(&stops_at), false);
208 // The passage is a region of its own: what its content changes in
209 // the parsing state ends with it, as a group's does.
210 let (outcome, _) = cx.parse_nodes(Arc::clone(&state), stop, ChildStateSpec::inherit())?;
211 let (close, end) = match outcome.stop {
212 StopCause::TokenCondition { after, .. } if closed.get() => {
213 // The closing command stands unconsumed here; the group's
214 // closing delimiter runs to where the command ends, the space
215 // after it included, as the command token reads it.
216 let close_start = cx.tokens.position_here();
217 cx.tokens.move_to_position(&after);
218 let span = cx.source_span_within(&close_start, &after)?;
219 (TextContent::Spanned(span.span()), after)
220 }
221 // The input's end, or the end of the group or environment around
222 // the annotation, the closing brace or `\end` left unconsumed for it.
223 StopCause::TokenCondition { .. }
224 | StopCause::EndOfInput
225 | StopCause::UnexpectedGroupClose { .. }
226 | StopCause::NodeCondition => {
227 let end = cx.tokens.position_here();
228 let span = cx.source_span_within(&start, &end)?;
229 cx.recover(
230 Unterminated { command: self.command.clone(), end_command: self.end_command.clone() },
231 span,
232 )?;
233 (TextContent::empty(), end)
234 }
235 };
236 let group_span = cx.source_span_within(&start, &end)?;
237 let count = outcome.nodes.len() as u32;
238 let data = GroupData { group_type: Some(FlmGroupType::Content), open: TextContent::empty(), close };
239 let group = cx
240 .stage_node(NodeKind::group(data), group_span.clone(), state, outcome.nodes)
241 .map_err(|error| staging_error(cx, error, group_span))?;
242 Ok(Some(ParsedArgumentNodes::new(vec![group], ContentNodes::InChildrenOf(group, 0..count), ())))
243 }
244}
245
246/// Turns a failure to build the passage's group into the error that aborts
247/// the parse: a failure building the node's extension is a `HookFailed`
248/// condition, any other failure an implementation error.
249fn staging_error(
250 cx: &ParseContext<'_, '_, Flm>,
251 error: NodeBuildError,
252 span: FlmSpan,
253) -> ParseError<FlmOrigin> {
254 match error {
255 NodeBuildError::ExtMintFailed { detail } => ParseError::new(HookFailed::new(detail, None), span),
256 other => cx.implementation_error(other, span),
257 }
258}
259
260impl fmt::Debug for AnnotationParser {
261 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262 f.debug_struct("AnnotationParser").field("command", &self.command).finish()
263 }
264}
265
266impl ArgumentParser<Flm> for AnnotationParser {
267 fn parse_argument(
268 &self,
269 cx: &mut ParseContext<'_, '_, Flm>,
270 spec: &ArgumentSpec<Flm>,
271 ) -> ConstructParserResult<Flm, Option<ParsedArgumentNodes<Flm>>> {
272 // Look past the whitespace and comments a group may follow, then
273 // leave them for whichever form reads them.
274 let noise = scan_argument_noise(cx)?;
275 let next = noise.next.clone();
276 noise.rewind(cx);
277 let braced = next.is_some_and(|token| {
278 matches!(cx.tokens.token_kind(&token), TokenKind::GroupOpen { rule, .. }
279 if rule.group_type == FlmGroupType::Content)
280 });
281 if braced {
282 return self.braces.parse_argument(cx, spec);
283 }
284 if let Some(comment) = self.brackets.parse_argument(cx, spec)? {
285 return Ok(Some(comment));
286 }
287 self.passage(cx)
288 }
289
290 /// Returns `false`: the argument is always present, since the third form
291 /// reads any content that follows the command.
292 fn can_match_empty(&self) -> bool {
293 false
294 }
295}
296
297impl FlmArgumentParser for AnnotationParser {
298 /// `flm.annotations.text:` followed by the command: the parsers of two
299 /// commands differ, since each stops at its own closing command.
300 fn identity(&self) -> Vec<u8> {
301 format!("flm.annotations.text:{}", self.command).into_bytes()
302 }
303
304 /// No user definition can declare an argument read by this parser.
305 fn definition_shape(&self) -> DefinitionShape {
306 DefinitionShape::NoShape { token: "annotation" }
307 }
308
309 fn description(&self) -> String {
310 format!(
311 "a `{{…}}` highlight, a `[…]` comment, or a highlighted passage up to `\\{}`",
312 self.end_command
313 )
314 }
315}