flm_core/lang/origin.rs
1//! Where an FLM source comes from ([`FlmOrigin`]), and the type aliases for FLM
2//! sources, spans and diagnostics.
3//!
4//! techy attaches an **origin** to every source: a small value saying where the
5//! text comes from. FLM's origin is [`FlmOrigin`]. For a file, it holds the
6//! file's *canonical path*: a key that the embedding program chooses, usually
7//! the file's path. The canonical path has three uses: it is the label a diagnostic
8//! shows for the source, the key by which the library detects a file that
9//! includes itself through `\input`, and the key of the tables an embedding
10//! program keeps per source. An origin records where the text comes from, not
11//! what it contains, so the front matter of a file is not part of it.
12//!
13//! Two kinds of source have no canonical path:
14//!
15//! - A source with no name at all (a snippet held in memory) carries
16//! [`FlmOrigin::none`]. It has no label, and it is left out of every check
17//! keyed by source, so it cannot be confused with another unnamed source.
18//! - A **synthetic** source, which the library creates rather than reads from a
19//! file (for example, the source created for one use of a [user
20//! definition](crate::lang::rewrites::userdefs::Definition)), carries
21//! [`FlmOrigin::synthetic`] with a label saying what it is (`expansion of
22//! \foo`). A diagnostic raised inside it can then say where it was raised.
23//! The label is shown, never used as a key. The source a user definition's
24//! own text is compiled from (its template, labeled `template of \foo (text
25//! mode)`, or an argument's default value) carries [`FlmOrigin::definition`]
26//! instead: a synthetic origin that also marks the text as a user
27//! definition's own text ([`FlmOrigin::is_definition`]), in which `\input`
28//! includes no file.
29//!
30//! The four type aliases [`FlmSource`], [`FlmSpan`], [`FlmDiagnostic`] and
31//! [`FlmDiagnostics`] are techy's source, span and diagnostic types with
32//! [`FlmOrigin`] as their origin type; the whole library uses them.
33//!
34//! Serialized form of an origin: a map with the keys `canonical_path` and
35//! `label`, each a string or absent, and `definition`, `true` or absent.
36
37use std::borrow::Cow;
38
39use techy::error::{Diagnostic, Diagnostics};
40use techy::serialize::{DeserializableValue, SerializableValue};
41use techy::source::{Source, SourceOrigin, SourceSpan};
42
43/// Where an FLM source comes from: its canonical path when it has one, or the
44/// label of a source the library created.
45///
46/// Create an origin with [`FlmOrigin::new`] for a file, [`FlmOrigin::none`]
47/// for an unnamed snippet, [`FlmOrigin::synthetic`] or
48/// [`FlmOrigin::definition`] for a source the library creates, and attach it to
49/// a source with `FlmSource::with_origin`. The [module documentation](self)
50/// explains what the canonical path is used for.
51///
52/// # Examples
53///
54/// ```
55/// use flm_core::lang::FlmOrigin;
56/// use flm_core::techy::source::SourceOrigin;
57///
58/// let file = FlmOrigin::new("book/ch1.flm");
59/// assert_eq!(file.canonical_path(), Some("book/ch1.flm"));
60/// assert_eq!(file.label().as_deref(), Some("book/ch1.flm"));
61///
62/// // A source the library creates has a label but no path, so no check keyed
63/// // by source applies to it.
64/// let made = FlmOrigin::synthetic("expansion of \\foo");
65/// assert_eq!(made.canonical_path(), None);
66/// assert_eq!(made.label().as_deref(), Some("expansion of \\foo"));
67///
68/// // An unnamed snippet has neither.
69/// assert_eq!(FlmOrigin::none(), FlmOrigin::default());
70/// assert_eq!(FlmOrigin::none().label(), None);
71/// ```
72#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
73#[derive(SerializableValue, DeserializableValue)]
74pub struct FlmOrigin {
75 #[serial(name = "canonical_path")]
76 canonical_path: Option<String>,
77 #[serial(name = "label")]
78 label: Option<String>,
79 #[serial(name = "definition")]
80 definition: Option<bool>,
81}
82
83impl FlmOrigin {
84 /// Returns an origin whose canonical path is `canonical_path`.
85 pub fn new(canonical_path: impl Into<String>) -> FlmOrigin {
86 FlmOrigin { canonical_path: Some(canonical_path.into()), label: None, definition: None }
87 }
88
89 /// Returns the origin of a source with no name at all. This is also the
90 /// `Default`.
91 pub fn none() -> FlmOrigin {
92 FlmOrigin { canonical_path: None, label: None, definition: None }
93 }
94
95 /// Returns the origin of a source the library creates: no canonical path,
96 /// so no check keyed by source applies to it, and `label` as the name that
97 /// diagnostics show.
98 pub fn synthetic(label: impl Into<String>) -> FlmOrigin {
99 FlmOrigin { canonical_path: None, label: Some(label.into()), definition: None }
100 }
101
102 /// Returns the origin of the source a user definition's own text is
103 /// compiled from (its template, or the default value of one of its
104 /// arguments): a [synthetic](FlmOrigin::synthetic) origin labeled `label`,
105 /// marked as a user definition's own text
106 /// ([`is_definition`](Self::is_definition)).
107 pub fn definition(label: impl Into<String>) -> FlmOrigin {
108 FlmOrigin { canonical_path: None, label: Some(label.into()), definition: Some(true) }
109 }
110
111 /// Returns whether this is the origin of a user definition's own text (its
112 /// template or an argument's default value), created with
113 /// [`FlmOrigin::definition`].
114 ///
115 /// The parser of `\input` reads it: an `\input` written in such text
116 /// includes no file and is reported
117 /// ([`InputInDefinition`](crate::lang::input::InputInDefinition)).
118 pub fn is_definition(&self) -> bool {
119 self.definition == Some(true)
120 }
121
122 /// Returns the canonical path, when there is one. It is the key of every
123 /// check and table keyed by source.
124 pub fn canonical_path(&self) -> Option<&str> {
125 self.canonical_path.as_deref()
126 }
127
128 /// Returns the label of a source the library created, when there is one.
129 /// The label a diagnostic shows is [`SourceOrigin::label`], which prefers
130 /// the canonical path.
131 pub fn synthetic_label(&self) -> Option<&str> {
132 self.label.as_deref()
133 }
134}
135
136impl SourceOrigin for FlmOrigin {
137 /// Returns what a diagnostic shows for this source: the canonical path, or
138 /// the label when there is no path, or nothing when there is neither.
139 fn label(&self) -> Option<Cow<'_, str>> {
140 self.canonical_path.as_deref().or(self.label.as_deref()).map(Cow::Borrowed)
141 }
142}
143
144/// An FLM source: a text with its [`FlmOrigin`]. techy's [`Source`] with
145/// [`FlmOrigin`] as its origin type.
146pub type FlmSource = Source<FlmOrigin>;
147
148/// A range of bytes in an FLM source, carrying the source it belongs to.
149/// techy's [`SourceSpan`] with [`FlmOrigin`] as its origin type.
150pub type FlmSpan = SourceSpan<FlmOrigin>;
151
152/// One problem reported about FLM content: a condition, a severity and a span
153/// (see [diagnostics](crate::guide::concepts_overview#diagnostics)). techy's
154/// [`Diagnostic`] with [`FlmOrigin`] as its origin type.
155pub type FlmDiagnostic = Diagnostic<FlmOrigin>;
156
157/// A collection of [`FlmDiagnostic`]s, with the cap on how many are kept and the
158/// count of those dropped past the cap. techy's [`Diagnostics`] with
159/// [`FlmOrigin`] as its origin type.
160pub type FlmDiagnostics = Diagnostics<FlmOrigin>;
161
162/// Returns an empty span over an empty source with `origin`, for a condition
163/// that has no position in any document (a stage that failed before it read a
164/// node, a backend that could not start a worker thread). A diagnostic needs a
165/// span, and this span points at no text; the reader of the diagnostic sees the
166/// origin's label instead, so each caller passes its own origin
167/// ([`FlmOrigin::synthetic`] labeled with the part of the library reporting, or
168/// [`FlmOrigin::none`] when there is nothing to show).
169pub(crate) fn nowhere(origin: FlmOrigin) -> FlmSpan {
170 let source = std::sync::Arc::new(Source::new("").with_origin(origin));
171 SourceSpan::new(&source, 0..0)
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[test]
179 fn the_label_is_the_canonical_path() {
180 assert_eq!(FlmOrigin::new("book/ch1.flm").label().as_deref(), Some("book/ch1.flm"));
181 assert_eq!(FlmOrigin::none().label(), None);
182 assert_eq!(FlmOrigin::default(), FlmOrigin::none());
183 }
184
185 #[test]
186 fn a_synthetic_origin_is_labeled_but_has_no_path() {
187 let origin = FlmOrigin::synthetic("expansion of \\foo");
188 assert_eq!(origin.label().as_deref(), Some("expansion of \\foo"));
189 assert_eq!(origin.canonical_path(), None);
190 assert_eq!(origin.synthetic_label(), Some("expansion of \\foo"));
191 assert!(!origin.is_definition());
192 }
193
194 #[test]
195 fn a_definition_origin_is_a_marked_synthetic_origin() {
196 let origin = FlmOrigin::definition("template of \\foo (text mode)");
197 assert_eq!(origin.label().as_deref(), Some("template of \\foo (text mode)"));
198 assert_eq!(origin.canonical_path(), None);
199 assert!(origin.is_definition());
200 assert!(!FlmOrigin::new("a.flm").is_definition() && !FlmOrigin::none().is_definition());
201 }
202}