Skip to main content

flm_core/lang/
parse.rs

1//! This module provides [`parse_fragment`], which parses FLM source text into a
2//! [`Fragment`], along with its options ([`ParseOptions`]) and the errors that
3//! it returns ([`FragmentError`]).
4//!
5//! [`parse_fragment`] parses one source with a [built language](BuiltLang): the
6//! language that [`crate::lang::build`] creates from the definitions declared in
7//! the registry. You usually obtain the built language with
8//! [`FlmRegistry::lang`](crate::core::registry::FlmRegistry::lang). The
9//! returned [`Fragment`] contains the parsed tree, the source, and the
10//! [diagnostics](crate::guide::concepts_overview#diagnostics) reported during
11//! the parse. To parse a document made of several files, use
12//! [`crate::model::assemble`].
13//!
14//! A parse is *tolerant*: the parser reports each problem in the source as a
15//! diagnostic, stores the diagnostic in the fragment, and continues. The tree
16//! covers the whole input. A parse returns no tree only in the cases listed in
17//! [`FragmentError`], and an error in the syntax of the document causes none of
18//! these cases.
19//!
20//! The caller passes the source as an `Arc<FlmSource>`, not as a string. The
21//! source contains its [origin](crate::lang::FlmOrigin), and the canonical path
22//! of the origin identifies the source. For instance, the parser of `\input`
23//! uses the canonical path to detect a file that includes itself, and an
24//! embedding program can use it as the key of its own tables of sources.
25//!
26//! A parse runs on a *worker thread*: a thread whose stack is large enough for
27//! the recursion guard. If the calling thread is not a worker thread, the parse
28//! functions run the parse on a new worker thread, so the caller does not need
29//! to create one. See [`on_worker_thread`](crate::lang::guard::on_worker_thread).
30
31use std::fmt;
32use std::sync::Arc;
33
34use techy::core::constructs::{ConstructParser, DescentLimitExceeded};
35use techy::core::node::BuildId;
36use techy::core::{Language, ParsingState};
37use techy::error::{Diagnostic, DiagnosticInfo, ParseError};
38use techy::source::SourceSpan;
39
40use crate::model::doc::{Fragment, FragmentLayout};
41use crate::lang::build::BuiltLang;
42use crate::lang::flm::Flm;
43use crate::lang::guard::{self, NestingTooDeep};
44use crate::lang::input::{InputResolver, Placements};
45use crate::lang::origin::{FlmDiagnostic, FlmOrigin, FlmSource};
46
47/// The settings of one parse that can differ from the settings of the built
48/// language.
49///
50/// `ParseOptions::default()` keeps every setting of the built language. A field
51/// set here applies to this parse only.
52#[derive(Clone, Default)]
53pub struct ParseOptions {
54    /// The maximum number of diagnostics that this parse stores. `None` keeps
55    /// the cap of the built language
56    /// ([`LangInputs::diagnostics_limit`](crate::lang::LangInputs::diagnostics_limit)).
57    /// Diagnostics beyond the cap are not stored, but they are counted.
58    pub max_diagnostics: Option<usize>,
59    /// The input resolver for this parse, used in place of the input resolver
60    /// of the built language; see [`crate::lang::input`]. `None` keeps the
61    /// input resolver of the built language. For instance, an embedding program
62    /// that records the files read during a build can set here an input
63    /// resolver that records these files, for the parses of this build.
64    pub input_resolver: Option<Arc<dyn InputResolver>>,
65}
66
67impl fmt::Debug for ParseOptions {
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        f.debug_struct("ParseOptions")
70            .field("max_diagnostics", &self.max_diagnostics)
71            .field("input_resolver", &self.input_resolver.as_ref().map(|_| "…"))
72            .finish()
73    }
74}
75
76/// Two `ParseOptions` values are equal if they have the same cap on
77/// diagnostics and the same input resolver. Two input resolvers are the same
78/// if both are `None`, or if both point to the same allocation.
79impl PartialEq for ParseOptions {
80    fn eq(&self, other: &ParseOptions) -> bool {
81        self.max_diagnostics == other.max_diagnostics
82            && match (&self.input_resolver, &other.input_resolver) {
83                (None, None) => true,
84                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
85                _ => false,
86            }
87    }
88}
89
90impl Eq for ParseOptions {}
91
92/// The error that a parse returns when it cannot produce a tree.
93///
94/// A parse reports each problem in the source as a diagnostic and continues.
95/// An error in the syntax of the document therefore never causes a
96/// `FragmentError`. [`FragmentError::diagnostic`] returns a diagnostic that
97/// reports the error, to be recorded in place of the missing tree.
98#[derive(Debug)]
99pub enum FragmentError {
100    /// The content is nested too deeply, and the recursion guard stopped the
101    /// parse. The diagnostic has the condition [`NestingTooDeep`] and the
102    /// position at which the guard stopped the parse.
103    NestingTooDeep(FlmDiagnostic),
104    /// The parse was aborted because of an error in the program: a parser of an
105    /// extension broke a requirement of techy's parser, or a method of the
106    /// language failed. The [`ParseError`] is the error with which techy
107    /// aborted the parse.
108    Aborted(ParseError<FlmOrigin>),
109    /// The parse did not run: the calling thread is not a worker thread, and
110    /// the operating system failed to create one. The diagnostic has the
111    /// condition [`WorkerThreadUnavailable`] and the position of the start of
112    /// the source.
113    WorkerThread(FlmDiagnostic),
114}
115
116impl FragmentError {
117    /// Returns the diagnostic, at error severity, that reports this error. A
118    /// program records this diagnostic for a fragment that could not be parsed.
119    ///
120    /// For [`NestingTooDeep`](FragmentError::NestingTooDeep) and
121    /// [`WorkerThread`](FragmentError::WorkerThread), returns the diagnostic of
122    /// the variant. For [`Aborted`](FragmentError::Aborted), returns a
123    /// diagnostic with the condition [`AbortCondition`], at the span of the
124    /// [`ParseError`]. This condition contains the identifier and the message
125    /// of the `ParseError`.
126    pub fn diagnostic(&self) -> FlmDiagnostic {
127        match self {
128            FragmentError::NestingTooDeep(diagnostic) => diagnostic.clone(),
129            FragmentError::Aborted(error) => abort_diagnostic(error),
130            FragmentError::WorkerThread(diagnostic) => diagnostic.clone(),
131        }
132    }
133}
134
135impl fmt::Display for FragmentError {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        match self {
138            FragmentError::NestingTooDeep(diagnostic) => write!(f, "{}", diagnostic.message()),
139            FragmentError::Aborted(error) => write!(f, "{}", abort_diagnostic(error).message()),
140            FragmentError::WorkerThread(diagnostic) => write!(f, "{}", diagnostic.message()),
141        }
142    }
143}
144
145impl std::error::Error for FragmentError {}
146
147/// Returns the diagnostic, at error severity, that reports the abort `error`:
148/// a diagnostic with the condition [`AbortCondition`], at the span of `error`.
149fn abort_diagnostic(error: &ParseError<FlmOrigin>) -> FlmDiagnostic {
150    let condition =
151        AbortCondition { identifier: error.identifier().to_string(), message: error.message() };
152    Diagnostic::error(condition, error.span().clone())
153}
154
155/// The error that is reported when a parse was aborted because of an error in
156/// the program (id `flm.lang.parse-aborted`).
157///
158/// A document cannot cause this error: it is caused by a faulty extension or by
159/// a faulty method of the language. [`FragmentError::diagnostic`] reports this
160/// error for [`FragmentError::Aborted`]. The fragment has no tree.
161///
162/// The condition contains a copy of the identifier and of the message of the
163/// [`ParseError`] that aborted the parse. The `ParseError` itself, with techy's
164/// record of where the abort happened, is available in
165/// [`FragmentError::Aborted`].
166#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
167#[diagnostic(
168    id = "flm.lang.parse-aborted",
169    message = "Parse aborted by a program error (‘{identifier}’): {message}"
170)]
171pub struct AbortCondition {
172    /// The identifier of the condition of the [`ParseError`].
173    pub identifier: String,
174    /// The message of the [`ParseError`].
175    pub message: String,
176}
177
178/// The error that is reported when the operating system fails to create a
179/// worker thread for a parse (id `flm.lang.worker-thread-unavailable`).
180///
181/// A parse runs on a worker thread, a thread with a large stack; see
182/// [`crate::lang::guard`]. When the calling thread is not a worker thread, the
183/// parse functions create one. If the operating system fails to create this
184/// thread, the parse does not run, and the parse functions return
185/// [`FragmentError::WorkerThread`] with this error. The fragment has no tree.
186///
187/// In this case, the parse does not run on the calling thread either. The
188/// recursion guard limits how deeply a parse descends, but it does not check
189/// the size of the stack of the thread. On a thread with a smaller stack,
190/// deeply nested content could overflow the stack and end the process.
191#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
192#[diagnostic(
193    id = "flm.lang.worker-thread-unavailable",
194    message = "Failed to create a thread with a sufficiently large stack for the parse: {detail}"
195)]
196pub struct WorkerThreadUnavailable {
197    /// The operating system's error message.
198    pub detail: String,
199}
200
201/// The techy [`Language`] that a parse uses: either the language of the
202/// [`BuiltLang`], borrowed, or a copy of it with the options of this parse.
203enum LanguageFor<'a> {
204    Shared(&'a Language<Flm>),
205    Owned(Language<Flm>),
206}
207
208impl LanguageFor<'_> {
209    fn get(&self) -> &Language<Flm> {
210        match self {
211            LanguageFor::Shared(language) => language,
212            LanguageFor::Owned(language) => language,
213        }
214    }
215}
216
217fn language_for<'a>(lang: &'a BuiltLang, options: &ParseOptions) -> LanguageFor<'a> {
218    let limit = match options.max_diagnostics {
219        Some(limit) if Some(limit) != lang.driver().diagnostics_limit_setting() => Some(limit),
220        _ => None,
221    };
222    match (limit, &options.input_resolver) {
223        (None, None) => LanguageFor::Shared(lang.language()),
224        (limit, resolver) => LanguageFor::Owned(lang.language_for_parse(
225            limit.or(lang.driver().diagnostics_limit_setting()),
226            resolver.clone(),
227        )),
228    }
229}
230
231/// Parses `source` with the built language `lang`, and returns the resulting
232/// fragment.
233///
234/// The parse starts from the initial parsing state of `lang`
235/// ([`BuiltLang::initial_state`]). `layout` ([`FragmentLayout`]) is stored in
236/// the fragment and is not used by the parse. It specifies how the
237/// block-structure rewrite pass lays out the top level of the fragment: as
238/// blocks, as inline content, or as inline content until a block appears.
239/// `options` can change the cap on diagnostics and the input resolver for this
240/// parse; see [`ParseOptions`].
241///
242/// The parse is tolerant: each problem in the source is reported as a
243/// diagnostic of the returned fragment ([`Fragment::diags`]). The parse runs on
244/// a worker thread; see the [module documentation](crate::lang::parse).
245///
246/// To parse from another parsing state than the initial state, use
247/// [`parse_fragment_with_state`]. To parse a document made of several files,
248/// use [`crate::model::assemble`].
249///
250/// # Errors
251///
252/// Returns an error, and no fragment, in the following cases:
253///
254/// - [`FragmentError::NestingTooDeep`] if the content is nested more deeply
255///   than the recursion guard allows;
256/// - [`FragmentError::Aborted`] if an error in the program aborts the parse;
257/// - [`FragmentError::WorkerThread`] if the operating system fails to create a
258///   worker thread.
259///
260/// [`FragmentError::diagnostic`] returns the diagnostic to record in place of
261/// the fragment.
262///
263/// # Examples
264///
265/// ```
266/// use std::sync::Arc;
267/// use flm_core::model::doc::FragmentLayout;
268/// use flm_core::lang::{
269///     build_language, parse_fragment, FlmOrigin, FlmSource, LangInputs, ParseOptions,
270/// };
271///
272/// // A language without any feature: it contains only FLM's structural
273/// // elements.
274/// let lang = build_language(LangInputs::new());
275/// let source = Arc::new(FlmSource::new("one {two} \\emph{three}")
276///     .with_origin(FlmOrigin::new("note.flm")));
277///
278/// let fragment = parse_fragment(
279///     &lang, source, FragmentLayout::default(), &ParseOptions::default(),
280/// ).expect("the input is shallow enough to parse");
281///
282/// // The tree covers the whole input, ...
283/// assert!(fragment.tree().root().child_count() > 0);
284/// // ... and `\emph`, which is not defined in any feature of this language, is
285/// // reported as a diagnostic.
286/// let unresolved = fragment.diags().with_identifier("core.specs.unresolvable-command");
287/// assert_eq!(unresolved.count(), 1);
288/// ```
289pub fn parse_fragment(
290    lang: &BuiltLang,
291    source: Arc<FlmSource>,
292    layout: FragmentLayout,
293    options: &ParseOptions,
294) -> Result<Fragment, FragmentError> {
295    parse_fragment_with_state(lang, source, layout, options, Arc::clone(lang.initial_state()))
296}
297
298/// Parses `source` with the built language `lang`, starting from the parsing
299/// state `state`, and returns the resulting fragment.
300///
301/// `state` must be derived from the initial parsing state of `lang` with
302/// [`BuiltLang::derive_state`]. A state derived in this way contains the
303/// packages of the features and the structural elements of the language. For
304/// instance, the library parses the template of a [user
305/// definition](crate::lang::rewrites::userdefs::Definition) from a derived
306/// state with the [`Template`](crate::lang::RestrictedInterior::Template)
307/// policy for restricted interiors and with the package of the placeholders.
308///
309/// The parameters `layout` and `options` and the behavior of the parse are the
310/// same as for [`parse_fragment`]. [`parse_fragment`] calls this function with
311/// the initial parsing state of `lang`.
312///
313/// # Errors
314///
315/// Returns the same errors as [`parse_fragment`].
316pub fn parse_fragment_with_state(
317    lang: &BuiltLang,
318    source: Arc<FlmSource>,
319    layout: FragmentLayout,
320    options: &ParseOptions,
321    state: Arc<ParsingState<Flm>>,
322) -> Result<Fragment, FragmentError> {
323    let run = || parse_on_worker_thread(lang, Arc::clone(&source), layout, options, state);
324    match guard::on_worker_thread(run) {
325        Ok(result) => result,
326        Err(error) => Err(FragmentError::WorkerThread(Diagnostic::error(
327            WorkerThreadUnavailable::new(error.to_string()),
328            SourceSpan::new(&source, 0..0),
329        ))),
330    }
331}
332
333/// Performs the parse of [`parse_fragment_with_state`]. The calling thread must
334/// be a worker thread; see [`crate::lang::guard`].
335fn parse_on_worker_thread(
336    lang: &BuiltLang,
337    source: Arc<FlmSource>,
338    layout: FragmentLayout,
339    options: &ParseOptions,
340    state: Arc<ParsingState<Flm>>,
341) -> Result<Fragment, FragmentError> {
342    let language = language_for(lang, options);
343    parse_in(language.get(), source, layout, state, None)
344}
345
346/// Returns the language with which [`crate::model::assemble`] parses each file
347/// of a document: the language of `lang` with the options `options`, and with
348/// a driver that records the heading inputs in `placements`.
349pub(crate) fn language_for_assembly(
350    lang: &BuiltLang,
351    options: &ParseOptions,
352    placements: Arc<Placements>,
353) -> Language<Flm> {
354    let limit = options.max_diagnostics.or(lang.driver().diagnostics_limit_setting());
355    lang.language_recording(limit, options.input_resolver.clone(), Some(placements))
356}
357
358/// Parses `source` with `language`, starting from the parsing state `state`,
359/// and returns the resulting fragment. If `root` is given, it is the parser of
360/// the top level of the source; otherwise, the root parser of `language` is
361/// used. Like [`parse_fragment`], this function runs the parse on a worker
362/// thread.
363///
364/// # Errors
365///
366/// Returns the same errors as [`parse_fragment`].
367pub(crate) fn parse_with(
368    language: &Language<Flm>,
369    source: Arc<FlmSource>,
370    layout: FragmentLayout,
371    state: Arc<ParsingState<Flm>>,
372    root: Option<&mut (dyn ConstructParser<Flm, Output = BuildId> + Send)>,
373) -> Result<Fragment, FragmentError> {
374    let run = || parse_in(language, Arc::clone(&source), layout, state, root);
375    match guard::on_worker_thread(run) {
376        Ok(result) => result,
377        Err(error) => Err(FragmentError::WorkerThread(Diagnostic::error(
378            WorkerThreadUnavailable::new(error.to_string()),
379            SourceSpan::new(&source, 0..0),
380        ))),
381    }
382}
383
384/// Performs the parse of [`parse_with`]. The calling thread must be a worker
385/// thread; see [`crate::lang::guard`].
386fn parse_in(
387    language: &Language<Flm>,
388    source: Arc<FlmSource>,
389    layout: FragmentLayout,
390    state: Arc<ParsingState<Flm>>,
391    root: Option<&mut (dyn ConstructParser<Flm, Output = BuildId> + Send)>,
392) -> Result<Fragment, FragmentError> {
393    let setup = language.parse_setup(Arc::clone(&source)).with_initial_state(state);
394    let result = match root {
395        Some(root) => setup.with_root_parser(root).parse(),
396        None => setup.parse(),
397    };
398    match result {
399        Ok(result) => Ok(Fragment::new(source, Arc::new(result.tree), result.diagnostics, layout)),
400        Err(error) => match error.data().downcast_ref::<DescentLimitExceeded>() {
401            Some(refusal) => Err(FragmentError::NestingTooDeep(Diagnostic::error(
402                NestingTooDeep::new(refusal.detail.clone()),
403                error.span().clone(),
404            ))),
405            None => Err(FragmentError::Aborted(error)),
406        },
407    }
408}