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