Skip to main content

badness_parser/
declarations.rs

1//! Project declarations for constructs syntax or semantics cannot infer from
2//! source without macro expansion.
3//!
4//! Declarations supplement the aliases found by [`crate::semantic::define`].
5//! They can describe environments defined in another file or through constructs
6//! the definition scanner does not recognize.
7//!
8//! Environment declarations name spellings, not pairings: shape gates still
9//! decide whether the source supports a construct. Command declarations are
10//! semantic-only ref/cite aliases and never affect tree shape.
11//!
12//! The schema follows three rules:
13//!
14//! 1. Each syntactic category has its own name map.
15//! 2. `like` copies a built-in entry from the same category. Cross-category
16//!    relationships use explicit fields such as [`EnvironmentDecl::begin`].
17//! 3. [`Declarations::resolve`] performs validation after deserialization so
18//!    errors can identify the original configuration key.
19//!
20//! These types are shared by all parser front ends. Their serialized field names
21//! are public API.
22
23use std::collections::BTreeMap;
24use std::fmt;
25
26use serde::{Deserialize, Serialize};
27use smol_str::SmolStr;
28
29use crate::parser::lexer::is_control_word_name;
30use crate::semantic::builder::{cite_command, ref_command};
31use crate::semantic::signature::{EnvironmentSig, SignatureDb, builtin};
32
33/// A control-word name as written in a declaration, stored **without** the
34/// leading backslash — the spelling every signature and `ParseCtx` map is keyed
35/// by.
36///
37/// Users write `\bea`, which in TOML wants a literal string (`'\bea'`) to avoid
38/// escaping. Both spellings are accepted and normalize to the same value: a
39/// control word can never itself contain a backslash, so there is nothing to
40/// disambiguate. Normalization lives in the type rather than at one call site so
41/// every front end gets it.
42#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
43#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
44#[serde(transparent)]
45pub struct CommandName(#[cfg_attr(feature = "schema", schemars(with = "String"))] SmolStr);
46
47impl CommandName {
48    /// Normalize `name` by stripping one leading backslash, if present.
49    pub fn new(name: &str) -> Self {
50        Self(SmolStr::new(name.strip_prefix('\\').unwrap_or(name)))
51    }
52
53    /// The name without its leading backslash.
54    pub fn as_str(&self) -> &str {
55        &self.0
56    }
57}
58
59impl From<&str> for CommandName {
60    fn from(name: &str) -> Self {
61        Self::new(name)
62    }
63}
64
65impl fmt::Display for CommandName {
66    /// Renders *with* the backslash, since that is how a diagnostic should spell
67    /// it back to the user.
68    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
69        write!(f, "\\{}", self.0)
70    }
71}
72
73impl<'de> Deserialize<'de> for CommandName {
74    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
75    where
76        D: serde::Deserializer<'de>,
77    {
78        let raw = String::deserialize(deserializer)?;
79        Ok(Self::new(&raw))
80    }
81}
82
83/// One `[environments.<name>]` entry: what the environment named by the key
84/// behaves like, and which command spellings stand in for its delimiters.
85///
86/// The key is the environment's *own* name, whether or not it is one the
87/// built-in database knows. That is what lets a single entry serve both shapes
88/// the issue asked for — `\begin{myenv} … \end{myenv}` needing only behavior,
89/// and `\startmyenv … \endmyenv` needing behavior *and* spellings — without a
90/// union-typed entry.
91#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
92#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
93#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
94pub struct EnvironmentDecl {
95    /// The curated built-in environment whose behavior this one copies — math,
96    /// alignment, list-ness, verbatim-ness, and every flag added later.
97    ///
98    /// Resolved against the built-in database alone, never the CWL tier or
99    /// scanned definitions, for the same reason the alias arm of
100    /// `Signatures::environment_at` is: a declaration supplies a *spelling*, and
101    /// behavior always comes from curated data. An unknown target is an error
102    /// rather than a silent no-op, because a mistyped `like = "algin"` is
103    /// otherwise invisible.
104    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
105    pub like: Option<SmolStr>,
106    /// Command spellings that stand in for this environment's `\begin{…}`
107    /// (`\bea`, `\startmyenv`). Any of them opens the environment; the closers
108    /// in [`end`](Self::end) close it — and so does the literal `\end{…}`, which
109    /// is why either list may stand alone (issue #117).
110    pub begin: Vec<CommandName>,
111    /// Command spellings that stand in for this environment's `\end{…}`. Kept a
112    /// separate list rather than begin/end tuples because pairing is by *kind*,
113    /// not by index: `\bea … \eea` pairs whichever spellings the author used.
114    pub end: Vec<CommandName>,
115}
116
117impl EnvironmentDecl {
118    /// Whether this entry declares delimiter spellings (as opposed to behavior
119    /// alone).
120    pub fn has_delimiters(&self) -> bool {
121        !self.begin.is_empty() || !self.end.is_empty()
122    }
123}
124
125/// The name-keyed `[environments]` map. A type alias so the CLI's `Config` can
126/// name the field's type without restating the key type.
127pub type EnvironmentDecls = BTreeMap<SmolStr, EnvironmentDecl>;
128
129/// One `[commands.<name>]` entry: the built-in reference or citation command
130/// whose semantic behavior the project command copies.
131#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
132#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
133#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
134pub struct CommandDecl {
135    /// The built-in reference or citation command whose key behavior is copied.
136    #[cfg_attr(feature = "schema", schemars(with = "Option<String>"))]
137    pub like: Option<SmolStr>,
138}
139
140/// The name-keyed `[commands]` declaration map.
141pub type CommandDecls = BTreeMap<SmolStr, CommandDecl>;
142
143/// Every declaration a project makes, as authored — unresolved and unvalidated.
144///
145/// `BTreeMap` rather than `HashMap` so iteration order is deterministic:
146/// resolution reports errors in the order the user reads them, and the value
147/// ends up on a salsa input whose equality must not depend on hash order.
148#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
149#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
150#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
151pub struct Declarations {
152    /// The `[commands.<name>]` semantic aliases.
153    #[cfg_attr(feature = "schema", schemars(with = "BTreeMap<String, CommandDecl>"))]
154    pub commands: CommandDecls,
155    /// The `[environments.<name>]` entries.
156    #[cfg_attr(
157        feature = "schema",
158        schemars(with = "BTreeMap<String, EnvironmentDecl>")
159    )]
160    pub environments: EnvironmentDecls,
161}
162
163impl Declarations {
164    /// Whether the project declares nothing at all — the overwhelmingly common
165    /// case, and the one the parse must not pay anything for.
166    pub fn is_empty(&self) -> bool {
167        self.commands.is_empty() && self.environments.is_empty()
168    }
169
170    /// Check every rule and project the declarations into a
171    /// [`ResolvedDeclarations`]: an environment signature per `like`, and the
172    /// delimiter spellings as opener and closer alias entries.
173    ///
174    /// Environment behavior and delimiter aliases resolve into a [`SignatureDb`]
175    /// so they fold into the existing scope machinery. Command aliases stay in a
176    /// separate deterministic map because they must not become parser or
177    /// formatter signatures.
178    ///
179    /// **Every failure is an error, never a silent no-op.** A declaration that
180    /// quietly does nothing is the worst outcome available here: the user sees
181    /// unchanged output and has no way to tell a typo from an unimplemented
182    /// feature. Errors surface in key order (the map is a `BTreeMap`), so the
183    /// message is stable across runs.
184    ///
185    /// An entry that declares behavior alone is unrestricted — `like =
186    /// "lstlisting"` is exactly how a project names a verbatim environment the
187    /// definition scan cannot find. The extra restrictions below apply only to
188    /// an entry that declares *delimiter spellings*, since those are the ones a
189    /// command has to stand in for. An entry that declares **nothing** is the
190    /// one shape rejected for saying too little rather than too much.
191    ///
192    /// One side alone is fine (issue #117): the literal `\begin{X}`/`\end{X}` is
193    /// a spelling of each side too, so `begin = ['\bsplit']` with no `end`
194    /// declares an opener the written-out `\end{split}` closes. This used to be
195    /// two errors, on the reasoning that a half-declared pair could never pair.
196    pub fn resolve(&self) -> Result<ResolvedDeclarations, DeclarationError> {
197        let mut db = SignatureDb::default();
198        let mut commands = BTreeMap::new();
199
200        for (name, entry) in &self.commands {
201            let error = |kind| DeclarationError {
202                key: dotted_key(["commands", name]),
203                kind,
204            };
205            if !is_control_word_name(name) {
206                return Err(error(DeclarationErrorKind::InvalidCommandName {
207                    name: SmolStr::new(name),
208                }));
209            }
210            if is_builtin_command(name) {
211                return Err(error(DeclarationErrorKind::BuiltinCommandName {
212                    name: SmolStr::new(name),
213                }));
214            }
215            let target = entry
216                .like
217                .as_ref()
218                .ok_or_else(|| error(DeclarationErrorKind::EmptyCommandEntry))?;
219            // The family tables alone decide what `like` copies, so they are the
220            // whole test. Requiring a `signatures.json` entry too would reject the
221            // targets a wrapper may need: that file carries layout data and omits
222            // citation commands such as `\supercite` and `\Textcite`.
223            if ref_command(target).is_none() && cite_command(target).is_none() {
224                return Err(DeclarationError {
225                    key: dotted_key(["commands", name, "like"]),
226                    kind: DeclarationErrorKind::UnknownCommandLikeTarget {
227                        target: target.clone(),
228                    },
229                });
230            }
231            commands.insert(name.clone(), target.clone());
232        }
233
234        // Which entry already claimed a spelling, so a second claim is an error
235        // rather than a last-writer-wins surprise.
236        let mut claimed: BTreeMap<SmolStr, SmolStr> = BTreeMap::new();
237
238        for (name, entry) in &self.environments {
239            let error = |kind| DeclarationError {
240                key: dotted_key(["environments", name]),
241                kind,
242            };
243
244            // An entry that says nothing is the one shape resolution could
245            // otherwise wave through, and it is exactly the shape a typo takes:
246            // `deny_unknown_fields` catches a misspelled key, but a user who
247            // wrote the header and nothing under it gets an entry that parses,
248            // resolves, and does nothing.
249            if entry.like.is_none() && !entry.has_delimiters() {
250                return Err(error(DeclarationErrorKind::EmptyEntry));
251            }
252
253            // `like` first: it decides the behavior every later rule reads.
254            let declared = match &entry.like {
255                Some(target) => {
256                    let sig = builtin()
257                        .environment(target)
258                        .ok_or_else(|| DeclarationError {
259                            key: dotted_key(["environments", name, "like"]),
260                            kind: DeclarationErrorKind::UnknownLikeTarget {
261                                target: target.clone(),
262                            },
263                        })?;
264                    db.insert_declared_environment(name.clone(), sig.clone());
265                    Some(sig)
266                }
267                None => None,
268            };
269
270            if !entry.has_delimiters() {
271                continue;
272            }
273
274            // A delimiter command has to stand in for *something*: an entry with
275            // no `like` falls back to the built-in of the same name, and an
276            // environment that is neither is one nothing downstream could
277            // resolve.
278            let sig: &EnvironmentSig = declared
279                .or_else(|| builtin().environment(name))
280                .ok_or_else(|| error(DeclarationErrorKind::UndeclaredTarget))?;
281            if sig.verbatim_body {
282                return Err(error(DeclarationErrorKind::VerbatimTarget));
283            }
284            if !sig.args.is_empty() {
285                return Err(error(DeclarationErrorKind::TargetTakesArguments));
286            }
287
288            for (side, spellings) in [("begin", &entry.begin), ("end", &entry.end)] {
289                let error = |kind| DeclarationError {
290                    key: dotted_key(["environments", name, side]),
291                    kind,
292                };
293                for spelling in spellings {
294                    // Named apart from the general not-a-control-word rule
295                    // because it is a *different mistake with a different fix*,
296                    // and the one the issue-#117 reporter actually made: reaching
297                    // for `end = ['\end{split}']` to say "closed by the written
298                    // -out delimiter". That is the default now, so the fix is to
299                    // delete the key — advice the generic message cannot give.
300                    if let Some(env) = literal_delimiter_target(spelling.as_str()) {
301                        return Err(error(DeclarationErrorKind::SpellingIsALiteralDelimiter {
302                            name: spelling.clone(),
303                            environment: SmolStr::new(env),
304                        }));
305                    }
306                    if !is_control_word_name(spelling.as_str()) {
307                        return Err(error(DeclarationErrorKind::NotAControlWord {
308                            name: spelling.clone(),
309                        }));
310                    }
311                    // A spelling the curated database already knows as a command
312                    // is a mistake we can name: `begin = ['\emph']` would turn
313                    // every `\emph` in the project into an environment opener
314                    // wherever the shape gate let it pair. Curated tier only,
315                    // for the same reason `like` is: the CWL tier carries every
316                    // package's names, so rejecting against it would refuse a
317                    // spelling on the say-so of a package the project never
318                    // loads. That leaves the check partial by construction — it
319                    // catches the arity-bearing commands, where a wrong pairing
320                    // also mis-attaches arguments — and it is a backstop, not
321                    // the safety property. The shape gate is still what keeps a
322                    // wrong declaration from corrupting a tree.
323                    if builtin().command(spelling.as_str()).is_some() {
324                        return Err(error(DeclarationErrorKind::SpellingIsABuiltinCommand {
325                            name: spelling.clone(),
326                        }));
327                    }
328                    let key = SmolStr::new(spelling.as_str());
329                    if let Some(first) = claimed.get(&key) {
330                        // Repeating a spelling *within* one entry is a different
331                        // mistake from two entries fighting over it, and reading
332                        // "already declared as a delimiter of `eqnarray`" under
333                        // `environments.eqnarray.begin` helps nobody.
334                        return Err(error(if first == name {
335                            DeclarationErrorKind::RepeatedDelimiter {
336                                name: spelling.clone(),
337                            }
338                        } else {
339                            DeclarationErrorKind::DuplicateDelimiter {
340                                name: spelling.clone(),
341                                first: first.clone(),
342                            }
343                        }));
344                    }
345                    claimed.insert(key.clone(), name.clone());
346                    if side == "begin" {
347                        db.insert_env_begin_alias(key, name.clone());
348                    } else {
349                        db.insert_env_end_alias(key, name.clone());
350                    }
351                }
352            }
353        }
354        Ok(ResolvedDeclarations { db, commands })
355    }
356}
357
358/// A project's declarations, checked and projected into signature data by
359/// [`Declarations::resolve`].
360///
361/// The environment signature tier plus semantic-only command aliases. This is
362/// the only signature data the parser accepts: a value can only come from a
363/// declaration block, so `parse_with_declarations` cannot be handed a document's
364/// merged package/definition scope. The parser reads only `db`; semantic-model
365/// construction reads `commands`.
366#[derive(Debug, Clone, Default, PartialEq, Eq)]
367pub struct ResolvedDeclarations {
368    db: SignatureDb,
369    commands: BTreeMap<SmolStr, SmolStr>,
370}
371
372impl ResolvedDeclarations {
373    /// The declared tier as signature data, for merging into a document's scope
374    /// (where it is the top tier: a declaration is the user explicitly
375    /// correcting an inference).
376    pub fn as_db(&self) -> &SignatureDb {
377        &self.db
378    }
379
380    /// The built-in semantic target of a declared command alias.
381    pub fn command_like(&self, name: &str) -> Option<&str> {
382        self.commands.get(name).map(SmolStr::as_str)
383    }
384
385    /// The declared command names, in deterministic order.
386    pub fn command_names(&self) -> impl Iterator<Item = &str> {
387        self.commands.keys().map(SmolStr::as_str)
388    }
389
390    /// Whether nothing was declared — the common case, and the one that must
391    /// cost the parse nothing.
392    pub fn is_empty(&self) -> bool {
393        self.db == SignatureDb::default() && self.commands.is_empty()
394    }
395
396    /// The parse-facing half of this block: the environment signature tier, with
397    /// the semantic command aliases dropped.
398    ///
399    /// The two halves are split so a reader depends only on the one it uses. A
400    /// command alias provably cannot change a tree
401    /// (`command_declarations_do_not_change_the_parse_tree`), so an incremental
402    /// front end can hold this half behind its own firewall and leave every parse
403    /// standing when only `[commands]` changed. The environment tier is what
404    /// [`parse_with_declarations`](crate::parser::parse_with_declarations) and the
405    /// signature scope read.
406    pub fn parse_tier(&self) -> Self {
407        Self {
408            db: self.db.clone(),
409            commands: BTreeMap::new(),
410        }
411    }
412
413    /// The semantic-facing half: the command aliases alone.
414    ///
415    /// The counterpart of [`parse_tier`](Self::parse_tier), read by
416    /// [`SemanticModel::build_with_declarations`](crate::semantic::SemanticModel::build_with_declarations),
417    /// which never looks at the environment tier. Together the two halves
418    /// partition the block: nothing is in both, and nothing in neither.
419    pub fn semantic_tier(&self) -> Self {
420        Self {
421            db: SignatureDb::default(),
422            commands: self.commands.clone(),
423        }
424    }
425}
426
427/// A rule [`Declarations::resolve`] rejected, with the dotted key of the entry
428/// that broke it (`environments.myenv.like`) so the CLI can point at the line
429/// the user wrote.
430///
431/// The key is a `String` rather than a borrowed path because the error outlives
432/// the borrow of the config in every caller, and this crate is wasm-clean: it
433/// knows nothing about the file the key came from, which is the CLI's to add.
434#[derive(Debug, Clone, PartialEq, Eq)]
435pub struct DeclarationError {
436    pub key: String,
437    pub kind: DeclarationErrorKind,
438}
439
440/// Why a declaration was rejected. Each variant is a rule from
441/// `AGENTS.md` decision #12 or its architecture section.
442#[derive(Debug, Clone, PartialEq, Eq)]
443pub enum DeclarationErrorKind {
444    /// A `[commands.<name>]` entry without its required `like` target.
445    EmptyCommandEntry,
446    /// A command map key that could never lex as one control word.
447    InvalidCommandName { name: SmolStr },
448    /// A declaration attempted to reclassify a curated built-in command.
449    BuiltinCommandName { name: SmolStr },
450    /// `like` did not name a curated reference or citation command.
451    UnknownCommandLikeTarget { target: SmolStr },
452    /// An entry with no keys at all. Nothing to reject it on rule grounds, and
453    /// nothing for it to do either — which is the outcome this module exists to
454    /// avoid.
455    EmptyEntry,
456    /// `like` named something the curated built-in database does not have.
457    /// Never resolved against the CWL tier or scanned definitions: behavior
458    /// comes from curated data only.
459    UnknownLikeTarget { target: SmolStr },
460    /// Delimiter spellings for a verbatim environment. Not conservatism but TeX
461    /// truth, which is why it is rejected rather than merely discouraged.
462    VerbatimTarget,
463    /// Delimiter spellings for an environment that takes arguments. A bare
464    /// control word carries none, and attaching them from the target's
465    /// signature would be arity-directed grouping from declaration data.
466    TargetTakesArguments,
467    /// Delimiter spellings for an environment whose behavior is unknown — no
468    /// `like`, and no built-in of that name.
469    UndeclaredTarget,
470    /// A spelling two entries both claim. Silently letting the last one win
471    /// would make the pairing depend on map order.
472    DuplicateDelimiter { name: CommandName, first: SmolStr },
473    /// A spelling one entry lists twice — across its two sides, or twice on
474    /// one. The [`DuplicateDelimiter`](Self::DuplicateDelimiter) mistake seen
475    /// from inside a single entry, where naming the "other" entry is no help.
476    RepeatedDelimiter { name: CommandName },
477    /// A spelling that *is* the written-out delimiter (`\end{split}`) rather
478    /// than a command standing in for one. A special case of
479    /// [`NotAControlWord`](Self::NotAControlWord) with its own fix: the literal
480    /// delimiter is already a spelling of both sides, so the key is redundant.
481    SpellingIsALiteralDelimiter {
482        name: CommandName,
483        environment: SmolStr,
484    },
485    /// A spelling the lexer could never produce as one control word, so it
486    /// could never match anything.
487    NotAControlWord { name: CommandName },
488    /// A spelling the curated database already knows as a command. Not a
489    /// no-op — it would take effect, on a command the project did not mean to
490    /// redefine.
491    SpellingIsABuiltinCommand { name: CommandName },
492}
493
494/// Whether the curated data already knows `name` as a command.
495///
496/// All three sources have to be asked, because `signatures.json` is not a
497/// superset of the ref/cite family tables: it carries layout data, and citation
498/// commands such as `\supercite` and `\Textcite` have no entry there.
499/// Asking it alone would let a declaration reclassify one of them: `like = "ref"`
500/// on `\supercite` would turn a citation into a label reference, which is exactly
501/// what this gate exists to prevent.
502fn is_builtin_command(name: &str) -> bool {
503    builtin().command(name).is_some() || ref_command(name).is_some() || cite_command(name).is_some()
504}
505
506/// The environment named by `spelling` when it is the written-out delimiter
507/// (`end{split}`, `begin{split}` — the leading backslash is already stripped by
508/// [`CommandName`]), or `None` for an ordinary command name.
509///
510/// Deliberately shape-only, with no check that the name is one badness knows: a
511/// user who writes `end = ['\end{myenv}']` made this mistake whether or not
512/// `myenv` exists, and pointing at the wrong rule would send them looking for a
513/// missing `like`.
514fn literal_delimiter_target(spelling: &str) -> Option<&str> {
515    let rest = spelling
516        .strip_prefix("begin")
517        .or_else(|| spelling.strip_prefix("end"))?;
518    let name = rest.strip_prefix('{')?.strip_suffix('}')?.trim();
519    (!name.is_empty()).then_some(name)
520}
521
522/// Join `segments` into a TOML dotted key, quoting any segment that is not a
523/// bare key so the result can be pasted back into `badness.toml`.
524///
525/// An environment may be named anything, and `environments.my.env` would point
526/// at a key the user never wrote.
527fn dotted_key<'a>(segments: impl IntoIterator<Item = &'a str>) -> String {
528    let mut key = String::new();
529    for segment in segments {
530        if !key.is_empty() {
531            key.push('.');
532        }
533        let bare = !segment.is_empty()
534            && segment
535                .chars()
536                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-');
537        if bare {
538            key.push_str(segment);
539        } else {
540            key.push('"');
541            key.push_str(&segment.replace('\\', "\\\\").replace('"', "\\\""));
542            key.push('"');
543        }
544    }
545    key
546}
547
548impl fmt::Display for DeclarationError {
549    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
550        write!(f, "`{}`: {}", self.key, self.kind)
551    }
552}
553
554impl fmt::Display for DeclarationErrorKind {
555    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556        match self {
557            Self::EmptyCommandEntry => write!(
558                f,
559                "declares nothing; add `like` naming a reference or citation command"
560            ),
561            Self::InvalidCommandName { name } => write!(
562                f,
563                "`{name}` is not a control-word name; command names may contain letters, `@`, `_`, or `:`"
564            ),
565            Self::BuiltinCommandName { name } => write!(
566                f,
567                "`\\{name}` is already a curated LaTeX command; command declarations may only name project commands"
568            ),
569            Self::UnknownCommandLikeTarget { target } => write!(
570                f,
571                "unknown reference or citation command `{target}`; `like` must name a curated ref/cite command"
572            ),
573            Self::EmptyEntry => write!(
574                f,
575                "declares nothing; add `like` to say what the environment behaves like, or \
576                 `begin`/`end` to give it delimiter spellings"
577            ),
578            Self::UnknownLikeTarget { target } => write!(
579                f,
580                "unknown environment `{target}`; `like` must name an environment badness \
581                 knows about"
582            ),
583            Self::VerbatimTarget => write!(
584                f,
585                "a command cannot stand in for a verbatim environment's delimiters, because \
586                 TeX never expands the closer — the verbatim scanner has already swallowed \
587                 it. Declare the environment name on its own, without `begin`/`end`"
588            ),
589            Self::TargetTakesArguments => write!(
590                f,
591                "the environment takes arguments, which a delimiter command cannot carry; \
592                 declare the environment name on its own, without `begin`/`end`"
593            ),
594            Self::UndeclaredTarget => write!(
595                f,
596                "declares delimiters for an environment badness does not know; add `like` \
597                 to say what it behaves like"
598            ),
599            Self::DuplicateDelimiter { name, first } => write!(
600                f,
601                "`{name}` is already declared as a delimiter of `{first}`"
602            ),
603            Self::RepeatedDelimiter { name } => {
604                write!(
605                    f,
606                    "`{name}` is listed twice as a delimiter of this environment"
607                )
608            }
609            Self::SpellingIsALiteralDelimiter { name, environment } => write!(
610                f,
611                "`{name}` is the delimiter itself, not a command standing in for one — and \
612                 badness already pairs a declared spelling with the written-out \
613                 `\\begin{{{environment}}}`/`\\end{{{environment}}}`, so this key can be \
614                 removed"
615            ),
616            Self::NotAControlWord { name } => write!(
617                f,
618                "`{name}` is not a control word; a delimiter must be a name of letters"
619            ),
620            Self::SpellingIsABuiltinCommand { name } => write!(
621                f,
622                "`{name}` is already a LaTeX command badness knows; a delimiter spelling must \
623                 be a command of your own, or the declaration would change what `{name}` means \
624                 everywhere in the project"
625            ),
626        }
627    }
628}
629
630impl std::error::Error for DeclarationError {}
631
632#[cfg(test)]
633mod tests {
634    use super::*;
635
636    fn from_json(json: &str) -> Declarations {
637        serde_json::from_str(json).expect("deserializes")
638    }
639
640    #[test]
641    fn empty_declarations_are_the_default() {
642        assert!(Declarations::default().is_empty());
643        assert!(from_json("{}").is_empty());
644    }
645
646    #[test]
647    fn a_command_may_declare_a_reference_family() {
648        let decls = from_json(r#"{"commands": {"eqrefs": {"like": "cref"}}}"#);
649        assert_eq!(decls.commands["eqrefs"].like.as_deref(), Some("cref"));
650        assert!(!decls.is_empty());
651    }
652
653    #[test]
654    fn an_entry_may_declare_behavior_alone() {
655        let decls = from_json(r#"{"environments": {"myenv": {"like": "align"}}}"#);
656        let entry = &decls.environments["myenv"];
657        assert_eq!(entry.like.as_deref(), Some("align"));
658        assert!(!entry.has_delimiters());
659        assert!(!decls.is_empty());
660    }
661
662    #[test]
663    fn an_entry_may_declare_delimiters_alone() {
664        let decls =
665            from_json(r#"{"environments": {"eqnarray": {"begin": ["\\bea"], "end": ["\\eea"]}}}"#);
666        let entry = &decls.environments["eqnarray"];
667        assert_eq!(entry.like, None);
668        assert!(entry.has_delimiters());
669        assert_eq!(entry.begin, vec![CommandName::new("bea")]);
670        assert_eq!(entry.end, vec![CommandName::new("eea")]);
671    }
672
673    #[test]
674    fn an_entry_may_declare_both() {
675        let decls = from_json(
676            r#"{"environments": {"mytheorem": {
677                 "like": "theorem",
678                 "begin": ["\\startmyenv"],
679                 "end": ["\\endmyenv"]
680               }}}"#,
681        );
682        let entry = &decls.environments["mytheorem"];
683        assert_eq!(entry.like.as_deref(), Some("theorem"));
684        assert_eq!(entry.begin, vec![CommandName::new("startmyenv")]);
685    }
686
687    #[test]
688    fn a_leading_backslash_is_optional_and_normalized_away() {
689        assert_eq!(CommandName::new("\\bea"), CommandName::new("bea"));
690        assert_eq!(CommandName::new("\\bea").as_str(), "bea");
691        let decls = from_json(r#"{"environments": {"e": {"begin": ["bea", "\\bea"]}}}"#);
692        assert_eq!(
693            decls.environments["e"].begin,
694            vec![CommandName::new("bea"), CommandName::new("bea")]
695        );
696    }
697
698    #[test]
699    fn only_one_backslash_is_stripped() {
700        assert_eq!(CommandName::new("\\\\").as_str(), "\\");
701    }
702
703    #[test]
704    fn display_restores_the_backslash() {
705        assert_eq!(CommandName::new("bea").to_string(), "\\bea");
706    }
707
708    #[test]
709    fn a_misspelled_key_is_rejected_rather_than_ignored() {
710        let err = serde_json::from_str::<Declarations>(
711            r#"{"environments": {"myenv": {"liek": "align"}}}"#,
712        )
713        .expect_err("unknown field is rejected");
714        assert!(err.to_string().contains("liek"), "{err}");
715
716        let err = serde_json::from_str::<Declarations>(r#"{"enviroments": {}}"#)
717            .expect_err("unknown section is rejected");
718        assert!(err.to_string().contains("enviroments"), "{err}");
719
720        let err =
721            serde_json::from_str::<Declarations>(r#"{"commands": {"eqrefs": {"liek": "cref"}}}"#)
722                .expect_err("unknown command field is rejected");
723        assert!(err.to_string().contains("liek"), "{err}");
724    }
725
726    #[test]
727    fn wire_spellings_are_pinned() {
728        let decls = from_json(
729            r#"{"commands": {"eqrefs": {"like": "cref"}},
730                "environments": {"myenv": {"like": "align", "begin": ["\\b"], "end": ["\\e"]}}}"#,
731        );
732        let json = serde_json::to_value(&decls).expect("serializes");
733        assert_eq!(json["commands"]["eqrefs"]["like"], "cref");
734        let entry = &json["environments"]["myenv"];
735        assert_eq!(entry["like"], "align");
736        assert_eq!(entry["begin"][0], "b");
737        assert_eq!(entry["end"][0], "e");
738    }
739
740    #[test]
741    fn environments_iterate_in_name_order() {
742        let decls = from_json(r#"{"environments": {"zed": {}, "alpha": {}, "mid": {}}}"#);
743        let names: Vec<&str> = decls.environments.keys().map(SmolStr::as_str).collect();
744        assert_eq!(names, ["alpha", "mid", "zed"]);
745    }
746
747    fn resolve(json: &str) -> SignatureDb {
748        from_json(json).resolve().expect("resolves").as_db().clone()
749    }
750
751    fn resolve_err(json: &str) -> DeclarationError {
752        from_json(json).resolve().expect_err("is rejected")
753    }
754
755    #[test]
756    fn nothing_declared_resolves_to_nothing() {
757        assert!(from_json("{}").resolve().expect("resolves").is_empty());
758    }
759
760    #[test]
761    fn command_families_resolve_with_target_behavior() {
762        let declared = from_json(
763            r#"{"commands": {
764                 "one": {"like": "eqref"},
765                 "many": {"like": "cref"},
766                 "sources": {"like": "parencite"},
767                 "everything": {"like": "nocite"}
768               }}"#,
769        )
770        .resolve()
771        .expect("resolves");
772
773        assert_eq!(declared.command_like("one"), Some("eqref"));
774        assert_eq!(declared.command_like("many"), Some("cref"));
775        assert_eq!(declared.command_like("sources"), Some("parencite"));
776        assert_eq!(declared.command_like("everything"), Some("nocite"));
777        assert!(
778            declared.as_db().command("many").is_none(),
779            "semantic aliases must not become formatter/parser signatures"
780        );
781        assert_eq!(
782            declared.command_names().collect::<Vec<_>>(),
783            vec!["everything", "many", "one", "sources"]
784        );
785    }
786
787    #[test]
788    fn like_may_name_a_family_command_absent_from_the_signature_database() {
789        for target in ["supercite", "Textcite", "fnotecite"] {
790            assert!(
791                builtin().command(target).is_none(),
792                "{target} is in signatures.json; pick another for this test"
793            );
794            let json = format!(r#"{{"commands": {{"wrapper": {{"like": "{target}"}}}}}}"#);
795            let declared = from_json(&json).resolve().expect("resolves");
796            assert_eq!(declared.command_like("wrapper"), Some(target));
797        }
798    }
799
800    #[test]
801    fn a_family_command_absent_from_the_signature_database_may_not_be_redeclared() {
802        for name in ["supercite", "Textcite", "fnotecite"] {
803            let json = format!(r#"{{"commands": {{"{name}": {{"like": "ref"}}}}}}"#);
804            let err = resolve_err(&json);
805            assert_eq!(err.key, format!("commands.{name}"), "{err}");
806            assert!(matches!(
807                err.kind,
808                DeclarationErrorKind::BuiltinCommandName { .. }
809            ));
810        }
811    }
812
813    #[test]
814    fn the_two_tiers_partition_the_block() {
815        let declared = from_json(
816            r#"{
817                 "commands": {"myref": {"like": "cref"}},
818                 "environments": {"mycode": {"like": "lstlisting"}}
819               }"#,
820        )
821        .resolve()
822        .expect("resolves");
823
824        let parse = declared.parse_tier();
825        assert_eq!(parse.as_db(), declared.as_db());
826        assert_eq!(parse.command_names().count(), 0);
827
828        let semantic = declared.semantic_tier();
829        assert_eq!(semantic.as_db(), &SignatureDb::default());
830        assert_eq!(semantic.command_like("myref"), Some("cref"));
831
832        assert!(!parse.is_empty() && !semantic.is_empty());
833        let recommanded = from_json(
834            r#"{
835                 "commands": {"myref": {"like": "eqref"}},
836                 "environments": {"mycode": {"like": "lstlisting"}}
837               }"#,
838        )
839        .resolve()
840        .expect("resolves");
841        assert_ne!(recommanded, declared);
842        assert_eq!(recommanded.parse_tier(), parse);
843        assert_ne!(recommanded.semantic_tier(), semantic);
844    }
845
846    #[test]
847    fn invalid_command_declarations_are_rejected() {
848        for (json, key) in [
849            (r#"{"commands": {"empty": {}}}"#, "commands.empty"),
850            (
851                r#"{"commands": {"wrapper": {"like": "emph"}}}"#,
852                "commands.wrapper.like",
853            ),
854            (
855                r#"{"commands": {"bad-name": {"like": "ref"}}}"#,
856                "commands.bad-name",
857            ),
858            (
859                r#"{"commands": {"section": {"like": "ref"}}}"#,
860                "commands.section",
861            ),
862        ] {
863            let err = resolve_err(json);
864            assert_eq!(err.key, key, "{err}");
865        }
866    }
867
868    #[test]
869    fn command_declarations_do_not_change_the_parse_tree() {
870        use crate::parser::{LatexFlavor, parse_with_declarations, parse_with_flavor};
871
872        let src = "\\eqrefs{a,b}\n";
873        let declared = from_json(r#"{"commands": {"eqrefs": {"like": "cref"}}}"#)
874            .resolve()
875            .expect("resolves");
876        assert_eq!(
877            parse_with_declarations(src, LatexFlavor::Document, &declared).green,
878            parse_with_flavor(src, LatexFlavor::Document).green
879        );
880    }
881
882    #[test]
883    fn like_copies_the_builtin_entry() {
884        let db = resolve(r#"{"environments": {"myenv": {"like": "align"}}}"#);
885        let sig = db.environment("myenv").expect("declared");
886        assert_eq!(sig, builtin().environment("align").expect("builtin"));
887        assert!(sig.math && sig.align);
888    }
889
890    #[test]
891    fn like_may_name_a_verbatim_environment() {
892        let db = resolve(r#"{"environments": {"mycode": {"like": "lstlisting"}}}"#);
893        assert!(db.environment("mycode").expect("declared").verbatim_body);
894    }
895
896    #[test]
897    fn like_may_name_an_argument_taking_environment() {
898        let db = resolve(r#"{"environments": {"mytab": {"like": "tabular"}}}"#);
899        assert!(!db.environment("mytab").expect("declared").args.is_empty());
900    }
901
902    #[test]
903    fn a_mistyped_like_target_is_an_error_not_a_silent_no_op() {
904        let err = resolve_err(r#"{"environments": {"myenv": {"like": "algin"}}}"#);
905        assert_eq!(err.key, "environments.myenv.like");
906        assert!(matches!(
907            err.kind,
908            DeclarationErrorKind::UnknownLikeTarget { .. }
909        ));
910        assert!(err.to_string().contains("algin"), "{err}");
911    }
912
913    #[test]
914    fn like_does_not_resolve_against_the_cwl_tier() {
915        let cwl_only = crate::semantic::signature::cwl()
916            .environment_names()
917            .find(|name| builtin().environment(name).is_none())
918            .expect("the CWL tier has an environment the curated one does not")
919            .to_string();
920        let err = resolve_err(&format!(
921            r#"{{"environments": {{"myenv": {{"like": "{cwl_only}"}}}}}}"#
922        ));
923        assert!(matches!(
924            err.kind,
925            DeclarationErrorKind::UnknownLikeTarget { .. }
926        ));
927    }
928
929    #[test]
930    fn delimiters_for_a_builtin_environment_need_no_like() {
931        let db =
932            resolve(r#"{"environments": {"eqnarray": {"begin": ["\\bea"], "end": ["\\eea"]}}}"#);
933        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
934        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
935        assert!(db.environment("eqnarray").is_none());
936    }
937
938    #[test]
939    fn delimiters_and_like_resolve_together() {
940        let db = resolve(
941            r#"{"environments": {"mytheorem": {
942                 "like": "theorem",
943                 "begin": ["\\startmyenv"],
944                 "end": ["\\endmyenv"]
945               }}}"#,
946        );
947        assert_eq!(db.env_begin_alias("startmyenv"), Some("mytheorem"));
948        assert!(db.environment("mytheorem").is_some());
949    }
950
951    #[test]
952    fn an_environment_may_have_several_spellings_per_side() {
953        let db = resolve(
954            r#"{"environments": {"eqnarray": {
955                 "begin": ["\\bea", "\\beqa"], "end": ["\\eea"]
956               }}}"#,
957        );
958        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
959        assert_eq!(db.env_begin_alias("beqa"), Some("eqnarray"));
960    }
961
962    #[test]
963    fn one_side_alone_resolves() {
964        let db = resolve(r#"{"environments": {"eqnarray": {"begin": ["\\bea"]}}}"#);
965        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
966        assert_eq!(db.env_end_alias("bea"), None);
967
968        let db = resolve(r#"{"environments": {"eqnarray": {"end": ["\\eea"]}}}"#);
969        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
970        assert_eq!(db.env_begin_alias("eea"), None);
971    }
972
973    #[test]
974    fn one_side_alone_still_obeys_every_target_rule() {
975        for json in [
976            r#"{"environments": {"verbatim": {"begin": ["\\bv"]}}}"#,
977            r#"{"environments": {"verbatim": {"end": ["\\ev"]}}}"#,
978        ] {
979            assert_eq!(resolve_err(json).kind, DeclarationErrorKind::VerbatimTarget);
980        }
981        assert_eq!(
982            resolve_err(r#"{"environments": {"tabular": {"begin": ["\\bt"]}}}"#).kind,
983            DeclarationErrorKind::TargetTakesArguments
984        );
985        assert_eq!(
986            resolve_err(r#"{"environments": {"myenv": {"end": ["\\e"]}}}"#).kind,
987            DeclarationErrorKind::UndeclaredTarget
988        );
989    }
990
991    #[test]
992    fn delimiters_for_a_verbatim_environment_are_rejected() {
993        let err =
994            resolve_err(r#"{"environments": {"verbatim": {"begin": ["\\bv"], "end": ["\\ev"]}}}"#);
995        assert_eq!(err.kind, DeclarationErrorKind::VerbatimTarget);
996
997        let err = resolve_err(
998            r#"{"environments": {"mycode": {
999                 "like": "lstlisting", "begin": ["\\bc"], "end": ["\\ec"]
1000               }}}"#,
1001        );
1002        assert_eq!(err.kind, DeclarationErrorKind::VerbatimTarget);
1003    }
1004
1005    #[test]
1006    fn delimiters_for_an_argument_taking_environment_are_rejected() {
1007        let err =
1008            resolve_err(r#"{"environments": {"tabular": {"begin": ["\\bt"], "end": ["\\et"]}}}"#);
1009        assert_eq!(err.kind, DeclarationErrorKind::TargetTakesArguments);
1010    }
1011
1012    #[test]
1013    fn delimiters_for_an_unknown_environment_ask_for_like() {
1014        let err = resolve_err(r#"{"environments": {"myenv": {"begin": ["\\b"], "end": ["\\e"]}}}"#);
1015        assert_eq!(err.kind, DeclarationErrorKind::UndeclaredTarget);
1016        assert!(err.to_string().contains("like"), "{err}");
1017    }
1018
1019    #[test]
1020    fn an_entry_that_declares_nothing_is_an_error() {
1021        let err = resolve_err(r#"{"environments": {"myenv": {}}}"#);
1022        assert_eq!(err.key, "environments.myenv");
1023        assert_eq!(err.kind, DeclarationErrorKind::EmptyEntry);
1024        assert!(err.to_string().contains("like"), "{err}");
1025    }
1026
1027    #[test]
1028    fn a_spelling_that_is_already_a_builtin_command_is_rejected() {
1029        let err =
1030            resolve_err(r#"{"environments": {"center": {"begin": ["\\emph"], "end": ["\\ec"]}}}"#);
1031        assert_eq!(err.key, "environments.center.begin");
1032        assert!(matches!(
1033            err.kind,
1034            DeclarationErrorKind::SpellingIsABuiltinCommand { .. }
1035        ));
1036        assert!(err.to_string().contains("emph"), "{err}");
1037    }
1038
1039    #[test]
1040    fn a_cwl_only_command_name_is_still_available_as_a_spelling() {
1041        let cwl_only = crate::semantic::signature::cwl()
1042            .command_names()
1043            .find(|name| {
1044                builtin().command(name).is_none() && is_control_word_name(name) && name.len() > 2
1045            })
1046            .expect("the CWL tier has a command the curated one does not")
1047            .to_string();
1048        let db = resolve(&format!(
1049            r#"{{"environments": {{"center": {{"begin": ["{cwl_only}"], "end": ["\\ec"]}}}}}}"#
1050        ));
1051        assert_eq!(db.env_begin_alias(&cwl_only), Some("center"));
1052    }
1053
1054    #[test]
1055    fn the_error_key_quotes_a_name_that_is_not_a_bare_key() {
1056        let err = resolve_err(r#"{"environments": {"my.env": {}}}"#);
1057        assert_eq!(err.key, r#"environments."my.env""#);
1058        let err = resolve_err(r#"{"environments": {"my env": {"like": "algin"}}}"#);
1059        assert_eq!(err.key, r#"environments."my env".like"#);
1060    }
1061
1062    #[test]
1063    fn a_spelling_may_not_be_claimed_twice() {
1064        let err = resolve_err(
1065            r#"{"environments": {
1066                 "align": {"begin": ["\\bx"], "end": ["\\ex"]},
1067                 "equation": {"begin": ["\\bx"], "end": ["\\ey"]}
1068               }}"#,
1069        );
1070        assert_eq!(
1071            err.kind,
1072            DeclarationErrorKind::DuplicateDelimiter {
1073                name: CommandName::new("bx"),
1074                first: SmolStr::new("align"),
1075            }
1076        );
1077    }
1078
1079    #[test]
1080    fn a_spelling_may_not_be_both_opener_and_closer() {
1081        let err = resolve_err(r#"{"environments": {"align": {"begin": ["\\x"], "end": ["\\x"]}}}"#);
1082        assert_eq!(err.key, "environments.align.end");
1083        assert_eq!(
1084            err.kind,
1085            DeclarationErrorKind::RepeatedDelimiter {
1086                name: CommandName::new("x"),
1087            }
1088        );
1089    }
1090
1091    #[test]
1092    fn the_written_out_delimiter_is_rejected_with_its_own_advice() {
1093        let err = resolve_err(
1094            r#"{"environments": {"split": {"begin": ["\\bsplit"], "end": ["\\end{split}"]}}}"#,
1095        );
1096        assert_eq!(err.key, "environments.split.end");
1097        assert!(
1098            matches!(
1099                err.kind,
1100                DeclarationErrorKind::SpellingIsALiteralDelimiter { .. }
1101            ),
1102            "{err:?}"
1103        );
1104        let rendered = err.to_string();
1105        assert!(rendered.contains("\\end{split}"), "{rendered}");
1106        assert!(rendered.contains("removed"), "{rendered}");
1107
1108        for json in [
1109            r#"{"environments": {"split": {"begin": ["\\begin{split}"]}}}"#,
1110            r#"{"environments": {"split": {"end": ["\\end{myenv}"]}}}"#,
1111        ] {
1112            assert!(
1113                matches!(
1114                    resolve_err(json).kind,
1115                    DeclarationErrorKind::SpellingIsALiteralDelimiter { .. }
1116                ),
1117                "{json}"
1118            );
1119        }
1120
1121        let db = resolve(r#"{"environments": {"center": {"begin": ["\\beginning"]}}}"#);
1122        assert_eq!(db.env_begin_alias("beginning"), Some("center"));
1123    }
1124
1125    #[test]
1126    fn a_spelling_that_could_never_lex_as_one_control_word_is_rejected() {
1127        for bad in ["b ea", "bea2", "", "b-ea"] {
1128            let json = format!(
1129                r#"{{"environments": {{"align": {{"begin": ["{bad}"], "end": ["\\ex"]}}}}}}"#
1130            );
1131            let err = resolve_err(&json);
1132            assert!(
1133                matches!(err.kind, DeclarationErrorKind::NotAControlWord { .. }),
1134                "`{bad}` should be rejected, got {err:?}"
1135            );
1136        }
1137    }
1138
1139    #[test]
1140    fn a_spelling_may_use_letters_of_any_catcode_regime() {
1141        let db =
1142            resolve(r#"{"environments": {"align": {"begin": ["\\my@b"], "end": ["\\my_e:n"]}}}"#);
1143        assert_eq!(db.env_begin_alias("my@b"), Some("align"));
1144        assert_eq!(db.env_end_alias("my_e:n"), Some("align"));
1145    }
1146
1147    #[test]
1148    fn the_resolved_tier_merges_like_any_other() {
1149        let declared = resolve(
1150            r#"{"environments": {"myenv": {"like": "align"}, "eqnarray": {
1151                 "begin": ["\\bea"], "end": ["\\eea"]
1152               }}}"#,
1153        );
1154        let mut scope = SignatureDb::default();
1155        scope.merge_from(&declared, None);
1156        assert!(scope.environment("myenv").is_some());
1157        assert_eq!(scope.env_begin_alias("bea"), Some("eqnarray"));
1158    }
1159
1160    fn environment_sig_at(src: &str, json: &str) -> Option<EnvironmentSig> {
1161        scope_and_sig_at(src, json).1
1162    }
1163
1164    fn scope_and_sig_at(src: &str, json: &str) -> (Option<EnvironmentSig>, Option<EnvironmentSig>) {
1165        use crate::parser::{LatexFlavor, parse_with_declarations};
1166        use crate::semantic::define::scan_definitions;
1167        use crate::semantic::signature::Signatures;
1168        use crate::syntax::{SyntaxKind, SyntaxNode};
1169
1170        let decls = from_json(json).resolve().expect("resolves");
1171        let parsed = parse_with_declarations(src, LatexFlavor::Document, &decls);
1172        let root = SyntaxNode::new_root(parsed.green);
1173        let mut scope = scan_definitions(&root);
1174        scope.merge_declarations(&decls);
1175        let node = root
1176            .descendants()
1177            .find(|n| n.kind() == SyntaxKind::ENVIRONMENT)
1178            .expect("an environment");
1179        let sigs = Signatures::new(&scope);
1180        (
1181            sigs.environment("eqnarray").cloned(),
1182            sigs.environment_at(&node).cloned(),
1183        )
1184    }
1185
1186    #[test]
1187    fn a_declared_alias_resolves_to_a_declared_target() {
1188        let sig = environment_sig_at(
1189            "\\startmyenv x \\endmyenv\n",
1190            r#"{"environments": {"myenv": {
1191                 "like": "align", "begin": ["\\startmyenv"], "end": ["\\endmyenv"]
1192               }}}"#,
1193        )
1194        .expect("the alias resolves");
1195        assert_eq!(&sig, builtin().environment("align").expect("curated"));
1196    }
1197
1198    #[test]
1199    fn a_scanned_definition_still_lends_an_alias_nothing() {
1200        let (scanned, sig) = scope_and_sig_at(
1201            "\\newenvironment{eqnarray}{}{}\n\\bea x \\eea\n",
1202            r#"{"environments": {"eqnarray": {"begin": ["\\bea"], "end": ["\\eea"]}}}"#,
1203        );
1204        let sig = sig.expect("the alias resolves");
1205        assert_eq!(&sig, builtin().environment("eqnarray").expect("curated"));
1206        let scanned = scanned.expect("the scan records the redefinition");
1207        assert!(!scanned.math, "the scanned redefinition is not math");
1208        assert!(sig.math, "the alias resolves to the curated entry");
1209    }
1210}