flm_core/lang/rewrites/userdefs/diagnostics.rs
1//! The conditions that user-definition expansion reports. Their identifiers have
2//! the form `flm.userdefs.<condition>`; a
3//! [condition](crate::guide::concepts_overview#diagnostics) is the typed body of
4//! a diagnostic.
5//!
6//! The module declares four conditions. Each arises when the **registry is
7//! built**, while a definition's templates are compiled, at a **use site**,
8//! while the [expand pass](super::expand) runs, or in both cases:
9//!
10//! - [`RecursionLimit`], at a use site while the expand pass runs: expanding the
11//! use site would exceed the expansion depth limit.
12//! - [`BadPlaceholder`], when the registry is built, for a placeholder that
13//! refers to something the definition does not have or that is misused (the
14//! definition is then refused); at a use site, with the problem
15//! [`Unresolvable`](PlaceholderProblem::Unresolvable), for a placeholder that
16//! has no value there.
17//! - [`BadDefinition`], when the registry is built, for a problem with the
18//! definition as a whole (the definition is then refused); at a use site, with
19//! the problem [`NotCompiled`](DefinitionProblem::NotCompiled), for a
20//! definition whose template was not compiled, or with the problem
21//! [`NotInForceInMode`](DefinitionProblem::NotInForceInMode), for a use in a
22//! parsing mode where the definition's one template text did not parse.
23//! - [`ExpansionFailed`], for a failure of the expand pass itself: an internal
24//! error while building the expanded tree, or a failing expansion hook. The
25//! pass then returns no tree, and this diagnostic says why.
26//!
27//! For each condition reported at a use site, the use site is replaced by a text
28//! node holding its literal source text, and one Error diagnostic at the use
29//! site says why. No problem in a document makes the pass panic.
30//!
31//! Diagnostic data never carries the displayed text, so that a test that checks
32//! the data does not depend on the wording. A problem type
33//! ([`PlaceholderProblem`], [`DefinitionProblem`]) appears in the data as a map
34//! with a stable `kind` token and the problem's fields. A problem type has no
35//! text of its own: the condition that carries it ([`BadPlaceholder`],
36//! [`BadDefinition`]) writes the whole message, one wording for each problem,
37//! from the problem and the condition's other fields.
38
39use std::fmt;
40
41use techy::error::{DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
42use techy::latexlike::Mode;
43
44/// Condition `flm.userdefs.recursion-limit`: expanding a use site would exceed
45/// the expansion depth limit, the number of expansions that one chain may nest
46/// inside one another ([`ExpandOptions::recursion_limit`](super::ExpandOptions::recursion_limit)).
47/// This limit is separate from the [recursion guard](crate::lang::guard), which
48/// limits how deeply a tree may nest.
49///
50/// Recovery: the use site is replaced by its literal source text.
51#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
52#[diagnostic(
53 id = "flm.userdefs.recursion-limit",
54 message = "Recursion limit reached ({limit} levels) while expanding ‘{name}’"
55)]
56pub struct RecursionLimit {
57 /// The definition whose use site could not be expanded, as an author
58 /// writes it (`\foo`).
59 pub name: String,
60 /// The depth limit that applies.
61 pub limit: usize,
62}
63
64/// What is wrong with a placeholder of a template: the detail of
65/// [`BadPlaceholder`].
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub enum PlaceholderProblem {
68 /// A numbered placeholder beyond the definition's arguments.
69 OutOfRange {
70 /// How many arguments a numbered placeholder may refer to: the number of
71 /// declared arguments minus the definition's argument number offset.
72 arity: usize,
73 },
74 /// A named placeholder that matches no argument name and no placeholder name
75 /// that an expansion hook of the definition computes.
76 UnknownName,
77 /// A `#{body}` placeholder in the template of a definition that has no body: a
78 /// macro or a special character sequence.
79 NoBody,
80 /// A substitution argument (`#[…]{…}`) on a placeholder that takes none: a
81 /// numbered or named argument, the body, or a computed placeholder name declared
82 /// without one.
83 SubstitutionNotAccepted,
84 /// A placeholder that has no value at expansion time: the placeholder bindings
85 /// of the use site give it none (no expansion hook computes it), or it is a
86 /// placeholder left in content that an expansion hook built.
87 Unresolvable,
88 /// A default argument value that refers to itself through other default values.
89 DefaultCycle,
90}
91
92impl PlaceholderProblem {
93 /// The stable token for the problem in diagnostic data, which a test or a
94 /// tool matches on; the wording belongs to the message alone.
95 pub fn kind(&self) -> &'static str {
96 match self {
97 PlaceholderProblem::OutOfRange { .. } => "out-of-range",
98 PlaceholderProblem::UnknownName => "unknown-name",
99 PlaceholderProblem::NoBody => "no-body",
100 PlaceholderProblem::SubstitutionNotAccepted => "substitution-not-accepted",
101 PlaceholderProblem::Unresolvable => "unresolvable",
102 PlaceholderProblem::DefaultCycle => "default-cycle",
103 }
104 }
105}
106
107/// Diagnostic data: a map holding the [`kind`](PlaceholderProblem::kind) token
108/// and the fields (`arity` for an out-of-range placeholder), never the
109/// displayed text, so that a test that checks the data does not depend on the
110/// wording.
111impl ToDiagnosticValue for PlaceholderProblem {
112 fn to_diagnostic_value(&self) -> DiagnosticValue {
113 let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
114 if let PlaceholderProblem::OutOfRange { arity } = self {
115 fields.push((String::from("arity"), arity.to_diagnostic_value()));
116 }
117 DiagnosticValue::Map(fields)
118 }
119}
120
121/// Condition `flm.userdefs.bad-placeholder`: a placeholder of a template that is
122/// invalid (found when the registry is built) or that has no value at a use site
123/// (found at expansion); [`PlaceholderProblem`] says which.
124///
125/// Recovery: when the registry is built, where templates are compiled, the
126/// definition is refused; at expansion, the use site is replaced by its literal
127/// source text.
128#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
129#[diagnostic(id = "flm.userdefs.bad-placeholder")]
130pub struct BadPlaceholder {
131 /// The definition whose template holds the placeholder, as an author
132 /// writes it (`\foo`).
133 pub name: String,
134 /// The placeholder as written between the `#` and the end of the
135 /// placeholder (`1`, `body`, `title`).
136 pub reference: String,
137 /// What is wrong with the placeholder.
138 pub reason: PlaceholderProblem,
139}
140
141impl fmt::Display for BadPlaceholder {
142 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143 let BadPlaceholder { name, reference, reason } = self;
144 match reason {
145 PlaceholderProblem::OutOfRange { arity: 0 } => write!(
146 f,
147 "Invalid argument number ‘#{reference}’: ‘{name}’ has no numbered arguments"
148 ),
149 PlaceholderProblem::OutOfRange { arity: 1 } => write!(
150 f,
151 "Invalid argument number ‘#{reference}’: ‘{name}’ has only argument number ‘#1’"
152 ),
153 PlaceholderProblem::OutOfRange { arity } => write!(
154 f,
155 "Invalid argument number ‘#{reference}’: ‘{name}’ has arguments ‘#1’..‘#{arity}’"
156 ),
157 PlaceholderProblem::UnknownName => write!(
158 f,
159 "Invalid argument or placeholder name ‘#{reference}’ in ‘{name}’"
160 ),
161 PlaceholderProblem::NoBody => write!(
162 f,
163 "Invalid placeholder ‘#{reference}’; ‘{name}’ has no body"
164 ),
165 PlaceholderProblem::SubstitutionNotAccepted => write!(
166 f,
167 "Placeholder ‘#{reference}’ in definition of ‘{name}’ does not accept any \
168 bracketed modifiers (‘[…]’)"
169 ),
170 PlaceholderProblem::Unresolvable => write!(
171 f,
172 "No value for argument or placeholder ‘#{reference}’ in the definition of ‘{name}’"
173 ),
174 PlaceholderProblem::DefaultCycle => write!(
175 f,
176 "Cyclic recursion in default argument values for argument or placeholder \
177 ‘#{reference}’ in the definition of ‘{name}’"
178 ),
179 }
180 }
181}
182
183/// What is wrong with a definition as a whole: the detail of [`BadDefinition`].
184#[derive(Debug, Clone, PartialEq, Eq)]
185pub enum DefinitionProblem {
186 /// The definition declares no template at all (its `content` is `None`).
187 NoTemplate,
188 /// The definition was refused when the registry was built, so a use site has
189 /// nothing to expand into; the reason was reported then, among the registry's
190 /// build diagnostics. A use site that the expand pass reaches before the
191 /// templates are compiled has this problem too.
192 NotCompiled,
193 /// The use site is in a parsing mode where the definition does not apply. The
194 /// definition was declared for both modes with one template text, and that
195 /// text parses only in the other mode, which is then the only mode where the
196 /// definition applies (running text, or a formula).
197 NotInForceInMode {
198 /// The parsing mode of the use site.
199 mode: Mode,
200 },
201 /// A default value is declared for an argument the definition does not have.
202 UnknownDefault {
203 /// The key the default was declared under.
204 key: String,
205 },
206 /// The template language could not be built: [minting](crate::lang::mint) its
207 /// declarations, which turns them into the techy packages a parse looks
208 /// commands up in, failed. Those declarations are constants of the
209 /// [`template`](super::template) module, so this is not expected to happen.
210 Minting {
211 /// The minting error, as text.
212 detail: String,
213 },
214 /// The template parse returned no tree: the template's parsing state could not
215 /// be prepared, the [recursion guard](crate::lang::guard) refused deeply nested
216 /// content, or the parse was aborted.
217 ParseFailed {
218 /// The parse failure, as text.
219 detail: String,
220 },
221 /// The template refers to a *tack-on argument*: the argument that absorbs
222 /// the field macros written at its position in a call, after the arguments
223 /// declared before it, such as the `\label{…}` of
224 /// `\thm{Euclid}\label{thm:euclid}` (see
225 /// [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)).
226 ///
227 /// A template cannot use what a tack-on argument absorbs, on any backend: what
228 /// was absorbed is a run of whole macros, and those macros have no meaning as
229 /// the content of a placeholder (a `\label` has no meaning on its own in the
230 /// content a template produces). A definition may declare a tack-on argument and
231 /// leave it unused; referring to it is this problem. Reading the absorbed
232 /// information through a placeholder that queries it is intended and not
233 /// implemented.
234 TackOnPlaceholder {
235 /// The placeholder as written between the `#` and the end of the
236 /// placeholder (`2`, `fields`).
237 reference: String,
238 },
239}
240
241impl DefinitionProblem {
242 /// The stable token for the problem in diagnostic data.
243 pub fn kind(&self) -> &'static str {
244 match self {
245 DefinitionProblem::NoTemplate => "no-template",
246 DefinitionProblem::NotCompiled => "not-compiled",
247 DefinitionProblem::NotInForceInMode { .. } => "not-in-force-in-mode",
248 DefinitionProblem::UnknownDefault { .. } => "unknown-default",
249 DefinitionProblem::Minting { .. } => "minting",
250 DefinitionProblem::ParseFailed { .. } => "parse-failed",
251 DefinitionProblem::TackOnPlaceholder { .. } => "tack-on-placeholder",
252 }
253 }
254}
255
256/// Diagnostic data: a map holding the [`kind`](DefinitionProblem::kind) token
257/// and the fields: the `mode` of a use site where the definition does not
258/// apply (`text` or `math`), the `key` of an unknown default value, the
259/// `detail` of a minting or parse failure (the failure's own text, not this
260/// module's wording), or the `reference` of a placeholder that refers to a
261/// tack-on argument.
262impl ToDiagnosticValue for DefinitionProblem {
263 fn to_diagnostic_value(&self) -> DiagnosticValue {
264 let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
265 match self {
266 DefinitionProblem::UnknownDefault { key } => {
267 fields.push((String::from("key"), key.to_diagnostic_value()));
268 }
269 DefinitionProblem::Minting { detail } | DefinitionProblem::ParseFailed { detail } => {
270 fields.push((String::from("detail"), detail.to_diagnostic_value()));
271 }
272 DefinitionProblem::TackOnPlaceholder { reference } => {
273 fields.push((String::from("reference"), reference.to_diagnostic_value()));
274 }
275 DefinitionProblem::NotInForceInMode { mode } => {
276 fields.push((String::from("mode"), mode_token(*mode).to_diagnostic_value()));
277 }
278 DefinitionProblem::NoTemplate | DefinitionProblem::NotCompiled => {}
279 }
280 DiagnosticValue::Map(fields)
281 }
282}
283
284/// The stable token for a parsing mode in diagnostic data: `text` or `math`, the
285/// tokens with which a definition's modes are written
286/// ([`DefinitionModes::token`](super::DefinitionModes::token)).
287fn mode_token(mode: Mode) -> &'static str {
288 match mode {
289 Mode::Math => "math",
290 _ => "text",
291 }
292}
293
294/// How a message refers to a parsing mode
295fn mode_phrase(mode: Mode) -> &'static str {
296 match mode {
297 Mode::Math => "math mode",
298 _ => "text mode",
299 }
300}
301
302
303/// Condition `flm.userdefs.bad-definition`: a definition cannot be compiled as
304/// declared, found when the registry is built. With the problem
305/// [`NotCompiled`](DefinitionProblem::NotCompiled), the condition is reported at
306/// a use site of a definition that was refused then; with the problem
307/// [`NotInForceInMode`](DefinitionProblem::NotInForceInMode), at a use site in a
308/// parsing mode where the definition's template did not parse.
309///
310/// Recovery: when the registry is built, the definition is refused and the rest
311/// of the registry is built; at a use site, the use site is replaced by its
312/// literal source text.
313#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
314#[diagnostic(id = "flm.userdefs.bad-definition")]
315pub struct BadDefinition {
316 /// The definition, as an author writes it (`\foo`).
317 pub name: String,
318 /// What is wrong with the definition.
319 pub problem: DefinitionProblem,
320}
321
322impl fmt::Display for BadDefinition {
323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324 let BadDefinition { name, problem } = self;
325 match problem {
326 DefinitionProblem::NoTemplate => {
327 write!(f, "Missing definition template for ‘{name}’")
328 }
329 DefinitionProblem::NotCompiled => write!(
330 f,
331 "Failed to compile definition of ‘{name}’"
332 ),
333 DefinitionProblem::NotInForceInMode { mode } => write!(
334 f,
335 "Definition of ‘{name}’ fails to parse in {}",
336 mode_phrase(*mode)
337 ),
338 DefinitionProblem::UnknownDefault { key } => write!(
339 f,
340 "Default value given for invalid argument ‘{key}’ in definition of ‘{name}’"
341 ),
342 DefinitionProblem::Minting { detail } => write!(
343 f,
344 "Parsing the definition of ‘{name}’ failed (minting failed): {detail}"
345 ),
346 DefinitionProblem::ParseFailed { detail } => write!(
347 f,
348 "Parsing the definition of ‘{name}’ failed: {detail}"
349 ),
350 DefinitionProblem::TackOnPlaceholder { reference } => write!(
351 f,
352// ### Problem: this should not be a diagnostic. TackOnPlaceholder is a specific argument type. The BadDefinition diagnostic should know nothing about specific argument types.
353 "the definition of ‘{name}’ cannot be used: a template cannot refer to \
354 ‘#{reference}’: that argument collects the commands written after a call, such \
355 as ‘\\label’"
356 ),
357 }
358 }
359}
360
361/// Condition `flm.userdefs.expansion-failed`: the expand pass failed for a reason
362/// that no recovery covers. Either an internal error occurred while building the
363/// expanded tree (an invariant of a tree transformation was broken, or a region
364/// of a node could not be attached to its new nodes), or an expansion hook
365/// failed.
366///
367/// Recovery: none; the pass returns no tree, and this diagnostic says why.
368#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
369#[diagnostic(
370 id = "flm.userdefs.expansion-failed",
371 message = "Definition expansion pass failed: {detail}"
372)]
373pub struct ExpansionFailed {
374 /// The failure, as text.
375 pub detail: String,
376}
377
378#[cfg(test)]
379mod tests {
380 use super::*;
381
382 #[test]
383 fn a_placeholder_problem_projects_as_a_token_with_its_payload() {
384 let problem = PlaceholderProblem::OutOfRange { arity: 2 };
385 assert_eq!(
386 problem.to_diagnostic_value(),
387 DiagnosticValue::Map(vec![
388 (String::from("kind"), DiagnosticValue::Str(String::from("out-of-range"))),
389 (String::from("arity"), DiagnosticValue::Int(2)),
390 ])
391 );
392 }
393
394 #[test]
395 fn a_definition_problem_projects_as_a_token_with_its_payload() {
396 let problem = DefinitionProblem::UnknownDefault { key: String::from("zz") };
397 assert_eq!(
398 problem.to_diagnostic_value(),
399 DiagnosticValue::Map(vec![
400 (String::from("kind"), DiagnosticValue::Str(String::from("unknown-default"))),
401 (String::from("key"), DiagnosticValue::Str(String::from("zz"))),
402 ])
403 );
404 }
405}