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