Skip to main content

flm_core/lang/
driver.rs

1//! This module defines [`FlmDriver`], the parse driver of the FLM language,
2//! along with the error conditions that the driver reports.
3//!
4//! techy describes a language in two parts. The *language type*, [`Flm`] for
5//! FLM, defines at compile time the kinds of groups and callables of the
6//! language and the data attached to parsing states and to nodes. The *parse
7//! driver* is a value that provides the settings and the callbacks that the
8//! parser uses during a parse: the error recovery policy, the cap on the number
9//! of stored diagnostics, the resolution of command names, the node created for
10//! a paragraph break, and the change of parsing state inside a math group.
11//!
12//! Most methods of [`FlmDriver`] call the corresponding function of techy's
13//! LaTeX-like preset ([`techy::latexlike`]). FLM's driver differs from the
14//! preset in the following points:
15//!
16//! - A paragraph break (a blank line) is parsed as a node with the element
17//!   `flm.parbreak` ([`PARBREAK`](crate::lang::structural::PARBREAK)).
18//! - When `$` is not a math delimiter, each `$` in the source is reported with
19//!   the condition [`DollarMathDisabled`]. The message of this condition gives
20//!   the math delimiters to use instead.
21//! - When a lone `%` is a forbidden character, each lone `%` in the source is
22//!   reported with the condition [`PercentForbidden`]. The message of this
23//!   condition gives the syntax for a percent sign and for a comment.
24//! - The driver resolves FLM's state events ([`FlmEvent`]). It holds the
25//!   *standard state of the parse*, which [`FlmEvent::StandardScope`] and
26//!   [`FlmEvent::StandardState`] restore: the initial state of the built
27//!   language, or the state that
28//!   [`ParseOptions::standard_state`](crate::lang::ParseOptions::standard_state)
29//!   sets for one parse. [`FlmEvent::ExitMathContext`] is resolved as techy's
30//!   preset resolves it.
31//! - The driver stores the input resolver ([`InputResolver`]) that the
32//!   embedding program provides. The parser of the `\input` command uses the
33//!   input resolver to read the included file; see [`crate::lang::input`].
34
35use std::fmt;
36use std::sync::Arc;
37
38use techy::core::node::NodeKind;
39use techy::core::specs::{resolve_command_in_scopes, CommandResolution, ScopeOp};
40use techy::core::token::{ForbiddenChar, GroupRule, Token, TokenReader};
41use techy::core::{ParseDriver, ParsingState, ParsingStateDelta, ParsingStateStack};
42use techy::error::{DiagnosticData, DiagnosticInfo, Diagnostics, ParseError, Recovery};
43use techy::latexlike::{
44    exit_math_context_delta, make_paragraph_break_node, math_group_interior_delta, LatexlikeLang,
45    LatexlikeParseDriver, ParagraphBreakStyle,
46};
47use techy::source::{Source, SourceSpan};
48
49use crate::lang::flm::{Flm, FlmCallableType, FlmEvent};
50use crate::lang::input::{InputResolver, Placements};
51use crate::lang::origin::FlmOrigin;
52use crate::lang::rules::{restoring_overrides, FlmParsing};
53
54/// The error that is reported when a `$` appears in the source while `$` is not
55/// a math delimiter (id `flm.lang.dollar-math-disabled`).
56///
57/// `$` is a math delimiter only when the parsing setting
58/// [`FlmParsing::dollar_math`](crate::lang::FlmParsing::dollar_math) is on.
59/// When this setting is off, which is the default, inline math is written
60/// `\(…\)`, as in `\(x^2\)`, and display math is written `\[…\]`. `\$` writes a
61/// dollar sign in either setting.
62///
63/// Reported by the parser when it reads the `$`. The `$` is kept in the text as
64/// an ordinary character, and the parse continues.
65#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
66#[diagnostic(
67    id = "flm.lang.dollar-math-disabled",
68    message = "‘$’ may not be used here; use {suggestion}"
69)]
70pub struct DollarMathDisabled {
71    /// The text that the message gives after "use": the math delimiters to
72    /// write instead of `$`. The driver always sets this field to
73    /// [`DollarMathDisabled::SUGGESTION`].
74    pub suggestion: String,
75}
76
77impl DollarMathDisabled {
78    /// The value of the `suggestion` field in every condition that the driver
79    /// reports. It gives the delimiters `\(…\)` for inline math and `\[…\]` for
80    /// display math.
81    pub const SUGGESTION: &'static str =
82        "\\(…\\) for inline mathematics or \\[…\\] for display mathematics";
83}
84
85/// The error that is reported when a lone `%` appears in the source under
86/// parsing settings that forbid it (id `flm.lang.percent-forbidden`).
87///
88/// A lone `%` is forbidden unless it starts a comment, that is, unless comments
89/// are on and the comment prefix is `%`
90/// ([`FlmParsing::percent_forbidden`](crate::lang::FlmParsing::percent_forbidden)).
91/// Under the default parsing settings, the comment prefix is `%%`, and a lone
92/// `%` is therefore forbidden. A lone `%` is ambiguous: it can be meant as a
93/// percent sign or as the start of a comment. The author writes `\%` for a
94/// percent sign, as in `add 10\% to the total`, and the comment prefix, e.g.
95/// `%%`, to start a comment.
96///
97/// Reported by the parser when it reads the `%`. The `%` is kept in the text as
98/// an ordinary character, and the parse continues.
99#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
100#[diagnostic(
101    id = "flm.lang.percent-forbidden",
102    message = "A lone ‘%’ is not allowed; use {suggestion}"
103)]
104pub struct PercentForbidden {
105    /// The text that the message gives after "use": the syntax for a percent
106    /// sign and for a comment, as returned by [`PercentForbidden::suggestion`].
107    pub suggestion: String,
108    /// The comment prefix under the parsing settings of the file in which the
109    /// `%` appears, or `None` if no comment is recognized in this file. An
110    /// included file can have parsing settings of its own.
111    pub comment_start: Option<String>,
112}
113
114impl PercentForbidden {
115    /// Returns the text of the `suggestion` field for the comment prefix
116    /// `comment_start`.
117    ///
118    /// The text gives `\%` for a percent sign. If `comment_start` is `Some`,
119    /// the text also gives the comment prefix for a comment. `comment_start` is
120    /// `None` when comments are off or the comment prefix is empty; see
121    /// [`FlmParsing::comment_start`](crate::lang::FlmParsing::comment_start).
122    ///
123    /// The wording of this text may change between versions. A program that
124    /// inspects the condition should read the `comment_start` field.
125    pub fn suggestion(comment_start: Option<&str>) -> String {
126        match comment_start {
127            Some(start) => {
128                format!("‘\\%’ for a percent sign, or ‘{start}’ to start a comment")
129            }
130            None => {
131                String::from("‘\\%’ for a percent sign")
132            }
133        }
134    }
135}
136
137/// An `FlmDriver` is the parse driver of the FLM language. It stores the
138/// settings of a parse: the error recovery policy, the cap on the number of
139/// stored diagnostics, the standard state of the parse, and the input resolver
140/// that reads the files included with `\input`. The [module
141/// documentation](crate::lang::driver) explains what a parse driver is.
142///
143/// You do not usually create a driver yourself. [`build_language`] creates the
144/// driver of a [`BuiltLang`] from the settings in its
145/// [`LangInputs`](crate::lang::LangInputs), and
146/// [`BuiltLang::driver`](crate::lang::BuiltLang::driver) returns this driver.
147/// To parse with a different cap on diagnostics, a different standard state or
148/// a different input resolver, pass [`ParseOptions`](crate::lang::ParseOptions) to
149/// [`parse_fragment`](crate::lang::parse_fragment).
150///
151/// [`build_language`]: crate::lang::build_language
152/// [`BuiltLang`]: crate::lang::BuiltLang
153pub struct FlmDriver {
154    recovery: Recovery,
155    diagnostics_limit: Option<usize>,
156    standard_state: Arc<ParsingState<Flm>>,
157    input_resolver: Option<Arc<dyn InputResolver>>,
158    placements: Option<Arc<Placements>>,
159}
160
161impl FlmDriver {
162    /// Returns a driver with the error recovery policy `recovery`, the cap
163    /// `diagnostics_limit` on the number of stored diagnostics, the standard
164    /// state `standard_state`, and no input resolver.
165    ///
166    /// With [`Recovery::Tolerant`], the parser reports a problem in the source
167    /// as a diagnostic and continues the parse. With [`Recovery::Strict`], the
168    /// parse fails at the first problem. [`build_language`](crate::lang::build_language)
169    /// always uses `Recovery::Tolerant`.
170    ///
171    /// `diagnostics_limit` is the maximum number of diagnostics that a parse
172    /// stores. With `None`, techy's default cap applies
173    /// ([`Diagnostics::DEFAULT_LIMIT`]). Diagnostics beyond the cap are not
174    /// stored, but they are counted ([`Diagnostics::suppressed`]).
175    ///
176    /// `standard_state` is the standard state of the parses that use this
177    /// driver: the state that [`FlmEvent::StandardScope`] and
178    /// [`FlmEvent::StandardState`] restore. [`build_language`](crate::lang::build_language)
179    /// passes the initial state of the built language
180    /// ([`BuiltLang::initial_state`](crate::lang::BuiltLang::initial_state)).
181    pub fn new(
182        recovery: Recovery,
183        diagnostics_limit: Option<usize>,
184        standard_state: Arc<ParsingState<Flm>>,
185    ) -> FlmDriver {
186        FlmDriver {
187            recovery,
188            diagnostics_limit,
189            standard_state,
190            input_resolver: None,
191            placements: None,
192        }
193    }
194
195    /// Sets the cap on the number of diagnostics that a parse stores, and
196    /// returns the driver. With `None`, techy's default cap applies
197    /// ([`Diagnostics::DEFAULT_LIMIT`]).
198    pub fn with_diagnostics_limit(mut self, limit: Option<usize>) -> FlmDriver {
199        self.diagnostics_limit = limit;
200        self
201    }
202
203    /// Sets the standard state of the parse, and returns the driver: the state
204    /// that [`FlmEvent::StandardScope`] and [`FlmEvent::StandardState`]
205    /// restore. A parse with
206    /// [`ParseOptions::standard_state`](crate::lang::ParseOptions::standard_state)
207    /// set runs with a copy of the built language's driver that carries it.
208    pub fn with_standard_state(mut self, state: Arc<ParsingState<Flm>>) -> FlmDriver {
209        self.standard_state = state;
210        self
211    }
212
213    /// Sets the input resolver, and returns the driver. The input resolver finds
214    /// and reads the file that an `\input` command includes; see
215    /// [`crate::lang::input`].
216    ///
217    /// The library reads no files itself. Without an input resolver, each
218    /// `\input` command is reported with the condition
219    /// [`InputUnavailable`](crate::lang::input::InputUnavailable) and includes
220    /// nothing. The `flm` command-line program sets an input resolver that reads
221    /// files from the disk.
222    pub fn with_input_resolver(mut self, resolver: Arc<dyn InputResolver>) -> FlmDriver {
223        self.input_resolver = Some(resolver);
224        self
225    }
226
227    /// Returns the input resolver set with [`FlmDriver::with_input_resolver`],
228    /// or `None` if no input resolver is set.
229    pub fn input_resolver(&self) -> Option<&dyn InputResolver> {
230        self.input_resolver.as_deref()
231    }
232
233    /// Sets the list in which the parser of `\input` records the heading
234    /// inputs, and returns the driver. A heading input is an included file that
235    /// begins with a heading. [`crate::model::assemble`] sets this list when it
236    /// assembles a document from several files, and reads it after each parse.
237    pub(crate) fn with_placements(mut self, placements: Arc<Placements>) -> FlmDriver {
238        self.placements = Some(placements);
239        self
240    }
241
242    /// Returns the list of heading inputs set with
243    /// [`FlmDriver::with_placements`], or `None` if this driver does not parse
244    /// for the assembly of a document.
245    pub(crate) fn placements(&self) -> Option<&Placements> {
246        self.placements.as_deref()
247    }
248
249    /// Returns the cap on the number of stored diagnostics that this driver was
250    /// given. `None` means that techy's default cap applies.
251    pub fn diagnostics_limit_setting(&self) -> Option<usize> {
252        self.diagnostics_limit
253    }
254}
255
256impl Clone for FlmDriver {
257    fn clone(&self) -> FlmDriver {
258        FlmDriver {
259            recovery: self.recovery,
260            diagnostics_limit: self.diagnostics_limit,
261            standard_state: Arc::clone(&self.standard_state),
262            input_resolver: self.input_resolver.clone(),
263            placements: self.placements.clone(),
264        }
265    }
266}
267
268impl fmt::Debug for FlmDriver {
269    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
270        f.debug_struct("FlmDriver")
271            .field("recovery", &self.recovery)
272            .field("diagnostics_limit", &self.diagnostics_limit)
273            .field(
274                "standard_state",
275                &self.standard_state.scopes().provider_names().collect::<Vec<_>>(),
276            )
277            .field("input_resolver", &self.input_resolver.as_ref().map(|_| "…"))
278            .field("placements", &self.placements.is_some())
279            .finish()
280    }
281}
282
283impl ParseDriver<Flm> for FlmDriver {
284    fn recovery(&self) -> Recovery {
285        self.recovery
286    }
287
288    fn diagnostics_limit(&self) -> Option<usize> {
289        self.diagnostics_limit
290    }
291
292    /// Resolves the command name of `token` as a macro, in the scopes of the
293    /// parsing state `state`, from the innermost scope outwards.
294    ///
295    /// `\begin` and `\end` are resolved like any other command name. They
296    /// resolve to techy's built-in specifications of `\begin` and `\end`, which
297    /// then resolve the environment name. A name that is not defined in any
298    /// package is resolved by the fallback provider
299    /// ([`FlmFallbackProvider`](crate::lang::mint::FlmFallbackProvider)) at the
300    /// bottom of the scope stack.
301    ///
302    /// # Errors
303    ///
304    /// Never returns an error.
305    fn resolve_command(
306        &self,
307        state: &ParsingState<Flm>,
308        token: &Token<Flm>,
309        tokens: &dyn TokenReader<'_, Flm>,
310    ) -> Result<CommandResolution<Flm>, ParseError<FlmOrigin>> {
311        Ok(resolve_command_in_scopes(state, token, tokens, FlmCallableType::Macro))
312    }
313
314    /// Returns the node created for a paragraph break: a callable node with
315    /// techy's standard paragraph-break specification
316    /// ([`ParagraphBreakStyle::Specials`]). Nodes of this form have the element
317    /// [`flm.parbreak`](crate::lang::structural::PARBREAK), and the
318    /// block-structure rewrite pass splits paragraphs at these nodes.
319    fn make_paragraph_break_node(
320        &self,
321        state: &ParsingState<Flm>,
322        break_span: &SourceSpan<FlmOrigin>,
323    ) -> NodeKind<Flm> {
324        make_paragraph_break_node(ParagraphBreakStyle::Specials, state, break_span)
325    }
326
327    /// Replaces the condition reported for a forbidden `$` or `%` with an FLM
328    /// condition whose message contains the syntax to write instead.
329    ///
330    /// - For `$`, the replacement is [`DollarMathDisabled`].
331    /// - For `%`, the replacement is [`PercentForbidden`]. This condition gives
332    ///   the comment prefix of the parsing settings in `state`, which are the
333    ///   parsing settings of the file in which the `%` appears.
334    ///
335    /// Every other condition is returned unchanged.
336    fn refine_diagnostic(
337        &self,
338        data: Box<dyn DiagnosticData>,
339        state: &ParsingState<Flm>,
340    ) -> Box<dyn DiagnosticData> {
341        if let Some(forbidden) = data.downcast_ref::<ForbiddenChar>() {
342            // The forbidden characters come from the parsing settings alone:
343            // `$` is forbidden exactly where it delimits no mathematics, and `%`
344            // exactly where a lone `%` starts no comment — under the document's
345            // settings or under an included file's own — so the character alone
346            // says which condition this is.
347            if forbidden.ch == '$' {
348                return Box::new(DollarMathDisabled::new(DollarMathDisabled::SUGGESTION));
349            }
350            if forbidden.ch == '%' {
351                let comment_start = state.ext().parsing.comment_start();
352                return Box::new(PercentForbidden::new(
353                    PercentForbidden::suggestion(comment_start),
354                    comment_start.map(String::from),
355                ));
356            }
357        }
358        data
359    }
360
361    /// Calls [`Flm::check_parse_start`] at the start of a parse. FLM uses the
362    /// default implementation of this function, which performs no check.
363    fn observe_parse_start(
364        &self,
365        source: &Arc<Source<FlmOrigin>>,
366        initial_state: &Arc<ParsingState<Flm>>,
367        diagnostics: &mut Diagnostics<FlmOrigin>,
368    ) {
369        Flm::check_parse_start(source, initial_state, diagnostics);
370    }
371
372    /// Returns the change of parsing state that replaces `event`, from the
373    /// enclosing parsing states in `stack` (the current state first) and from
374    /// the standard state of the parse ([`FlmDriver::new`]).
375    ///
376    /// - [`FlmEvent::ExitMathContext`]: the change that restores the innermost
377    ///   enclosing parsing state that is not in math mode, for instance at the
378    ///   argument of `\text`, as techy's preset computes it.
379    /// - [`FlmEvent::StandardScope`]: one scope operation, which replaces the
380    ///   scope stack by that of the standard state.
381    /// - [`FlmEvent::StandardState`]: the change that gives the state the
382    ///   scope stack, the tokenizer rules, the mode and the data
383    ///   ([`FlmStateExt`](crate::lang::FlmStateExt)) of the standard state
384    ///   under the parsing settings of the file being read. These settings
385    ///   are those that the current state records
386    ///   ([`FlmStateExt::parsing`](crate::lang::FlmStateExt::parsing)). When
387    ///   they are those of the standard state, the change restores the
388    ///   standard state. When the file being read has settings of its own, the
389    ///   change restores the standard state with these settings applied, as
390    ///   the parser of `\input` applies them
391    ///   ([`FlmParsing::state_delta`](crate::lang::FlmParsing::state_delta)).
392    ///   The temporary group rules and the expected group close of the
393    ///   current state are kept.
394    ///
395    /// # Errors
396    ///
397    /// Never returns an error.
398    fn resolve_state_event(
399        &self,
400        event: &FlmEvent,
401        stack: &ParsingStateStack<Flm>,
402    ) -> Result<Option<ParsingStateDelta<Flm>>, ParseError<FlmOrigin>> {
403        let standard = &self.standard_state;
404        let delta = match event {
405            FlmEvent::ExitMathContext => exit_math_context_delta(stack),
406            FlmEvent::StandardScope => ParsingStateDelta::new()
407                .scope_op(ScopeOp::ReplaceStack(standard.scopes().providers().to_vec())),
408            FlmEvent::StandardState => standard_state_delta(standard, stack),
409        };
410        Ok(Some(delta))
411    }
412
413    /// Returns the change of parsing state that the parser applies inside a
414    /// group.
415    ///
416    /// For a math group, the parser applies this change so that the parsing
417    /// state inside the group is in math mode and has no group rules that open
418    /// math. For any other group, returns `None`, and the parser applies only
419    /// techy's standard change.
420    fn group_interior_delta(
421        &self,
422        base: &ParsingState<Flm>,
423        rule: &Arc<GroupRule<Flm>>,
424    ) -> Option<ParsingStateDelta<Flm>> {
425        math_group_interior_delta(base, rule)
426    }
427}
428
429/// Returns the change that [`FlmEvent::StandardState`] resolves to: the change
430/// that makes a state equal to the standard state `standard` under the parsing
431/// settings of the file being read, which the current state, the first of
432/// `stack`, records. See [`FlmDriver::resolve_state_event`].
433fn standard_state_delta(
434    standard: &ParsingState<Flm>,
435    stack: &ParsingStateStack<Flm>,
436) -> ParsingStateDelta<Flm> {
437    let mut rules = standard.rules().clone();
438    let mut ext = standard.ext().clone();
439    if let Some(current) = stack.iter().next() {
440        let parsing = &current.ext().parsing;
441        if **parsing != *standard.ext().parsing {
442            // The derivation of `\input` for a file with settings of its own
443            // (`crate::lang::input`), applied to the standard state.
444            parsing.state_delta().rules.apply(&mut rules);
445            ext = ext.with_parsing(FlmParsing::clone(parsing));
446        }
447    }
448    ParsingStateDelta::new()
449        .mode(standard.mode())
450        .rules(restoring_overrides(&rules))
451        .ext(ext)
452        .scope_op(ScopeOp::ReplaceStack(standard.scopes().providers().to_vec()))
453}
454
455/// Uses the default implementation of every function of techy's
456/// [`LatexlikeParseDriver`]. In particular, the changes of parsing state made
457/// inside the body of an environment do not apply after the end of the
458/// environment.
459impl LatexlikeParseDriver<Flm> for FlmDriver {}