flm_core/lib.rs
1//! `flm-core` is the Rust library that implements FLM ("flexible latexlike
2//! markup"), a markup language for documents. FLM borrows its syntax from
3//! LaTeX: commands begin with a backslash, environments are written as
4//! `\begin{…}…\end{…}`, and a blank line separates two paragraphs. Each
5//! construct of FLM expresses the meaning of a part of the document, not its
6//! appearance, so that one source can be rendered in several output formats.
7//!
8//! The library parses FLM source, processes the document, and renders it in
9//! four output formats: plain text, HTML, *rendered LaTeX* and *recomposed
10//! LaTeX*. Rendered LaTeX is LaTeX for LuaLaTeX in which FLM has already
11//! resolved the numbering, the cross-references and the other computed
12//! content. Recomposed LaTeX is LaTeX source close to what an author would
13//! type; it leaves the numbering and the cross-references to LaTeX.
14//!
15//! The library is built on [techy], a parser toolkit for LaTeX-like
16//! languages, which provides the tokenizer, the parser and the node tree. The
17//! library `flm-host`, which finds and reads the files and the settings of a
18//! document and writes its outputs, uses this library, and so does the
19//! command-line program `flm` (crate `flm`).
20//!
21//! The processing reads and writes no files. A program that uses the library
22//! provides the source text and receives the output as
23//! [artifacts](core::artifact::Artifact): each artifact is a value that
24//! contains the content of one output file. The program decides where to
25//! write the artifacts. When a document includes other files with `\input`,
26//! the program provides an [input resolver](lang::InputResolver), which finds
27//! and reads these files.
28//!
29//! # Using the library
30//!
31//! A program that renders an FLM document takes the following five steps. The
32//! [Introduction](guide::introduction#embedding-the-library) shows them in a
33//! complete program, and the chapter [Embedding flm-core](guide::embedding)
34//! describes each of them in full.
35//!
36//! 1. **Build a registry.** A [registry](core::registry) contains the
37//! definitions used to parse and process documents: the commands and
38//! environments that an author can write, the processing stages, the tables
39//! of computed data, the backends, the workflows, and so on. These
40//! definitions are made in *features*: a
41//! [feature](core::registry::FlmFeature) is a Rust value that contributes a
42//! group of related definitions to a registry. Build the registry with a
43//! [`RegistryBuilder`](core::registry::RegistryBuilder); most programs add
44//! to it a package that holds the standard features of [`stdlib`]
45//! ([`stdlib::add_features`]). The
46//! result, an [`FlmRegistry`](core::registry::FlmRegistry), cannot be
47//! changed after it is built. For documents that contain mathematics, the
48//! registry also needs a feature that processes mathematics, such as the
49//! feature of the package [`math_passthrough`]. Without such a feature,
50//! each formula is reported as an error when the document is rendered.
51//! 2. **Parse the source and place it in a document.**
52//! [`parse_fragment`](lang::parse_fragment) parses one source text into a
53//! [fragment](model::doc::Fragment), and the program places the fragment in
54//! a [document](model::doc::Doc). To parse a file together with the files
55//! that it includes, use [`assemble`](model::assemble::assemble).
56//! 3. **Build a plan.** A [plan](core::plan::Plan) is the list of
57//! [stages](core::stage::Stage) that a run executes, in the order of their
58//! dependencies. A stage is one unit of processing work. The program states
59//! in a [plan request](core::plan::PlanRequest) which *capabilities* it
60//! wants. A [capability](core::registry::CapabilityDef) is a named state of
61//! processing, such as a rendered output. The library then selects the
62//! stages that provide these capabilities and orders them. Usually, the
63//! program uses a [workflow](core::registry::WorkflowDef), a complete plan
64//! request stored in the registry under a name such as `html`, and builds
65//! the plan with [`Plan::for_workflow`](core::plan::Plan::for_workflow).
66//! 4. **Execute a run.** A [run](core::run::Run) is one execution of a plan
67//! over a document. Create the run with [`Run::new`](core::run::Run::new)
68//! and execute it with [`Run::execute`](core::run::Run::execute).
69//! 5. **Read the results.** A run stores what it computes in typed
70//! [tables](core::data::table::Table), which
71//! [`Run::table`](core::run::Run::table) returns. The files of an output,
72//! such as the HTML page, form an [artifact
73//! set](core::artifact::ArtifactSet), which is stored in the table
74//! declared for that output ([`OutputDef`](core::registry::OutputDef)).
75//! The problems found in the document are
76//! [diagnostics](guide::concepts_overview#diagnostics), which
77//! [`Run::diagnostics`](core::run::Run::diagnostics) returns.
78//!
79//! The registry and the plan do not depend on a document. A program therefore
80//! builds them once and uses them for every document that it processes.
81//!
82//! A program that adds commands, checks or output formats of its own defines
83//! them in features, and adds these features to the registry beside the
84//! standard features. The standard features register in the same way. The
85//! chapter [Extending FLM](guide::extending) describes this work.
86//!
87//! # How a document is processed
88//!
89//! Three design decisions shape the library. The [Concepts
90//! overview](guide::concepts_overview) explains each of them.
91//!
92//! 1. **The parsed node trees are the only representation of a document.** A
93//! document consists of the node trees that techy's parser produces. Each
94//! node stores an [element](model::element::ElementSpec), a value that
95//! describes what the node means, such as a heading or emphasis. The
96//! library does not convert the trees into another data structure. See [the
97//! document tree](guide::concepts_overview#the-document-tree).
98//! 2. **The trees are frozen early, and computed data is stored in tables.**
99//! The *rewrite stages* run first, and they are the only stages that change
100//! the trees. Among the standard features, they insert the content of included
101//! files, expand user-defined macros and environments, and group the
102//! content into paragraphs and blocks. After the rewrite stages, the trees
103//! are *frozen*, and no later stage changes them. Each later stage stores
104//! what it computes in tables, such as the numbers of the headings or the
105//! output text, or it checks the document and reports diagnostics. [Frozen
106//! trees and computed
107//! data](guide::concepts_overview#frozen-trees-and-computed-data) explains
108//! the reasons for this design.
109//! 3. **The library derives the processing from what a program requests.**
110//! Each stage is declared with the capabilities that it provides and the
111//! capabilities that it requires. A program *demands* capabilities in its
112//! plan request, and the library builds the plan that provides them. A
113//! feature can therefore add a stage without any change to the other
114//! stages: the stage runs in every plan that needs a capability that it
115//! provides. See [stages, capabilities, and
116//! plans](guide::concepts_overview#stages-capabilities-and-plans).
117//!
118//! # Modules
119//!
120//! - [`model`]: the document model. It defines documents and fragments, the
121//! elements that the nodes store and their aspects, the addresses of trees
122//! and nodes, dotted names, and the option values set on a document.
123//! - [`lang`]: the FLM language on top of techy. It contains the parse
124//! functions, the construction of techy's command specifications from the
125//! elements defined in the features ([`lang::mint`]), the recursion
126//! guard and the worker threads ([`lang::guard`]), and the rewrite passes
127//! that insert included files, expand user definitions and group content
128//! into blocks ([`lang::rewrites`]).
129//! - [`core`]: the processing framework. It contains the registry, stages and
130//! the tables of computed data, plans and runs, lowering rules, artifacts,
131//! services and settings.
132//! - [`stdlib`]: the standard features. They provide the commands and
133//! environments of the language, the stages that structure and check a
134//! document, and the four backends `text`, `html`, `latex-rendered` and
135//! `latex-recomposed`. [`stdlib::add_features`] adds them to a package that
136//! a program declares.
137//! - [`math_passthrough`]: the package `math-passthrough`. Its feature
138//! processes mathematics by copying the source of each formula to the output
139//! as the author wrote it.
140//! - [`layout`]: the text layout engine, which wraps and indents text to a
141//! given line width. The plain-text backend uses it.
142//! - [`progress`]: the progress sheet of a build: the rows of the work under
143//! way and how far each is, the request to stop a build, and the sink of the
144//! log lines that the work writes.
145//! - [`dump`]: tools to inspect and test what the library holds in memory:
146//! projections of trees, tables and diagnostics that tests compare, golden
147//! files, assertions on diagnostics, and the serialization of parses that
148//! the command `flm dump` prints.
149//! - [`guide`]: the chapters of the guide (see [Guide](#guide) below).
150//!
151//! # Cargo features
152//!
153//! The crate has two Cargo features, and both are enabled by default.
154//!
155//! - `parallel`: A [run](core::run::Run) executes independent work in
156//! parallel, on a thread pool of the `rayon` crate. For instance, a stage
157//! that runs once per tree runs on all the trees of a document at the same
158//! time. The output is the same as without the feature. To run all the work
159//! on one thread in a build with this feature, pass
160//! [`RunOptions::sequential`](core::run::RunOptions::sequential) to
161//! [`Run::execute`](core::run::Run::execute).
162//! - `docs`: The library stores the documentation texts given with the
163//! definitions of a registry: the texts of the commands, of their
164//! arguments, of the features, of the stages, of the tables, of the
165//! settings, and so on. The command `flm info` shows these texts. A program
166//! that never shows them, such as a WebAssembly build, can disable the
167//! feature; the library then stores no documentation text.
168//!
169//! When the feature is disabled, every builder method and constructor that
170//! takes a documentation text, such as
171//! [`ElementDef::docs`](lang::mint::ElementDef::docs), stores an empty text.
172//! This also applies to the texts read from settings data, such as the
173//! description of a user definition or of a workflow, because they pass
174//! through the same builder methods. A text that a program assigns directly
175//! to a public `docs` field is kept.
176//!
177//! Disabling the feature changes neither the rendered output of a document
178//! nor the [registry digest](core::registry::FlmRegistry::digest). The JSON
179//! Schema of a feature's settings
180//! ([`SettingsDecl::json_schema`](core::settings::SettingsDecl::json_schema))
181//! then has no top-level description, but it keeps the descriptions of the
182//! individual settings.
183//!
184//! # Module layering
185//!
186//! The top-level modules form layers, and each module uses only the modules of
187//! its own layer and of the layers below it:
188//!
189//! ```text
190//! {model, lang} < core < dump < stdlib < math_passthrough layout, progress standalone
191//! ```
192//!
193//! The modules [`model`] and [`lang`] form one layer because each uses the
194//! other. The parser defined in [`lang`] stores an element in each node, and
195//! elements are defined in [`model`]. A fragment, defined in [`model`],
196//! contains a tree of the FLM language defined in [`lang`]. The [`layout`]
197//! module uses no other module of this crate, and [`stdlib`] uses it in
198//! addition to the modules of the lower layers. The [`progress`] module uses
199//! no other module of this crate either, and [`core`] and [`stdlib`] use it.
200//!
201//! # Guide
202//!
203//! The [`guide`] module contains the narrative documentation of FLM, and the
204//! other modules form the API reference. Start with the
205//! [Introduction](guide::introduction). The [Concepts
206//! overview](guide::concepts_overview) defines the main concepts of the
207//! library, one per section. The [guide's landing page](guide) lists all
208//! chapters: the chapters on the language and on the `flm` program for
209//! authors, the chapters on the library for programmers, and condensed
210//! chapters for AI assistants.
211//!
212//! [techy]: https://github.com/phfaist/techy
213
214/// Re-exports the parser toolkit techy, on which FLM is built. The re-exported
215/// crate is the version of techy that `flm-core` is compiled against.
216///
217/// A program or an extension that uses FLM works with techy's types, such as
218/// node trees, diagnostics and serialization sessions. Use these types through
219/// `flm_core::techy` rather than through a dependency on techy in your own
220/// crate. If a build contains two versions of techy, the types of one version
221/// are distinct from the types of the other, and the functions of one version
222/// do not accept the values of the other. The re-export ensures that your code
223/// uses the same version of techy as `flm-core`.
224pub use techy;
225
226/// Re-exports the Unicode-to-LaTeX encoder `untechxt`. The re-exported crate is
227/// the version of `untechxt` that `flm-core` is compiled against.
228///
229/// `untechxt` converts text into LaTeX source. It replaces each character that
230/// LaTeX does not accept, or treats specially, with LaTeX code that prints the
231/// character, and it records what this code needs in the preamble of a LaTeX
232/// document, such as a package or a font encoding. The LaTeX backends of
233/// `flm-core` take the LaTeX code for each non-ASCII character of a document
234/// from `untechxt` ([`stdlib::backends::latex::escape`]), and the interface of
235/// that module contains types of `untechxt`, such as
236/// [`PreambleNeeds`](untechxt::preamble::PreambleNeeds). Use `untechxt` through
237/// `flm_core::untechxt` rather than through a dependency in your own crate, for
238/// the reason given in the documentation of [`techy`].
239pub use untechxt;
240
241// The cargo feature `docs` is tested in this one function, which each builder
242// calls in its own body, never where a builder is called: those calls number
243// in the hundreds, and every one added would have to remember the test.
244/// Returns the documentation text `docs` when the Cargo feature `docs` is
245/// enabled, and an empty string when it is disabled.
246///
247/// Every builder method and constructor that stores a documentation text
248/// passes the text through this function, so that a build without the feature
249/// stores no documentation text. The code that calls these builder methods,
250/// including the code that reads definitions from settings data, therefore
251/// does not test the feature itself. Library code that sets a documentation
252/// text without a builder method calls this function directly. For instance,
253/// the shared LaTeX module ([`stdlib::backends::latex`]) calls it for the
254/// LaTeX definitions that it derives from the Unicode-to-LaTeX table of
255/// [`untechxt`].
256#[inline]
257pub(crate) fn kept_docs(docs: impl Into<String>) -> String {
258 #[cfg(feature = "docs")]
259 {
260 docs.into()
261 }
262 #[cfg(not(feature = "docs"))]
263 {
264 let _ = docs;
265 String::new()
266 }
267}
268
269// The module layering stated in the crate documentation above is not something
270// the compiler enforces; `tests/module_layering.rs` reads the source tree and
271// fails on any `crate::` path pointing upward, and its ALLOWED table has to be
272// updated whenever a top-level module is added or renamed.
273pub mod core;
274pub mod dump;
275pub mod lang;
276pub mod layout;
277pub mod math_passthrough;
278pub mod model;
279pub mod progress;
280pub mod stdlib;
281
282// Narrative documentation: markdown pages in the workspace-level `docs/` rendered as
283// doc-only modules. They are read through the symbolic link `flm-core/docs` to `../docs`,
284// so that the crate's package holds them. `cfg(doc)` keeps them out of compiled code;
285// rustdoc (including doctest collection) builds with `--cfg doc`, so code blocks in these
286// pages still run as doctests. The docs sidebar pins these pages in a "Guide" section
287// (docs/rustdoc-header.html, wired up in .cargo/config.toml). A new chapter takes four
288// steps: its file `docs/NAME.md`, its module in the block below, its entry in
289// GUIDE_PAGES of docs/rustdoc-header.html, and its line in the chapter index of
290// docs/guide.md.
291#[cfg(doc)]
292#[doc = include_str!("../docs/guide.md")]
293pub mod guide {
294 // User Guide.
295 #[doc = include_str!("../docs/introduction.md")]
296 pub mod introduction {}
297
298 #[doc = include_str!("../docs/language-syntax.md")]
299 pub mod language_syntax {}
300
301 #[doc = include_str!("../docs/std-flm.md")]
302 pub mod std_flm {}
303
304 #[doc = include_str!("../docs/command-line.md")]
305 pub mod command_line {}
306
307 // Developer Guide.
308 #[doc = include_str!("../docs/concepts-overview.md")]
309 pub mod concepts_overview {}
310
311 #[doc = include_str!("../docs/document-model.md")]
312 pub mod document_model {}
313
314 #[doc = include_str!("../docs/pipeline.md")]
315 pub mod pipeline {}
316
317 #[doc = include_str!("../docs/rendering.md")]
318 pub mod rendering {}
319
320 #[doc = include_str!("../docs/numbering.md")]
321 pub mod numbering {}
322
323 #[doc = include_str!("../docs/extending.md")]
324 pub mod extending {}
325
326 #[doc = include_str!("../docs/embedding.md")]
327 pub mod embedding {}
328
329 #[doc = include_str!("../docs/panics.md")]
330 pub mod panics {}
331
332 #[doc = include_str!("../docs/python-flm-migration.md")]
333 pub mod python_flm_migration {}
334
335 // AI Guide.
336 #[doc = include_str!("../docs/ai-guide.md")]
337 pub mod ai_guide {}
338
339 #[doc = include_str!("../docs/ai-guide-document-model.md")]
340 pub mod ai_guide_document_model {}
341
342 #[doc = include_str!("../docs/ai-guide-pipeline.md")]
343 pub mod ai_guide_pipeline {}
344
345 #[doc = include_str!("../docs/ai-guide-extending.md")]
346 pub mod ai_guide_extending {}
347
348 #[doc = include_str!("../docs/ai-guide-embedding.md")]
349 pub mod ai_guide_embedding {}
350}