flm-core 0.6.0

FLM semantic markup framework — core library, built on techy
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! The conditions that user-definition expansion reports. Their identifiers have
//! the form `flm.userdefs.<condition>`; a
//! [condition](crate::guide::concepts_overview#diagnostics) is the typed body of
//! a diagnostic.
//!
//! The module declares four conditions. Each arises when the **registry is
//! built**, while a definition's templates are compiled, at a **use site**,
//! while the [expand pass](super::expand) runs, or in both cases:
//!
//! - [`RecursionLimit`], at a use site while the expand pass runs: expanding the
//!   use site would exceed the expansion depth limit.
//! - [`BadPlaceholder`], when the registry is built, for a placeholder that
//!   refers to something the definition does not have or that is misused (the
//!   definition is then refused); at a use site, with the problem
//!   [`Unresolvable`](PlaceholderProblem::Unresolvable), for a placeholder that
//!   has no value there.
//! - [`BadDefinition`], when the registry is built, for a problem with the
//!   definition as a whole (the definition is then refused); at a use site, with
//!   the problem [`NotCompiled`](DefinitionProblem::NotCompiled), for a
//!   definition whose template was not compiled, or with the problem
//!   [`NotInForceInMode`](DefinitionProblem::NotInForceInMode), for a use in a
//!   parsing mode where the definition's one template text did not parse.
//! - [`ExpansionFailed`], for a failure of the expand pass itself: an internal
//!   error while building the expanded tree, or a failing expansion hook. The
//!   pass then returns no tree, and this diagnostic says why.
//!
//! For each condition reported at a use site, the use site is replaced by a text
//! node holding its literal source text, and one Error diagnostic at the use
//! site says why. No problem in a document makes the pass panic.
//!
//! Diagnostic data never carries the displayed text, so that a test that checks
//! the data does not depend on the wording. A problem type
//! ([`PlaceholderProblem`], [`DefinitionProblem`]) appears in the data as a map
//! with a stable `kind` token and the problem's fields. A problem type has no
//! text of its own: the condition that carries it ([`BadPlaceholder`],
//! [`BadDefinition`]) writes the whole message, one wording for each problem,
//! from the problem and the condition's other fields.

use std::fmt;

use techy::error::{DiagnosticInfo, DiagnosticValue, ToDiagnosticValue};
use techy::latexlike::Mode;

/// Condition `flm.userdefs.recursion-limit`: expanding a use site would exceed
/// the expansion depth limit, the number of expansions that one chain may nest
/// inside one another ([`ExpandOptions::recursion_limit`](super::ExpandOptions::recursion_limit)).
/// This limit is separate from the [recursion guard](crate::lang::guard), which
/// limits how deeply a tree may nest.
///
/// Recovery: the use site is replaced by its literal source text.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.userdefs.recursion-limit",
    message = "Recursion limit reached ({limit} levels) while expanding ‘{name}’"
)]
pub struct RecursionLimit {
    /// The definition whose use site could not be expanded, as an author
    /// writes it (`\foo`).
    pub name: String,
    /// The depth limit that applies.
    pub limit: usize,
}

/// What is wrong with a placeholder of a template: the detail of
/// [`BadPlaceholder`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PlaceholderProblem {
    /// A numbered placeholder beyond the definition's arguments.
    OutOfRange {
        /// How many arguments a numbered placeholder may refer to: the number of
        /// declared arguments minus the definition's argument number offset.
        arity: usize,
    },
    /// A named placeholder that matches no argument name and no placeholder name
    /// that an expansion hook of the definition computes.
    UnknownName,
    /// A `#{body}` placeholder in the template of a definition that has no body: a
    /// macro or a special character sequence.
    NoBody,
    /// A substitution argument (`#[…]{…}`) on a placeholder that takes none: a
    /// numbered or named argument, the body, or a computed placeholder name declared
    /// without one.
    SubstitutionNotAccepted,
    /// A placeholder that has no value at expansion time: the placeholder bindings
    /// of the use site give it none (no expansion hook computes it), or it is a
    /// placeholder left in content that an expansion hook built.
    Unresolvable,
    /// A default argument value that refers to itself through other default values.
    DefaultCycle,
}

impl PlaceholderProblem {
    /// The stable token for the problem in diagnostic data, which a test or a
    /// tool matches on; the wording belongs to the message alone.
    pub fn kind(&self) -> &'static str {
        match self {
            PlaceholderProblem::OutOfRange { .. } => "out-of-range",
            PlaceholderProblem::UnknownName => "unknown-name",
            PlaceholderProblem::NoBody => "no-body",
            PlaceholderProblem::SubstitutionNotAccepted => "substitution-not-accepted",
            PlaceholderProblem::Unresolvable => "unresolvable",
            PlaceholderProblem::DefaultCycle => "default-cycle",
        }
    }
}

/// Diagnostic data: a map holding the [`kind`](PlaceholderProblem::kind) token
/// and the fields (`arity` for an out-of-range placeholder), never the
/// displayed text, so that a test that checks the data does not depend on the
/// wording.
impl ToDiagnosticValue for PlaceholderProblem {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
        if let PlaceholderProblem::OutOfRange { arity } = self {
            fields.push((String::from("arity"), arity.to_diagnostic_value()));
        }
        DiagnosticValue::Map(fields)
    }
}

/// Condition `flm.userdefs.bad-placeholder`: a placeholder of a template that is
/// invalid (found when the registry is built) or that has no value at a use site
/// (found at expansion); [`PlaceholderProblem`] says which.
///
/// Recovery: when the registry is built, where templates are compiled, the
/// definition is refused; at expansion, the use site is replaced by its literal
/// source text.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.userdefs.bad-placeholder")]
pub struct BadPlaceholder {
    /// The definition whose template holds the placeholder, as an author
    /// writes it (`\foo`).
    pub name: String,
    /// The placeholder as written between the `#` and the end of the
    /// placeholder (`1`, `body`, `title`).
    pub reference: String,
    /// What is wrong with the placeholder.
    pub reason: PlaceholderProblem,
}

impl fmt::Display for BadPlaceholder {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let BadPlaceholder { name, reference, reason } = self;
        match reason {
            PlaceholderProblem::OutOfRange { arity: 0 } => write!(
                f,
                "Invalid argument number ‘#{reference}’: ‘{name}’ has no numbered arguments"
            ),
            PlaceholderProblem::OutOfRange { arity: 1 } => write!(
                f,
                "Invalid argument number ‘#{reference}’: ‘{name}’ has only argument number ‘#1’"
            ),
            PlaceholderProblem::OutOfRange { arity } => write!(
                f,
                "Invalid argument number ‘#{reference}’: ‘{name}’ has arguments ‘#1’..‘#{arity}’"
            ),
            PlaceholderProblem::UnknownName => write!(
                f,
                "Invalid argument or placeholder name ‘#{reference}’ in ‘{name}’"
            ),
            PlaceholderProblem::NoBody => write!(
                f,
                "Invalid placeholder ‘#{reference}’; ‘{name}’ has no body"
            ),
            PlaceholderProblem::SubstitutionNotAccepted => write!(
                f,
                "Placeholder ‘#{reference}’ in definition of ‘{name}’ does not accept any \
                 bracketed modifiers (‘[…]’)"
            ),
            PlaceholderProblem::Unresolvable => write!(
                f,
                "No value for argument or placeholder ‘#{reference}’ in the definition of ‘{name}’"
            ),
            PlaceholderProblem::DefaultCycle => write!(
                f,
                "Cyclic recursion in default argument values for argument or placeholder \
                 ‘#{reference}’ in the definition of ‘{name}’"
            ),
        }
    }
}

/// What is wrong with a definition as a whole: the detail of [`BadDefinition`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DefinitionProblem {
    /// The definition declares no template at all (its `content` is `None`).
    NoTemplate,
    /// The definition was refused when the registry was built, so a use site has
    /// nothing to expand into; the reason was reported then, among the registry's
    /// build diagnostics. A use site that the expand pass reaches before the
    /// templates are compiled has this problem too.
    NotCompiled,
    /// The use site is in a parsing mode where the definition does not apply. The
    /// definition was declared for both modes with one template text, and that
    /// text parses only in the other mode, which is then the only mode where the
    /// definition applies (running text, or a formula).
    NotInForceInMode {
        /// The parsing mode of the use site.
        mode: Mode,
    },
    /// A default value is declared for an argument the definition does not have.
    UnknownDefault {
        /// The key the default was declared under.
        key: String,
    },
    /// The template language could not be built: [minting](crate::lang::mint) its
    /// declarations, which turns them into the techy packages a parse looks
    /// commands up in, failed. Those declarations are constants of the
    /// [`template`](super::template) module, so this is not expected to happen.
    Minting {
        /// The minting error, as text.
        detail: String,
    },
    /// The template parse returned no tree: the template's parsing state could not
    /// be prepared, the [recursion guard](crate::lang::guard) refused deeply nested
    /// content, or the parse was aborted.
    ParseFailed {
        /// The parse failure, as text.
        detail: String,
    },
    /// The template refers to a *tack-on argument*: the argument that absorbs
    /// the field macros written at its position in a call, after the arguments
    /// declared before it, such as the `\label{…}` of
    /// `\thm{Euclid}\label{thm:euclid}` (see
    /// [fields](crate::guide::concepts_overview#fields-data-a-construct-reads)).
    ///
    /// A template cannot use what a tack-on argument absorbs, on any backend: what
    /// was absorbed is a run of whole macros, and those macros have no meaning as
    /// the content of a placeholder (a `\label` has no meaning on its own in the
    /// content a template produces). A definition may declare a tack-on argument and
    /// leave it unused; referring to it is this problem. Reading the absorbed
    /// information through a placeholder that queries it is intended and not
    /// implemented.
    TackOnPlaceholder {
        /// The placeholder as written between the `#` and the end of the
        /// placeholder (`2`, `fields`).
        reference: String,
    },
}

impl DefinitionProblem {
    /// The stable token for the problem in diagnostic data.
    pub fn kind(&self) -> &'static str {
        match self {
            DefinitionProblem::NoTemplate => "no-template",
            DefinitionProblem::NotCompiled => "not-compiled",
            DefinitionProblem::NotInForceInMode { .. } => "not-in-force-in-mode",
            DefinitionProblem::UnknownDefault { .. } => "unknown-default",
            DefinitionProblem::Minting { .. } => "minting",
            DefinitionProblem::ParseFailed { .. } => "parse-failed",
            DefinitionProblem::TackOnPlaceholder { .. } => "tack-on-placeholder",
        }
    }
}

/// Diagnostic data: a map holding the [`kind`](DefinitionProblem::kind) token
/// and the fields: the `mode` of a use site where the definition does not
/// apply (`text` or `math`), the `key` of an unknown default value, the
/// `detail` of a minting or parse failure (the failure's own text, not this
/// module's wording), or the `reference` of a placeholder that refers to a
/// tack-on argument.
impl ToDiagnosticValue for DefinitionProblem {
    fn to_diagnostic_value(&self) -> DiagnosticValue {
        let mut fields = vec![(String::from("kind"), self.kind().to_diagnostic_value())];
        match self {
            DefinitionProblem::UnknownDefault { key } => {
                fields.push((String::from("key"), key.to_diagnostic_value()));
            }
            DefinitionProblem::Minting { detail } | DefinitionProblem::ParseFailed { detail } => {
                fields.push((String::from("detail"), detail.to_diagnostic_value()));
            }
            DefinitionProblem::TackOnPlaceholder { reference } => {
                fields.push((String::from("reference"), reference.to_diagnostic_value()));
            }
            DefinitionProblem::NotInForceInMode { mode } => {
                fields.push((String::from("mode"), mode_token(*mode).to_diagnostic_value()));
            }
            DefinitionProblem::NoTemplate | DefinitionProblem::NotCompiled => {}
        }
        DiagnosticValue::Map(fields)
    }
}

/// The stable token for a parsing mode in diagnostic data: `text` or `math`, the
/// tokens with which a definition's modes are written
/// ([`DefinitionModes::token`](super::DefinitionModes::token)).
fn mode_token(mode: Mode) -> &'static str {
    match mode {
        Mode::Math => "math",
        _ => "text",
    }
}

/// How a message refers to a parsing mode
fn mode_phrase(mode: Mode) -> &'static str {
    match mode {
        Mode::Math => "math mode",
        _ => "text mode",
    }
}


/// Condition `flm.userdefs.bad-definition`: a definition cannot be compiled as
/// declared, found when the registry is built. With the problem
/// [`NotCompiled`](DefinitionProblem::NotCompiled), the condition is reported at
/// a use site of a definition that was refused then; with the problem
/// [`NotInForceInMode`](DefinitionProblem::NotInForceInMode), at a use site in a
/// parsing mode where the definition's template did not parse.
///
/// Recovery: when the registry is built, the definition is refused and the rest
/// of the registry is built; at a use site, the use site is replaced by its
/// literal source text.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(id = "flm.userdefs.bad-definition")]
pub struct BadDefinition {
    /// The definition, as an author writes it (`\foo`).
    pub name: String,
    /// What is wrong with the definition.
    pub problem: DefinitionProblem,
}

impl fmt::Display for BadDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let BadDefinition { name, problem } = self;
        match problem {
            DefinitionProblem::NoTemplate => {
                write!(f, "Missing definition template for ‘{name}’")
            }
            DefinitionProblem::NotCompiled => write!(
                f,
                "Failed to compile definition of ‘{name}’"
            ),
            DefinitionProblem::NotInForceInMode { mode } => write!(
                f,
                "Definition of ‘{name}’ fails to parse in {}",
                mode_phrase(*mode)
            ),
            DefinitionProblem::UnknownDefault { key } => write!(
                f,
                "Default value given for invalid argument ‘{key}’ in definition of ‘{name}’"
            ),
            DefinitionProblem::Minting { detail } => write!(
                f,
                "Parsing the definition of ‘{name}’ failed (minting failed): {detail}"
            ),
            DefinitionProblem::ParseFailed { detail } => write!(
                f,
                "Parsing the definition of ‘{name}’ failed: {detail}"
            ),
            DefinitionProblem::TackOnPlaceholder { reference } => write!(
                f,
// ### Problem: this should not be a diagnostic. TackOnPlaceholder is a specific argument type. The BadDefinition diagnostic should know nothing about specific argument types.
                "the definition of ‘{name}’ cannot be used: a template cannot refer to \
                 ‘#{reference}’: that argument collects the commands written after a call, such \
                 as ‘\\label’"
            ),
        }
    }
}

/// Condition `flm.userdefs.expansion-failed`: the expand pass failed for a reason
/// that no recovery covers. Either an internal error occurred while building the
/// expanded tree (an invariant of a tree transformation was broken, or a region
/// of a node could not be attached to its new nodes), or an expansion hook
/// failed.
///
/// Recovery: none; the pass returns no tree, and this diagnostic says why.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.userdefs.expansion-failed",
    message = "Definition expansion pass failed: {detail}"
)]
pub struct ExpansionFailed {
    /// The failure, as text.
    pub detail: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_placeholder_problem_projects_as_a_token_with_its_payload() {
        let problem = PlaceholderProblem::OutOfRange { arity: 2 };
        assert_eq!(
            problem.to_diagnostic_value(),
            DiagnosticValue::Map(vec![
                (String::from("kind"), DiagnosticValue::Str(String::from("out-of-range"))),
                (String::from("arity"), DiagnosticValue::Int(2)),
            ])
        );
    }

    #[test]
    fn a_definition_problem_projects_as_a_token_with_its_payload() {
        let problem = DefinitionProblem::UnknownDefault { key: String::from("zz") };
        assert_eq!(
            problem.to_diagnostic_value(),
            DiagnosticValue::Map(vec![
                (String::from("kind"), DiagnosticValue::Str(String::from("unknown-default"))),
                (String::from("key"), DiagnosticValue::Str(String::from("zz"))),
            ])
        );
    }
}