Skip to main content

badness_parser/semantic/
define.rs

1//! Scan a document for **user definitions** — `\newcommand`/`\newenvironment` and
2//! the xparse `\NewDocument…` family — and extract their argument *signatures* into
3//! a per-document [`SignatureDb`]. The scanner reads declared argument shapes,
4//! but neither interprets replacement text nor executes definitions.
5//!
6//! A single whole-tree walk (mirror of [`super::builder::build`]) collects every
7//! definition; the result overlays the built-in DB via [`Signatures`] (scanned
8//! first). The greedy parser attaches definitions like any other command, so they
9//! surface as plain `COMMAND` descendants — those inside a comment or a verbatim
10//! body never parse to a `COMMAND`, so they are skipped for free.
11//!
12//! [`Signatures`]: super::signature::Signatures
13//!
14//! ## Both name forms
15//!
16//! For command definitions we extract **both** name forms: the braced
17//! `\newcommand{\foo}…` and the unbraced `\newcommand\foo…`. The unbraced form
18//! parses awkwardly under greedy attachment — `\foo` becomes a *sibling* `COMMAND`
19//! and the `[n]`/replacement group attaches to it, not to `\newcommand` — so
20//! `\newcommand` itself has no name group. We recover it with a scanner-side sibling
21//! heuristic ([`resolve_command_def`]): when a definition command has no attached
22//! group, the name and argument shape are read off the immediately-following sibling
23//! `COMMAND`. This stays in the scanner — no parser change — so the parser remains
24//! meaning-free (decision #2). Environment names are brace-delimited *text*, never a
25//! bare control word, so they have no unbraced form to recover.
26
27use std::collections::{HashMap, HashSet};
28
29use crate::ast::{
30    AstNode, AstToken, Command, ControlWord, Optional, child, child_token, children, command_name,
31    control_word_range, group_command_name, group_inner_source, nth_group, nth_group_inner,
32    nth_group_text,
33};
34use crate::semantic::signature::{
35    ArgKind, ArgSpec, CommandSig, ContentKind, EnvironmentSig, SignatureDb, builtin,
36};
37use crate::semantic::xparse;
38use crate::syntax::{SyntaxKind, SyntaxNode, is_collapsible_trivia, is_trivia};
39use rowan::{NodeOrToken, TextRange, TextSize};
40use smol_str::SmolStr;
41
42/// Scan `root` for user command/environment definitions and return their extracted
43/// signatures. Names already defined earlier in the document are overwritten, so a
44/// later `\renewcommand` wins — TeX's last-definition-wins, modulo execution order
45/// we do not track.
46pub fn scan_definitions(root: &SyntaxNode) -> SignatureDb {
47    let mut db = SignatureDb::default();
48    // Replacement-body facts collected alongside each command signature, keyed by
49    // name (last definition wins, mirroring `db`). Consumed after the walk to flag
50    // catcode-othering verbatim-argument commands (`apply_verbatim_flags`).
51    let mut bodies: HashMap<SmolStr, DefBody> = HashMap::new();
52    // The same for environment *begin-code*, kept in a separate map because
53    // environment names live in a different namespace from commands (and so a name
54    // collision must not let one shadow the other during chain resolution). The
55    // begin-code's *called* helpers are resolved against the command `bodies` map.
56    let mut env_bodies: HashMap<SmolStr, DefBody> = HashMap::new();
57    // Environment-alias candidates: a zero-arity definition whose body is exactly
58    // `\begin{X}` or `\end{X}`. Collected raw during the walk (last definition
59    // wins, like `db`) and filtered by [`apply_env_aliases`] afterwards, since
60    // admitting one requires seeing the *other* half of the pair.
61    let mut alias_candidates: HashMap<SmolStr, EnvAliasCandidate> = HashMap::new();
62
63    for command in root
64        .descendants()
65        .filter(|node| node.kind() == SyntaxKind::COMMAND)
66    {
67        let Some(name) = command_name(&command) else {
68            continue;
69        };
70        match DefKind::of(&name) {
71            Some(DefKind::Command) => {
72                scan_newcommand(&command, &mut db, &mut bodies, &mut alias_candidates)
73            }
74            Some(DefKind::Def) => scan_def(&command, &mut db, &mut bodies, &mut alias_candidates),
75            Some(DefKind::Environment) => scan_newenvironment(&command, &mut db, &mut env_bodies),
76            Some(DefKind::XparseCommand) => {
77                scan_xparse_command(&command, &mut db, &mut bodies, &mut alias_candidates)
78            }
79            Some(DefKind::XparseEnvironment) => {
80                scan_xparse_environment(&command, &mut db, &mut env_bodies)
81            }
82            Some(DefKind::VerbatimEnvironment) => {
83                scan_verbatim_environment(&name, &command, &mut db)
84            }
85            None => {}
86        }
87    }
88
89    apply_verbatim_flags(&mut db, &bodies);
90    apply_verbatim_env_flags(&mut db, &env_bodies, &bodies);
91    apply_env_aliases(&mut db, &alias_candidates);
92    db
93}
94
95/// Which delimiter of an environment a definition body stands in for.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97enum AliasSide {
98    Begin,
99    End,
100}
101
102/// One unfiltered environment-alias candidate: the side its body spells and the
103/// environment it names. Admission is decided later by [`apply_env_aliases`],
104/// which needs the whole file's candidates to check that both halves exist.
105#[derive(Debug, Clone)]
106struct EnvAliasCandidate {
107    side: AliasSide,
108    target: SmolStr,
109}
110
111/// Read a definition's replacement `body` group as an environment delimiter: the
112/// body must be *exactly* `\begin{X}` or `\end{X}` and nothing else.
113///
114/// Reads the **CST**, not `group_inner_source`: the formatter may re-space inside
115/// the body, and `{\begin{eqnarray}}` and `{ \begin{eqnarray} }` must detect
116/// identically or the alias table would not survive a reformat (the pass-1/pass-2
117/// fixed point). Whitespace, newlines, and comments are skipped for the same
118/// reason; anything else present makes this not a delimiter definition.
119///
120/// Inside a definition body `\begin` is a plain `COMMAND` (the grammar sets
121/// `in_def_body`), so this never has to look through an `ENVIRONMENT` node.
122fn env_alias_body(body: &SyntaxNode) -> Option<EnvAliasCandidate> {
123    let mut sole: Option<SyntaxNode> = None;
124    for child in body.children_with_tokens() {
125        match child {
126            NodeOrToken::Token(t) => match t.kind() {
127                // The group's own delimiters, plus the trivia a reformat may move.
128                SyntaxKind::L_BRACE | SyntaxKind::R_BRACE | SyntaxKind::COMMENT => {}
129                k if is_collapsible_trivia(k) => {}
130                _ => return None,
131            },
132            // A second node means the body does more than open the environment.
133            NodeOrToken::Node(n) => {
134                if sole.replace(n).is_some() {
135                    return None;
136                }
137            }
138        }
139    }
140    let cmd = sole?;
141    if cmd.kind() != SyntaxKind::COMMAND {
142        return None;
143    }
144    // Exactly one attached child, the name group — so `\begin{tabular}{cc}` (two
145    // groups) is not a bare delimiter and does not read as one.
146    if cmd.children().count() != 1 {
147        return None;
148    }
149    let side = match command_name(&cmd)?.as_str() {
150        "begin" => AliasSide::Begin,
151        "end" => AliasSide::End,
152        _ => return None,
153    };
154    let target = nth_group_text(&cmd, 0)?;
155    let target = target.trim();
156    if target.is_empty() {
157        return None;
158    }
159    Some(EnvAliasCandidate {
160        side,
161        target: SmolStr::new(target),
162    })
163}
164
165/// Record an alias candidate for a zero-arity definition. Non-zero arity is
166/// rejected here: an alias head consumes no arguments (the grammar never calls
167/// `attach_arguments` on one), so a parameterized delimiter would silently drop
168/// its arguments into the body.
169fn record_env_alias(
170    candidates: &mut HashMap<SmolStr, EnvAliasCandidate>,
171    name: &str,
172    arity: usize,
173    body: Option<&SyntaxNode>,
174) {
175    // A later definition of the same name wins, mirroring `db`; but it must also
176    // be able to *retract* an earlier alias, or `\renewcommand{\bea}{\textbf}`
177    // would leave the stale entry standing.
178    candidates.remove(name);
179    if arity != 0 {
180        return;
181    }
182    if let Some(candidate) = body.and_then(env_alias_body) {
183        candidates.insert(SmolStr::new(name), candidate);
184    }
185}
186
187/// Promote the alias candidates that survive every admission rule into `db`.
188///
189/// The rules are narrow on purpose — an alias makes the *parser* pair two bare
190/// control words into an `ENVIRONMENT`, and a wrong pairing rewrites layout:
191///
192/// - **The target must be a curated built-in environment.** An alias declares a
193///   *spelling*, never a *semantic*; every behavior flag still comes from curated
194///   data, exactly as `is_math_environment` requires (AGENTS.md decision #1).
195/// - **The target must not be verbatim.** `\newcommand{\bv}{\begin{verbatim}}`
196///   genuinely does not work in TeX — `verbatim` others catcodes, and the body is
197///   already tokenized by the time the macro expands — so pairing it would model a
198///   construct that does not exist.
199/// - **The target must take no arguments.** The alias head consumes none, so an
200///   `array` alias would drop its column spec into the body and the formatter
201///   would grid it with no alignments.
202///
203/// One rule that used to be here is gone: **both halves no longer have to be
204/// defined**. It read "a lone opener can never pair anyway (no closer to
205/// locate)", and that stopped being true when the *literal* delimiter joined
206/// each side's spellings (issue #117): `\def\bsplit{\begin{split}}` expands to
207/// `\begin{split}`, so a plain `\end{split}` closes it, and a lone
208/// `\def\eeq{\end{equation}}` closes a plain `\begin{equation}`. The cost half
209/// of that rationale is carried by `parser::core::parse_ctx`'s "is it called
210/// anywhere" filter, which is what actually keeps an unused alias from buying a
211/// file a second parse.
212fn apply_env_aliases(db: &mut SignatureDb, candidates: &HashMap<SmolStr, EnvAliasCandidate>) {
213    let admissible = |target: &str| {
214        builtin()
215            .environment(target)
216            .is_some_and(|sig| !sig.verbatim_body && sig.args.is_empty())
217    };
218    for (name, candidate) in candidates {
219        let target = candidate.target.as_str();
220        if !admissible(target) {
221            continue;
222        }
223        match candidate.side {
224            AliasSide::Begin => {
225                db.insert_env_begin_alias(name.clone(), candidate.target.clone());
226            }
227            AliasSide::End => {
228                db.insert_env_end_alias(name.clone(), candidate.target.clone());
229            }
230        }
231    }
232}
233
234/// Which namespace a scanned definition site names. Commands and environments live
235/// in disjoint TeX namespaces, so a name match is only meaningful within a kind.
236#[derive(Debug, Clone, Copy, PartialEq, Eq)]
237pub enum DefSiteKind {
238    Command,
239    Environment,
240}
241
242/// One user definition's *location* — the range-bearing sibling of the signature
243/// facts [`scan_definitions`] extracts. Signatures stay range-free so the
244/// `document_signatures` salsa query backdates on pure-offset edits; definition
245/// sites feed LSP navigation (goto-definition, references, rename), which needs
246/// byte ranges and recomputes them per request off the memoized tree.
247#[derive(Debug, Clone, PartialEq, Eq)]
248pub struct DefSite {
249    /// The defined name (no leading `\` for commands).
250    pub name: SmolStr,
251    pub kind: DefSiteKind,
252    /// The defined name's own span. For a command this is the `\name` control-word
253    /// token, backslash included, so it compares equal to the same token found by an
254    /// occurrence walk; for an environment it is the name text between the braces of
255    /// `\newenvironment{name}` (the [`environment_name_range`] convention).
256    ///
257    /// [`environment_name_range`]: crate::ast::environment_name_range
258    pub name_range: TextRange,
259    /// The whole definition's span, through the sibling name `COMMAND` in the
260    /// unbraced `\newcommand\foo…`/`\def\foo…` forms.
261    pub range: TextRange,
262}
263
264/// Scan `root` for user command/environment definitions and return their *sites*, in
265/// document order. Same recognizer set and name resolution as [`scan_definitions`]
266/// (the [`DefKind`] dispatch and [`resolve_command_def`] sibling heuristic), but
267/// keeping every definition — no last-wins collapsing, since a `\renewcommand` of an
268/// earlier definition is still a definition site the user may navigate to or rename.
269pub fn scan_definition_sites(root: &SyntaxNode) -> Vec<DefSite> {
270    let mut sites = Vec::new();
271    for command in root
272        .descendants()
273        .filter(|node| node.kind() == SyntaxKind::COMMAND)
274    {
275        let Some(name) = command_name(&command) else {
276            continue;
277        };
278        let site = match DefKind::of(&name) {
279            Some(DefKind::Command | DefKind::XparseCommand) => command_def_site(&command),
280            Some(DefKind::Def) => def_def_site(&command),
281            Some(
282                DefKind::Environment | DefKind::XparseEnvironment | DefKind::VerbatimEnvironment,
283            ) => environment_def_site(&command),
284            None => None,
285        };
286        sites.extend(site);
287    }
288    sites
289}
290
291/// The [`DefSite`] of a `\newcommand`/xparse command definition, resolving the same
292/// two name forms as [`resolve_command_def`]: braced `{\name}` (the control word
293/// inside the name group) and unbraced `\newcommand\name` (the sibling `COMMAND`
294/// hosting the signature groups).
295fn command_def_site(command: &SyntaxNode) -> Option<DefSite> {
296    let def = resolve_command_def(command)?;
297    let name_range = if def.first_arg_group == 1 {
298        let group = nth_group(command, 0)?;
299        child::<Command>(&group)?.control_word_range()?
300    } else {
301        control_word_range(&def.host)?
302    };
303    Some(DefSite {
304        name: SmolStr::new(&def.name),
305        kind: DefSiteKind::Command,
306        name_range,
307        range: TextRange::new(
308            command.text_range().start(),
309            command.text_range().end().max(def.host.text_range().end()),
310        ),
311    })
312}
313
314/// The [`DefSite`] of a `\def`-family definition — the name is always the
315/// immediately-following sibling `COMMAND` (TeX has no braced `\def{\name}` form).
316fn def_def_site(command: &SyntaxNode) -> Option<DefSite> {
317    let name_node = adjacent_sibling_command(command)?;
318    let name = command_name(&name_node)?;
319    let name_range = control_word_range(&name_node)?;
320    Some(DefSite {
321        name: SmolStr::new(&name),
322        kind: DefSiteKind::Command,
323        name_range,
324        range: TextRange::new(command.text_range().start(), name_node.text_range().end()),
325    })
326}
327
328/// The [`DefSite`] of a `\newenvironment`/xparse environment definition. The name is
329/// brace-delimited *text* in group 0; the recorded span is the trimmed name within
330/// the group's inner range, mirroring the `.trim()` in [`scan_newenvironment`].
331fn environment_def_site(command: &SyntaxNode) -> Option<DefSite> {
332    let (inner_range, text) = nth_group_inner(command, 0)?;
333    let trimmed = text.trim();
334    if trimmed.is_empty() {
335        return None;
336    }
337    let leading = text.len() - text.trim_start().len();
338    let name_range = TextRange::at(
339        inner_range.start() + TextSize::new(leading as u32),
340        TextSize::new(trimmed.len() as u32),
341    );
342    Some(DefSite {
343        name: SmolStr::new(trimmed),
344        kind: DefSiteKind::Environment,
345        name_range,
346        range: command.text_range(),
347    })
348}
349
350/// Replacement-body facts for one scanned command definition, used to detect
351/// verbatim-argument commands without executing anything. We read only *static*
352/// surface text of the body — no macro expansion (AGENTS.md decision #1).
353struct DefBody {
354    /// A catcode-othering signal appears directly in this command's own body
355    /// (`\@makeother`, `\catcode…12`, `\dospecials`, …) — see [`catcode_signal`].
356    signal: bool,
357    /// Control words the body invokes, so chained helpers can be followed to find a
358    /// catcode signal one or more hops away (jss's `\code`→helper idiom).
359    called: Vec<SmolStr>,
360}
361
362/// Flag user commands whose argument is verbatim. A command is verbatim when it
363/// **takes at least one argument** (so it grabs the user's `{…}` itself) **and** a
364/// catcode-othering signal is reachable from its body — present directly, or in the
365/// body of a scanned macro it transitively calls. Conservative by construction
366/// (AGENTS.md): a wrong flag *suppresses* real diagnostics inside the body, so we
367/// flag only on a clear catcode signal and otherwise leave the body ordinary.
368///
369/// On a match we adopt the built-in convention: only the *leading* (non-verbatim)
370/// arguments stay in `args`; the final argument becomes the implicit verbatim one, so
371/// we drop the last `ArgSpec` and set `verbatim = true`. This keeps the lexer's
372/// `lex_verbatim_command` path uniform between built-in and user commands.
373fn apply_verbatim_flags(db: &mut SignatureDb, bodies: &HashMap<SmolStr, DefBody>) {
374    let verbatim: Vec<SmolStr> = bodies
375        .keys()
376        .filter(|name| {
377            // Needs an argument of its own to capture, and a reachable signal.
378            db.command(name).is_some_and(|sig| !sig.args.is_empty())
379                && reaches_signal(name, bodies, &mut HashSet::new())
380        })
381        .cloned()
382        .collect();
383
384    for name in verbatim {
385        if let Some(mut sig) = db.command(&name).cloned() {
386            sig.args.to_mut().pop(); // the final argument is the implicit verbatim one
387            sig.verbatim = true;
388            db.insert_command(name, sig);
389        }
390    }
391}
392
393/// Flag user environments whose body is verbatim — the environment analog of
394/// [`apply_verbatim_flags`]. An environment is verbatim when a catcode-othering signal
395/// is reachable from its **begin-code** (the first definition body), directly or via a
396/// chained helper command. Unlike commands, no argument is dropped: an environment's
397/// declared args are all leading and its body follows the `\begin{…}…` arguments, so
398/// we only flip `verbatim_body`. The begin-code's called
399/// helpers are resolved against the *command* `bodies` map (`\newcommand`/`\def`
400/// helpers live there). Conservative by construction, like the command case.
401fn apply_verbatim_env_flags(
402    db: &mut SignatureDb,
403    env_bodies: &HashMap<SmolStr, DefBody>,
404    bodies: &HashMap<SmolStr, DefBody>,
405) {
406    let verbatim: Vec<SmolStr> = env_bodies
407        .iter()
408        .filter(|(name, body)| {
409            db.environment(name).is_some() && reaches_signal_body(body, bodies, &mut HashSet::new())
410        })
411        .map(|(name, _)| name.clone())
412        .collect();
413
414    for name in verbatim {
415        if let Some(mut sig) = db.environment(&name).cloned() {
416            sig.verbatim_body = true;
417            db.insert_environment(name, sig);
418        }
419    }
420}
421
422/// Whether a catcode-othering signal is reachable from `name`'s body, following
423/// chained helper macros within the scanned definition set. A `visited` set breaks
424/// definition cycles (mutually recursive helpers terminate). A helper defined via
425/// `\def` (not scanned) is absent from `bodies`, so the chain breaks there and we do
426/// not flag — the conservative false-negative.
427fn reaches_signal(
428    name: &str,
429    bodies: &HashMap<SmolStr, DefBody>,
430    visited: &mut HashSet<SmolStr>,
431) -> bool {
432    if !visited.insert(SmolStr::new(name)) {
433        return false;
434    }
435    let Some(body) = bodies.get(name) else {
436        return false;
437    };
438    reaches_signal_body(body, bodies, visited)
439}
440
441/// Whether a catcode-othering signal is reachable from a definition `body` —
442/// present directly, or in the body of a scanned command it transitively calls. The
443/// body-level entry point used both by [`reaches_signal`] (after a name lookup) and by
444/// [`apply_verbatim_env_flags`] (for an environment's begin-code, which has no command
445/// name to look up).
446fn reaches_signal_body(
447    body: &DefBody,
448    bodies: &HashMap<SmolStr, DefBody>,
449    visited: &mut HashSet<SmolStr>,
450) -> bool {
451    body.signal
452        || body
453            .called
454            .iter()
455            .any(|callee| reaches_signal(callee, bodies, visited))
456}
457
458/// Whether `body` text reassigns a special char's catcode to "other" — the static
459/// fingerprint of a verbatim-argument command's setup. Strict, to avoid false
460/// positives (which would silence real diagnostics): each pattern is verbatim-setup
461/// specific. We match surface text only; no catcode arithmetic is evaluated.
462fn catcode_signal(body: &str) -> bool {
463    body.contains("\\@makeother")
464        || body.contains("\\@sanitize")
465        || body.contains("\\dospecials")
466        || body
467            .match_indices("\\catcode")
468            .any(|(start, _)| catcode_assigns_other(&body[start + "\\catcode".len()..]))
469}
470
471/// Recognize the bounded surface shape `\catcode`…`=12` after the primitive.
472///
473/// TeX's number scanner is broader than this deliberately conservative check.
474/// Verbatim inference may miss an exotic assignment, but it must not combine an
475/// unrelated `12` with a different catcode assignment and silence diagnostics.
476fn catcode_assigns_other(tail: &str) -> bool {
477    let mut chars = tail.chars();
478    if chars
479        .clone()
480        .next()
481        .is_some_and(|c| c.is_ascii_alphabetic() || matches!(c, '@' | '_' | ':'))
482    {
483        return false;
484    }
485
486    let mut after_equals = chars
487        .by_ref()
488        .take(64)
489        .skip_while(|&c| c != '=')
490        .skip(1)
491        .skip_while(|c| c.is_whitespace());
492    after_equals.next() == Some('1')
493        && after_equals.next() == Some('2')
494        && !after_equals.next().is_some_and(|c| c.is_ascii_digit())
495}
496
497/// The control-word names (leading `\` stripped) the body invokes, for chained-helper
498/// resolution. `@` is treated as a name char so `\@makeother`/`\@codex`-style helpers
499/// are captured; control symbols (`\$`, `\\`) yield no name and are skipped. Reads
500/// surface text only.
501fn called_macros(body: &str) -> Vec<SmolStr> {
502    body.match_indices('\\')
503        .filter_map(|(pos, _)| {
504            let after = &body[pos + 1..];
505            let len: usize = after
506                .chars()
507                .take_while(|c| c.is_ascii_alphabetic() || *c == '@')
508                .map(char::len_utf8)
509                .sum();
510            (len > 0).then(|| SmolStr::new(&after[..len]))
511        })
512        .collect()
513}
514
515/// Kernel sectioning primitives that themselves scan a `(*/[toc]/{title})` argument
516/// the static scanner cannot see from a redefinition body. A `\renewcommand{\cs}{…}`
517/// whose body is `\secdef …`/`\@startsection …` carries no `#` parameter and no `[n]`,
518/// so [`newcommand_arity`] reads it as arity 0 — but `\cs` really does consume a prose
519/// title at expansion time (jss's `\renewcommand{\section}{\secdef …}` is the canonical
520/// case). Curated and deliberately narrow: a *missed* name falls back to the safe status
521/// quo (the redefinition wins and the argument is left un-reflowed), while a *false*
522/// match is the only way to over-trust a built-in, so we keep the set tight and match
523/// only these kernel primitives.
524const DELEGATING_PRIMITIVES: &[&str] = &["secdef", "@startsection", "@dblarg", "@sect", "@ssect"];
525
526/// The **trust gate** for a `\newcommand`/`\def` the static scanner reads as taking no
527/// arguments. When the body *delegates* to a token-consuming kernel primitive
528/// ([`DELEGATING_PRIMITIVES`]), the arity-0 reading is provably unreliable, so it must
529/// not overwrite a curated built-in with a strictly less informative 0-arg signature
530/// (which would drop, e.g., a sectioning command's `prose` title and its reflow — the
531/// jss-class bug). The caller keeps the built-in showing through the overlay instead.
532///
533/// Narrow by construction (AGENTS.md conservatism): fires only when arity is 0, the body
534/// delegates, *and* a built-in exists to preserve. A genuine 0-arg redefinition has a
535/// self-contained body (no delegation) and is left to win, so it correctly loses prose.
536fn keeps_builtin_over_arity0(name: &str, arity: usize, body: &DefBody) -> bool {
537    arity == 0
538        && body
539            .called
540            .iter()
541            .any(|callee| DELEGATING_PRIMITIVES.contains(&callee.as_str()))
542        && crate::semantic::signature::builtin()
543            .command(name)
544            .is_some()
545}
546
547/// Whether `name` is a definition command the scanner recognizes
548/// (`\newcommand`/`\def`/xparse families; see [`DefKind`]). Exposed so consumers
549/// that must treat a definition's arguments as *code carried, not executed* (the
550/// linter's `missing-required-argument` rule skips partial applications like
551/// `\newcommand{\bold}{\textbf}`) share the scanner's one name list instead of
552/// duplicating it.
553pub fn is_definition_command(name: &str) -> bool {
554    DefKind::of(name).is_some()
555}
556
557/// Which definition family a control word names, if any.
558enum DefKind {
559    Command,
560    Def,
561    Environment,
562    XparseCommand,
563    XparseEnvironment,
564    /// A package command whose defined environment has a *verbatim* body, a static
565    /// fact of the *defining command's identity* (not of any catcode signal in its
566    /// begin-code, which lives inside the package's own machinery): `listings`'
567    /// `\lstnewenvironment` and `fancyvrb`'s `\DefineVerbatimEnvironment`.
568    VerbatimEnvironment,
569}
570
571impl DefKind {
572    fn of(name: &str) -> Option<Self> {
573        Some(match name {
574            "newcommand" | "renewcommand" | "providecommand" | "DeclareRobustCommand" => {
575                DefKind::Command
576            }
577            // Plain TeX `\def` and its global/expanded variants. `\let` is excluded: it
578            // aliases an existing meaning rather than carrying a replacement body to scan.
579            "def" | "edef" | "gdef" | "xdef" => DefKind::Def,
580            "newenvironment" | "renewenvironment" => DefKind::Environment,
581            "NewDocumentCommand"
582            | "RenewDocumentCommand"
583            | "ProvideDocumentCommand"
584            | "DeclareDocumentCommand" => DefKind::XparseCommand,
585            "NewDocumentEnvironment"
586            | "RenewDocumentEnvironment"
587            | "ProvideDocumentEnvironment"
588            | "DeclareDocumentEnvironment" => DefKind::XparseEnvironment,
589            // `listings`/`fancyvrb` verbatim-environment definitions: the body is raw
590            // text, a fact of the defining command, not of any scannable catcode signal.
591            "lstnewenvironment" | "DefineVerbatimEnvironment" => DefKind::VerbatimEnvironment,
592            _ => return None,
593        })
594    }
595}
596
597/// `\newcommand{\name}[n][default]{body}` → a [`CommandSig`]. The name is the
598/// control word in the first group; `[n]` (if present) is the arg count, and a
599/// second optional `[default]` makes the first argument optional `[…]` while the
600/// rest are mandatory `{…}` — LaTeX2e's `\newcommand` shape. The unbraced
601/// `\newcommand\name[n]…` form is recovered the same way via [`resolve_command_def`].
602fn scan_newcommand(
603    command: &SyntaxNode,
604    db: &mut SignatureDb,
605    bodies: &mut HashMap<SmolStr, DefBody>,
606    aliases: &mut HashMap<SmolStr, EnvAliasCandidate>,
607) {
608    let Some(def) = resolve_command_def(command) else {
609        return;
610    };
611    let (arity, first_optional) = newcommand_arity(&def.host);
612    // The replacement body is the group right after the name: index `first_arg_group`
613    // on the host (group 1 for the braced form, group 0 for the unbraced sibling).
614    let body = nth_group(&def.host, def.first_arg_group);
615    record_body(bodies, &def.name, body.as_ref());
616    record_env_alias(aliases, &def.name, arity, body.as_ref());
617    // Trust gate: a `\secdef`/`\@startsection`-style body reads as arity 0 but really
618    // consumes a title, so don't let it downgrade a curated built-in (keep the overlay
619    // falling through to the built-in). See [`keeps_builtin_over_arity0`].
620    if bodies
621        .get(def.name.as_str())
622        .is_some_and(|body| keeps_builtin_over_arity0(&def.name, arity, body))
623    {
624        return;
625    }
626    db.insert_command(
627        def.name,
628        CommandSig {
629            args: latex2e_args(arity, first_optional).into(),
630            sectioning: None,
631            verbatim: false,
632            verbatim_delimited: false,
633            rule: false,
634            inline: false,
635            citation: None,
636            // Never inferred for a scanned definition: block-ness is
637            // undecidable without meaning, so scanned commands stay with the
638            // formatter's residual authored-break rule.
639            block: false,
640        },
641    );
642}
643
644/// `\def\name<param text>{body}` (and the `\edef`/`\gdef`/`\xdef` variants) → a
645/// [`CommandSig`]. `\def` has only the unbraced name form (TeX has no `\def{\name}`), so
646/// the name is the immediately-following sibling `COMMAND`. The arity comes from the
647/// **parameter text** (`#1#2…`) between the name and the body — counted by
648/// [`def_params_and_body`] — not from a `[n]` optional. We record the body for the same
649/// catcode-signal/helper-chain analysis as `\newcommand`, which is what lets a `\def`
650/// helper participate in chain resolution ([`reaches_signal`]).
651fn scan_def(
652    command: &SyntaxNode,
653    db: &mut SignatureDb,
654    bodies: &mut HashMap<SmolStr, DefBody>,
655    aliases: &mut HashMap<SmolStr, EnvAliasCandidate>,
656) {
657    let Some(name_node) = adjacent_sibling_command(command) else {
658        return;
659    };
660    let Some(name) = command_name(&name_node) else {
661        return;
662    };
663    let (arity, body) = def_params_and_body(&name_node);
664    record_body(bodies, &name, body.as_ref());
665    record_env_alias(aliases, &name, arity, body.as_ref());
666    // Trust gate: same as `scan_newcommand` — a delegating `\def\section{\secdef …}`
667    // must not downgrade a curated built-in. See [`keeps_builtin_over_arity0`].
668    if bodies
669        .get(name.as_str())
670        .is_some_and(|body| keeps_builtin_over_arity0(&name, arity, body))
671    {
672        return;
673    }
674    db.insert_command(
675        name,
676        CommandSig {
677            // `\def` parameters carry no brace/bracket distinction; model them as the same
678            // all-mandatory-brace shape scanned `\newcommand`s use. `apply_verbatim_flags`
679            // pops the final slot and sets `verbatim` if a catcode signal is reachable.
680            args: latex2e_args(arity, false).into(),
681            sectioning: None,
682            verbatim: false,
683            verbatim_delimited: false,
684            rule: false,
685            inline: false,
686            citation: None,
687            // Never inferred for a scanned definition: block-ness is
688            // undecidable without meaning, so scanned commands stay with the
689            // formatter's residual authored-break rule.
690            block: false,
691        },
692    );
693}
694
695/// The `(arity, body)` of a `\def`-style definition, reading its parameter text off the
696/// name `COMMAND` node. Two CST shapes arise under greedy attachment:
697/// - **No parameters** (`\def\foo{body}`): the body brace group attaches as `\foo`'s first
698///   child `GROUP`, so arity is `0` and the body is `nth_group(name_node, 0)`.
699/// - **With parameters** (`\def\foo#1#2{body}`): the leading `#` (`HASH`) breaks greedy
700///   attachment, so `\foo` has no child group and the `#1`, `#2`, and `{body}` are all
701///   siblings. Arity is the number of `HASH` tokens (each `#1` lexes as `HASH` + `WORD`)
702///   before the first sibling `GROUP`, which is the body.
703///
704/// Anything other than trivia/`HASH`/`WORD` before a group means delimited or malformed
705/// parameter text we do not model; we stop and report no body (so no catcode signal is
706/// recorded for it — the conservative choice). Arity is capped at 9 like `\newcommand`.
707fn def_params_and_body(name_node: &SyntaxNode) -> (usize, Option<SyntaxNode>) {
708    // No parameter text: the body attached greedily as the name command's first group.
709    if let Some(body) = nth_group(name_node, 0) {
710        return (0, Some(body));
711    }
712    // Parameter text intervened: count `#` markers up to the first sibling group (the body).
713    let mut arity = 0usize;
714    let mut next = name_node.next_sibling_or_token();
715    while let Some(element) = next {
716        match element {
717            NodeOrToken::Token(token) if is_trivia(token.kind()) => {
718                next = token.next_sibling_or_token();
719            }
720            NodeOrToken::Token(token) if token.kind() == SyntaxKind::HASH => {
721                arity += 1;
722                next = token.next_sibling_or_token();
723            }
724            // The digit following `#`, or a literal delimiter token in a delimited macro.
725            NodeOrToken::Token(token) if token.kind() == SyntaxKind::WORD => {
726                next = token.next_sibling_or_token();
727            }
728            NodeOrToken::Node(node) if node.kind() == SyntaxKind::GROUP => {
729                return (arity.min(9), Some(node));
730            }
731            _ => return (arity.min(9), None),
732        }
733    }
734    (arity.min(9), None)
735}
736
737/// Record the catcode/called-macro facts of a command definition's replacement
738/// `body` group (absent or unresolvable body → no signal, no calls).
739fn record_body(bodies: &mut HashMap<SmolStr, DefBody>, name: &str, body: Option<&SyntaxNode>) {
740    let text = body.map(group_inner_source).unwrap_or_default();
741    bodies.insert(
742        SmolStr::new(name),
743        DefBody {
744            signal: catcode_signal(&text),
745            called: called_macros(&text),
746        },
747    );
748}
749
750/// `\newenvironment{name}[n][default]{begin}{end}` → an [`EnvironmentSig`]. Same
751/// arg-count shape as [`scan_newcommand`]. The begin-code (group 1 — the optionals
752/// `[n][default]` are `OPTIONAL` nodes, so they don't shift `nth_group` indexing) is
753/// recorded so [`apply_verbatim_env_flags`] can flag a catcode-othering body verbatim.
754fn scan_newenvironment(
755    command: &SyntaxNode,
756    db: &mut SignatureDb,
757    env_bodies: &mut HashMap<SmolStr, DefBody>,
758) {
759    let Some(name) = nth_group_text(command, 0) else {
760        return;
761    };
762    let name = name.trim();
763    if name.is_empty() {
764        return;
765    }
766    record_body(env_bodies, name, nth_group(command, 1).as_ref());
767    let (arity, first_optional) = newcommand_arity(command);
768    db.insert_environment(name, environment_sig(latex2e_args(arity, first_optional)));
769}
770
771/// A `listings`/`fancyvrb` verbatim-environment definition → an [`EnvironmentSig`]
772/// with `verbatim_body`. Unlike [`scan_newenvironment`], the verbatim-ness is *not*
773/// read from a catcode signal in the begin-code — that machinery lives inside the
774/// package — but is implied by the defining command's identity, a bounded static fact
775/// (AGENTS.md decision #1). The name is the control-word-free text in the first group:
776/// - `\lstnewenvironment{name}[n][default]{begin}{end}` — the `[n][default]` optionals
777///   give the runtime argument shape, as in [`scan_newenvironment`].
778/// - `\DefineVerbatimEnvironment{name}{base}{opts}` — the environment takes one
779///   optional `[key=val]` argument at use time (`fancyvrb`'s `Verbatim` family).
780fn scan_verbatim_environment(defining_command: &str, command: &SyntaxNode, db: &mut SignatureDb) {
781    let Some(name) = nth_group_text(command, 0) else {
782        return;
783    };
784    let name = name.trim();
785    if name.is_empty() {
786        return;
787    }
788    let args = if defining_command == "lstnewenvironment" {
789        let (arity, first_optional) = newcommand_arity(command);
790        latex2e_args(arity, first_optional)
791    } else {
792        // `\DefineVerbatimEnvironment` → a single optional `[options]` slot.
793        latex2e_args(1, true)
794    };
795    let mut sig = environment_sig(args);
796    sig.verbatim_body = true;
797    db.insert_environment(name, sig);
798}
799
800/// `\NewDocumentCommand{\name}{spec}{body}` → a [`CommandSig`] with args from the
801/// xparse spec. The unbraced `\NewDocumentCommand\name{spec}…` form is recovered the
802/// same way via [`resolve_command_def`]; `first_arg_group` indexes the spec group on
803/// whichever node hosts the arguments.
804fn scan_xparse_command(
805    command: &SyntaxNode,
806    db: &mut SignatureDb,
807    bodies: &mut HashMap<SmolStr, DefBody>,
808    aliases: &mut HashMap<SmolStr, EnvAliasCandidate>,
809) {
810    let Some(def) = resolve_command_def(command) else {
811        return;
812    };
813    let Some(spec) = nth_group(&def.host, def.first_arg_group) else {
814        return;
815    };
816    // The body follows the spec group, so it sits one index further along.
817    let body = nth_group(&def.host, def.first_arg_group + 1);
818    record_body(bodies, &def.name, body.as_ref());
819    let args = xparse::parse_spec(&group_inner_source(&spec));
820    record_env_alias(aliases, &def.name, args.len(), body.as_ref());
821    db.insert_command(
822        def.name,
823        CommandSig {
824            args: args.into(),
825            sectioning: None,
826            verbatim: false,
827            verbatim_delimited: false,
828            rule: false,
829            inline: false,
830            citation: None,
831            // Never inferred for a scanned definition: block-ness is
832            // undecidable without meaning, so scanned commands stay with the
833            // formatter's residual authored-break rule.
834            block: false,
835        },
836    );
837}
838
839/// A resolved command definition: the defined `name`, the node whose attached
840/// `OPTIONAL`/`GROUP` children carry the argument shape (`host`), and the index of
841/// the first *signature* group on that host.
842///
843/// Two name forms collapse to this shape:
844/// - **Braced** `\newcommand{\foo}…`: the host is the definition command itself; its
845///   group 0 is the `{\foo}` name, so signature groups start at index `1`.
846/// - **Unbraced** `\newcommand\foo…`: greedy attachment makes `\foo` the next sibling
847///   `COMMAND` and hangs the `[n]`/`{body}` (or xparse spec) off *it*, so the host is
848///   that sibling and signature groups start at index `0`.
849struct CommandDef {
850    name: SmolStr,
851    host: SyntaxNode,
852    first_arg_group: usize,
853}
854
855/// Resolve `command` (a `\newcommand`/xparse definition) to its [`CommandDef`],
856/// handling both the braced and unbraced name forms. Returns `None` when no command
857/// name can be read (a malformed or empty definition) — the scan then skips it.
858fn resolve_command_def(command: &SyntaxNode) -> Option<CommandDef> {
859    // Braced `{\name}`: the name control word lives in the first group, and every
860    // attached group/optional hangs off the definition command itself.
861    if command.children().any(|c| c.kind() == SyntaxKind::GROUP) {
862        let name = nth_group(command, 0)
863            .as_ref()
864            .and_then(group_command_name)?;
865        return Some(CommandDef {
866            name,
867            host: command.clone(),
868            first_arg_group: 1,
869        });
870    }
871    // Unbraced `\newcommand\foo…`: read the name and signature groups off the
872    // following sibling `COMMAND` (decision #2 — a scanner heuristic, no parser
873    // change).
874    let sibling = adjacent_sibling_command(command)?;
875    let name = command_name(&sibling)?;
876    Some(CommandDef {
877        name,
878        host: sibling,
879        first_arg_group: 0,
880    })
881}
882
883/// The immediately-following sibling `COMMAND`, separated from `command` by trivia
884/// only. Returns `None` if any non-trivia element intervenes, so `\newcommand\foo`
885/// (and the spaced `\newcommand \foo`) bind, but `\newcommand stray text \bar` does
886/// not. A blank line cannot reach here: the `\par` break splits the two commands into
887/// separate `PARAGRAPH` parents, so there is no sibling to find.
888fn adjacent_sibling_command(command: &SyntaxNode) -> Option<SyntaxNode> {
889    let mut next = command.next_sibling_or_token();
890    while let Some(element) = next {
891        match element {
892            NodeOrToken::Token(token) if is_trivia(token.kind()) => {
893                next = token.next_sibling_or_token();
894            }
895            NodeOrToken::Node(node) if node.kind() == SyntaxKind::COMMAND => return Some(node),
896            _ => return None,
897        }
898    }
899    None
900}
901
902/// `\NewDocumentEnvironment{name}{spec}{begin}{end}` → an [`EnvironmentSig`] with
903/// args and any verbatim body capture declared by the xparse spec. The begin-code
904/// (group 2 — after `{name}` and `{spec}`) is also recorded for verbatim detection,
905/// as in [`scan_newenvironment`].
906fn scan_xparse_environment(
907    command: &SyntaxNode,
908    db: &mut SignatureDb,
909    env_bodies: &mut HashMap<SmolStr, DefBody>,
910) {
911    let Some(name) = nth_group_text(command, 0) else {
912        return;
913    };
914    let name = name.trim();
915    if name.is_empty() {
916        return;
917    }
918    let Some(spec) = nth_group(command, 1) else {
919        return;
920    };
921    record_body(env_bodies, name, nth_group(command, 2).as_ref());
922    let (args, verbatim_body) = xparse::parse_environment_spec(&group_inner_source(&spec));
923    let mut sig = environment_sig(args);
924    sig.verbatim_body = verbatim_body;
925    db.insert_environment(name, sig);
926}
927
928/// The `(arity, first_arg_optional)` pair for a LaTeX2e definition: the integer in
929/// the first `[…]` optional (default `0`), and whether a *second* optional is
930/// present (which makes the first argument optional).
931fn newcommand_arity(command: &SyntaxNode) -> (usize, bool) {
932    let optionals: Vec<Optional> = children::<Optional>(command).collect();
933    let arity = optionals
934        .first()
935        .map(|o| o.syntax())
936        .and_then(optional_number)
937        .unwrap_or(0)
938        .min(9); // LaTeX caps macro arity at 9.
939    (arity, optionals.len() >= 2)
940}
941
942/// The integer inside an `OPTIONAL` node (`[2]` → `2`), or `None` if it isn't a
943/// bare number.
944fn optional_number(node: &SyntaxNode) -> Option<usize> {
945    let text = node.text().to_string();
946    let inner = text.strip_prefix('[').unwrap_or(&text);
947    let inner = inner.strip_suffix(']').unwrap_or(inner);
948    inner.trim().parse().ok()
949}
950
951/// Build the LaTeX2e argument slots: `arity` arguments, all mandatory `{…}` unless
952/// `first_optional`, in which case the first is optional `[…]`.
953fn latex2e_args(arity: usize, first_optional: bool) -> Vec<ArgSpec> {
954    (0..arity)
955        .map(|i| {
956            if i == 0 && first_optional {
957                ArgSpec {
958                    required: false,
959                    kind: ArgKind::Bracket,
960                    content: ContentKind::Opaque,
961                    domain: crate::semantic::ArgumentDomain::Unknown,
962                    verbatim: false,
963                }
964            } else {
965                ArgSpec {
966                    required: true,
967                    kind: ArgKind::Brace,
968                    content: ContentKind::Opaque,
969                    domain: crate::semantic::ArgumentDomain::Unknown,
970                    verbatim: false,
971                }
972            }
973        })
974        .collect()
975}
976
977/// An [`EnvironmentSig`] for a scanned environment with the given args: a
978/// reflowable, non-math, non-verbatim body. Callers add any verbatim evidence
979/// obtained from the argument specification or replacement text.
980fn environment_sig(args: Vec<ArgSpec>) -> EnvironmentSig {
981    EnvironmentSig {
982        args: args.into(),
983        verbatim_body: false,
984        // The delimited-verbatim name argument is a curated l3doc fact; a
985        // scanned definition never earns it.
986        verbatim_arg: false,
987        math: false,
988        code: false,
989        // Statement-sequence layout is a curated fact about a package's own
990        // grammar (a TikZ `;`), invisible in a `\newenvironment` body.
991        statement_body: false,
992        algorithm2e: false,
993        // A source definition exposes no package-specific `label` key semantics.
994        label_key: false,
995        // A source definition does not prove that labels belong to a `\captionof`.
996        caption_container: false,
997        align: false,
998        no_indent: false,
999        // A user `\newenvironment` is not assumed to be a list; the built-in DB
1000        // is the source of truth for `\item`-bearing list layout.
1001        list: false,
1002        inline: false,
1003        // Block-ness of a user-defined environment is unknown without
1004        // package-specific knowledge; default to non-block (the parser keeps the
1005        // conservative `PARAGRAPH` wrapper for it).
1006        block_explicit: false,
1007        // A scanned user environment carries no outline category; only curated
1008        // built-in environments show up in the document-symbol outline.
1009        outline: None,
1010    }
1011}
1012
1013/// TeX primitives that merely *reference* the following control word(s) — alias
1014/// them (`\let\x\rm`) or compare them (`\ifx\rm\y`) — rather than execute them,
1015/// and (unlike the `\def`/`\renewcommand` family) carry no replacement body, so
1016/// [`RuleContext::user_definitions`] does not record them. A deprecated switch or
1017/// discouraged primitive sitting in one of their operand slots must not get the
1018/// control-word swap: `\let\x\rmfamily` copies a *different* meaning, and where
1019/// this idiom guards the plain-TeX/ConTeXt branch, `\rmfamily`/`^` is undefined.
1020/// Redefinitions (a new meaning) are handled upstream by `user_definitions` — they
1021/// suppress the whole finding — so this narrow set is reference-only. Stored with
1022/// the leading backslash to compare against `CONTROL_WORD` text directly.
1023const REFERENCE_PRIMITIVES: &[&str] = &["\\let", "\\ifx"];
1024
1025/// Whether `command`'s control word sits in a [`REFERENCE_PRIMITIVES`] operand slot.
1026/// The CST is flat, so a `\let`/`\ifx` primitive is one or two control words back
1027/// (`\let\x\rm`: `\x` then `\let`; `\ifx\a\rm`: `\a` then `\ifx`). Scan backward over
1028/// trivia and a possible `=` separator (`\let\x=\rm`), inspecting the two nearest
1029/// control words; a reference primitive among them means "referenced". Shared by
1030/// `deprecated-command` and `primitive-command` to withhold their control-word swap.
1031pub fn in_reference_position(command: &SyntaxNode) -> bool {
1032    let Some(control_word) = child_token::<ControlWord>(command) else {
1033        return false;
1034    };
1035    let mut token = control_word.syntax().prev_token();
1036    let mut control_words_seen = 0;
1037    while let Some(current) = token {
1038        match current.kind() {
1039            // Trivia never breaks the chain. A `WORD` is skipped too: an at-letter
1040            // definee splits under document catcodes (`\let\foo@bar\rm` lexes as
1041            // `\foo` + `@bar`), and `\let\x=\rm` writes an explicit `=`. The
1042            // two-control-word cutoff below bounds how far this look-back reaches, so
1043            // skipping intervening words cannot run away.
1044            SyntaxKind::WHITESPACE
1045            | SyntaxKind::NEWLINE
1046            | SyntaxKind::COMMENT
1047            | SyntaxKind::WORD => {}
1048            SyntaxKind::CONTROL_WORD => {
1049                if REFERENCE_PRIMITIVES.contains(&current.text()) {
1050                    return true;
1051                }
1052                control_words_seen += 1;
1053                if control_words_seen >= 2 {
1054                    return false;
1055                }
1056            }
1057            _ => return false,
1058        }
1059        token = current.prev_token();
1060    }
1061    false
1062}
1063
1064#[cfg(test)]
1065mod tests {
1066    use super::*;
1067    use crate::parser::{parse, reconstruct};
1068
1069    fn db_of(src: &str) -> SignatureDb {
1070        assert_eq!(reconstruct(src), src, "reconstruct must round-trip");
1071        scan_definitions(&SyntaxNode::new_root(parse(src).green))
1072    }
1073
1074    fn arg_kinds(args: &[ArgSpec]) -> Vec<ArgKind> {
1075        args.iter().map(|a| a.kind).collect()
1076    }
1077
1078    #[test]
1079    fn newcommand_counts_mandatory_args() {
1080        let db = db_of("\\newcommand{\\foo}[2]{#1#2}\n");
1081        let sig = db.command("foo").expect("foo defined");
1082        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace, ArgKind::Brace]);
1083        assert!(sig.args.iter().all(|a| a.required));
1084        assert!(
1085            sig.args
1086                .iter()
1087                .all(|arg| arg.domain == crate::semantic::ArgumentDomain::Unknown)
1088        );
1089    }
1090
1091    #[test]
1092    fn newcommand_optional_first_arg() {
1093        let db = db_of("\\newcommand{\\foo}[2][d]{#1#2}\n");
1094        let sig = db.command("foo").expect("foo defined");
1095        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket, ArgKind::Brace]);
1096        assert!(!sig.args[0].required);
1097        assert!(sig.args[1].required);
1098    }
1099
1100    #[test]
1101    fn newcommand_zero_args() {
1102        let db = db_of("\\newcommand{\\foo}{bar}\n");
1103        assert!(db.command("foo").expect("foo defined").args.is_empty());
1104    }
1105
1106    #[test]
1107    fn renew_and_provide_recognized() {
1108        let db = db_of("\\renewcommand{\\a}[1]{x}\\providecommand{\\b}[1]{y}\n");
1109        assert_eq!(db.command("a").unwrap().args.len(), 1);
1110        assert_eq!(db.command("b").unwrap().args.len(), 1);
1111    }
1112
1113    #[test]
1114    fn secdef_redefinition_keeps_builtin_prose() {
1115        let db = db_of("\\renewcommand{\\section}{\\secdef \\a \\b}\n");
1116        assert!(
1117            db.command("section").is_none(),
1118            "the delegating redefinition must not be recorded as a scanned override"
1119        );
1120        let sigs = crate::semantic::signature::Signatures::new(&db);
1121        let sig = sigs.command("section").expect("built-in section survives");
1122        let last = sig.args.last().expect("section keeps its title argument");
1123        assert_eq!(
1124            last.content,
1125            crate::semantic::signature::ContentKind::Prose,
1126            "the title argument stays prose (reflowable)"
1127        );
1128    }
1129
1130    #[test]
1131    fn genuine_zero_arg_redefinition_downgrades_builtin() {
1132        let db = db_of("\\renewcommand{\\section}{\\textbf{Fixed}}\n");
1133        let sig = db
1134            .command("section")
1135            .expect("genuine 0-arg redefinition is recorded");
1136        assert!(
1137            sig.args.is_empty(),
1138            "no delegation means the scanned 0-arg signature wins"
1139        );
1140    }
1141
1142    #[test]
1143    fn secdef_redefinition_of_unknown_still_records() {
1144        let db = db_of("\\renewcommand{\\mysec}{\\secdef \\a \\b}\n");
1145        let sig = db.command("mysec").expect("unknown name is still recorded");
1146        assert!(sig.args.is_empty());
1147    }
1148
1149    #[test]
1150    fn newenvironment_args() {
1151        let db = db_of("\\newenvironment{thm}[1]{begin #1}{end}\n");
1152        let sig = db.environment("thm").expect("thm defined");
1153        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace]);
1154        assert!(sig.reflow());
1155        assert!(!sig.verbatim_body);
1156        assert!(!sig.math);
1157    }
1158
1159    #[test]
1160    fn xparse_command_spec() {
1161        let db = db_of("\\NewDocumentCommand{\\foo}{m O{d} m}{x}\n");
1162        let sig = db.command("foo").expect("foo defined");
1163        assert_eq!(
1164            arg_kinds(&sig.args),
1165            vec![ArgKind::Brace, ArgKind::Bracket, ArgKind::Brace]
1166        );
1167        assert!(
1168            sig.args
1169                .iter()
1170                .all(|arg| arg.domain == crate::semantic::ArgumentDomain::Unknown)
1171        );
1172    }
1173
1174    #[test]
1175    fn xparse_environment_spec() {
1176        let db = db_of("\\NewDocumentEnvironment{env}{O{x} m}{a}{b}\n");
1177        let sig = db.environment("env").expect("env defined");
1178        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket, ArgKind::Brace]);
1179        assert!(
1180            sig.args
1181                .iter()
1182                .all(|arg| arg.domain == crate::semantic::ArgumentDomain::Unknown)
1183        );
1184    }
1185
1186    #[test]
1187    fn xparse_verbatim_body_spec() {
1188        for definer in [
1189            "NewDocumentEnvironment",
1190            "RenewDocumentEnvironment",
1191            "ProvideDocumentEnvironment",
1192            "DeclareDocumentEnvironment",
1193        ] {
1194            let db = db_of(&format!("\\{definer}{{demo}}{{O{{code}} c}}{{#2}}{{}}\n"));
1195            let sig = db.environment("demo").expect("demo defined");
1196            assert!(sig.verbatim_body, "{definer}");
1197            assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket]);
1198        }
1199    }
1200
1201    #[test]
1202    fn unbraced_newcommand_extracted() {
1203        let db = db_of("\\newcommand\\foo[2]{#1#2}\n");
1204        let sig = db.command("foo").expect("foo defined");
1205        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace, ArgKind::Brace]);
1206        assert!(sig.args.iter().all(|a| a.required));
1207    }
1208
1209    #[test]
1210    fn unbraced_optional_first_arg() {
1211        let db = db_of("\\newcommand\\foo[2][d]{#1#2}\n");
1212        let sig = db.command("foo").expect("foo defined");
1213        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket, ArgKind::Brace]);
1214        assert!(!sig.args[0].required);
1215        assert!(sig.args[1].required);
1216    }
1217
1218    #[test]
1219    fn unbraced_zero_args() {
1220        let db = db_of("\\newcommand\\foo{x}\n");
1221        assert!(db.command("foo").expect("foo defined").args.is_empty());
1222    }
1223
1224    #[test]
1225    fn unbraced_spaced_binds() {
1226        let db = db_of("\\newcommand \\foo[1]{x}\n");
1227        assert_eq!(db.command("foo").unwrap().args.len(), 1);
1228    }
1229
1230    #[test]
1231    fn unbraced_renewcommand() {
1232        let db = db_of("\\renewcommand\\foo[1]{x}\n");
1233        assert_eq!(db.command("foo").unwrap().args.len(), 1);
1234    }
1235
1236    #[test]
1237    fn unbraced_xparse_command() {
1238        let db = db_of("\\NewDocumentCommand\\foo{m O{d} m}{x}\n");
1239        let sig = db.command("foo").expect("foo defined");
1240        assert_eq!(
1241            arg_kinds(&sig.args),
1242            vec![ArgKind::Brace, ArgKind::Bracket, ArgKind::Brace]
1243        );
1244    }
1245
1246    #[test]
1247    fn unbraced_stray_text_not_bound() {
1248        let db = db_of("\\newcommand foo \\bar{x}\n");
1249        assert!(db.command("foo").is_none());
1250        assert!(db.command("bar").is_none());
1251    }
1252
1253    #[test]
1254    fn redefinition_last_wins() {
1255        let db = db_of("\\newcommand{\\foo}[1]{x}\\renewcommand{\\foo}[3]{y}\n");
1256        assert_eq!(db.command("foo").unwrap().args.len(), 3);
1257    }
1258
1259    #[test]
1260    fn garbage_definition_degrades_to_no_insert() {
1261        let db = db_of("\\newcommand\n");
1262        assert!(db.command("foo").is_none());
1263    }
1264
1265    #[test]
1266    fn nested_definition_collected() {
1267        let db = db_of("\\begin{document}\n\\newcommand{\\foo}[1]{x}\n\\end{document}\n");
1268        assert_eq!(db.command("foo").unwrap().args.len(), 1);
1269    }
1270
1271    #[test]
1272    fn commented_definition_ignored() {
1273        let db = db_of("% \\newcommand{\\foo}[1]{x}\n");
1274        assert!(db.command("foo").is_none());
1275    }
1276
1277    #[test]
1278    fn verbatim_makeother_flagged() {
1279        let db = db_of("\\newcommand\\shellcmd[1]{\\@makeother\\$#1}\n");
1280        let sig = db.command("shellcmd").expect("shellcmd defined");
1281        assert!(sig.verbatim);
1282        assert!(sig.args.is_empty());
1283    }
1284
1285    #[test]
1286    fn verbatim_catcode_flagged() {
1287        let db = db_of("\\newcommand\\shellcmd[1]{\\catcode 36=12 #1}\n");
1288        assert!(db.command("shellcmd").expect("shellcmd defined").verbatim);
1289    }
1290
1291    #[test]
1292    fn unrelated_twelve_does_not_flag_catcode_assignment() {
1293        let db = db_of("\\newcommand\\ordinary[1]{\\catcode 36=\\active \\hspace{12pt}#1}\n");
1294        assert!(!db.command("ordinary").expect("ordinary defined").verbatim);
1295    }
1296
1297    #[test]
1298    fn verbatim_dospecials_flagged() {
1299        let db = db_of("\\newcommand\\shellcmd[1]{\\let\\do\\@makeother\\dospecials #1}\n");
1300        assert!(db.command("shellcmd").expect("shellcmd defined").verbatim);
1301    }
1302
1303    #[test]
1304    fn verbatim_keeps_leading_args() {
1305        let db = db_of("\\newcommand\\mycode[2]{\\@makeother\\$#1#2}\n");
1306        let sig = db.command("mycode").expect("mycode defined");
1307        assert!(sig.verbatim);
1308        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace]);
1309    }
1310
1311    #[test]
1312    fn verbatim_via_chained_helper() {
1313        let db =
1314            db_of("\\newcommand\\setup{\\@makeother\\$}\\newcommand\\shellcmd[1]{\\setup#1}\n");
1315        assert!(db.command("shellcmd").expect("shellcmd defined").verbatim);
1316        assert!(!db.command("setup").expect("setup defined").verbatim);
1317    }
1318
1319    #[test]
1320    fn verbatim_chain_cycle_terminates() {
1321        let db = db_of("\\newcommand\\a[1]{\\b#1}\\newcommand\\b[1]{\\a#1}\n");
1322        assert!(!db.command("a").expect("a defined").verbatim);
1323        assert!(!db.command("b").expect("b defined").verbatim);
1324    }
1325
1326    #[test]
1327    fn ordinary_command_not_verbatim() {
1328        let db = db_of("\\newcommand\\foo[1]{\\emph{#1}}\n");
1329        assert!(!db.command("foo").expect("foo defined").verbatim);
1330    }
1331
1332    #[test]
1333    fn verbatim_needs_an_argument() {
1334        let db = db_of("\\newcommand\\setup{\\@makeother\\$}\n");
1335        assert!(!db.command("setup").expect("setup defined").verbatim);
1336    }
1337
1338    #[test]
1339    fn def_helper_chain_followed() {
1340        let db = db_of("\\def\\setup{\\@makeother\\$}\\newcommand\\shellcmd[1]{\\setup#1}\n");
1341        assert!(db.command("shellcmd").expect("shellcmd defined").verbatim);
1342        assert!(!db.command("setup").expect("setup defined").verbatim);
1343    }
1344
1345    #[test]
1346    fn def_direct_verbatim_flagged() {
1347        let db = db_of("\\def\\shellcmd#1{\\@makeother\\$#1}\n");
1348        let sig = db.command("shellcmd").expect("shellcmd defined");
1349        assert!(sig.verbatim);
1350        assert!(sig.args.is_empty());
1351    }
1352
1353    #[test]
1354    fn def_zero_params() {
1355        let db = db_of("\\def\\foo{x}\n");
1356        let sig = db.command("foo").expect("foo defined");
1357        assert!(sig.args.is_empty());
1358        assert!(!sig.verbatim);
1359    }
1360
1361    #[test]
1362    fn def_counts_params() {
1363        let db = db_of("\\def\\foo#1#2{#1#2}\n");
1364        let sig = db.command("foo").expect("foo defined");
1365        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace, ArgKind::Brace]);
1366    }
1367
1368    #[test]
1369    fn def_variants_scanned() {
1370        let db = db_of("\\edef\\a#1{x}\\gdef\\b{y}\\xdef\\c#1{\\@makeother\\$#1}\n");
1371        assert_eq!(db.command("a").expect("a defined").args.len(), 1);
1372        assert!(db.command("b").expect("b defined").args.is_empty());
1373        let c = db.command("c").expect("c defined");
1374        assert!(c.verbatim);
1375        assert!(c.args.is_empty());
1376    }
1377
1378    #[test]
1379    fn def_chain_through_def_helpers() {
1380        let db = db_of(
1381            "\\def\\inner{\\@makeother\\$}\\def\\outer{\\inner}\\newcommand\\cmd[1]{\\outer#1}\n",
1382        );
1383        assert!(db.command("cmd").expect("cmd defined").verbatim);
1384    }
1385
1386    #[test]
1387    fn verbatim_xparse_flagged() {
1388        let db = db_of("\\NewDocumentCommand\\shellcmd{m}{\\@makeother\\$#1}\n");
1389        let sig = db.command("shellcmd").expect("shellcmd defined");
1390        assert!(sig.verbatim);
1391        assert!(sig.args.is_empty());
1392    }
1393
1394    #[test]
1395    fn env_makeother_flagged() {
1396        let db = db_of("\\newenvironment{shellenv}{\\@makeother\\$}{}\n");
1397        let sig = db.environment("shellenv").expect("shellenv defined");
1398        assert!(sig.verbatim_body);
1399        assert!(!sig.reflow()); // a verbatim body is never reflowed
1400    }
1401
1402    #[test]
1403    fn env_catcode_flagged() {
1404        let db = db_of("\\newenvironment{shellenv}[1]{\\catcode 36=12 }{}\n");
1405        let sig = db.environment("shellenv").expect("shellenv defined");
1406        assert!(sig.verbatim_body);
1407        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Brace]);
1408    }
1409
1410    #[test]
1411    fn env_via_chained_helper() {
1412        let db =
1413            db_of("\\newcommand\\setup{\\@makeother\\$}\\newenvironment{shellenv}{\\setup}{}\n");
1414        assert!(
1415            db.environment("shellenv")
1416                .expect("shellenv defined")
1417                .verbatim_body
1418        );
1419    }
1420
1421    #[test]
1422    fn env_without_signal_not_flagged() {
1423        let db = db_of("\\newenvironment{remark}{\\par\\noindent\\textbf{Remark.}}{\\par}\n");
1424        let sig = db.environment("remark").expect("remark defined");
1425        assert!(!sig.verbatim_body);
1426        assert!(sig.reflow());
1427    }
1428
1429    #[test]
1430    fn lstnewenvironment_flagged_verbatim() {
1431        let db = db_of("\\lstnewenvironment{demo}[1][code]{\\lstset{#1}}{}\n");
1432        let sig = db.environment("demo").expect("demo defined");
1433        assert!(sig.verbatim_body);
1434        assert!(!sig.reflow());
1435        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket]);
1436    }
1437
1438    #[test]
1439    fn lstnewenvironment_no_args_flagged_verbatim() {
1440        let db = db_of("\\lstnewenvironment{demo}{}{}\n");
1441        let sig = db.environment("demo").expect("demo defined");
1442        assert!(sig.verbatim_body);
1443        assert!(sig.args.is_empty());
1444    }
1445
1446    #[test]
1447    fn defineverbatimenvironment_flagged_verbatim() {
1448        let db = db_of("\\DefineVerbatimEnvironment{code}{Verbatim}{fontsize=\\small}\n");
1449        let sig = db.environment("code").expect("code defined");
1450        assert!(sig.verbatim_body);
1451        assert!(!sig.reflow());
1452        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket]);
1453    }
1454
1455    #[test]
1456    fn xparse_env_makeother_flagged() {
1457        let db = db_of("\\NewDocumentEnvironment{shellenv}{O{x}}{\\dospecials}{}\n");
1458        let sig = db.environment("shellenv").expect("shellenv defined");
1459        assert!(sig.verbatim_body);
1460        assert_eq!(arg_kinds(&sig.args), vec![ArgKind::Bracket]);
1461    }
1462
1463    fn sites_of(src: &str) -> Vec<DefSite> {
1464        assert_eq!(reconstruct(src), src, "reconstruct must round-trip");
1465        scan_definition_sites(&SyntaxNode::new_root(parse(src).green))
1466    }
1467
1468    #[test]
1469    fn def_site_newcommand_braced_name_span() {
1470        let src = "\\newcommand{\\foo}[1]{#1}\n";
1471        let sites = sites_of(src);
1472        assert_eq!(sites.len(), 1);
1473        let site = &sites[0];
1474        assert_eq!(site.name, "foo");
1475        assert_eq!(site.kind, DefSiteKind::Command);
1476        assert_eq!(&src[site.name_range], "\\foo");
1477        assert_eq!(&src[site.range], "\\newcommand{\\foo}[1]{#1}");
1478    }
1479
1480    #[test]
1481    fn def_site_newcommand_unbraced_name_span() {
1482        let src = "\\newcommand\\foo[1]{#1}\n";
1483        let sites = sites_of(src);
1484        assert_eq!(sites.len(), 1);
1485        assert_eq!(sites[0].name, "foo");
1486        assert_eq!(&src[sites[0].name_range], "\\foo");
1487        assert_eq!(&src[sites[0].range], "\\newcommand\\foo[1]{#1}");
1488    }
1489
1490    #[test]
1491    fn def_site_def_sibling_name_span() {
1492        let src = "\\def\\foo#1{#1}\n";
1493        let sites = sites_of(src);
1494        assert_eq!(sites.len(), 1);
1495        assert_eq!(sites[0].name, "foo");
1496        assert_eq!(sites[0].kind, DefSiteKind::Command);
1497        assert_eq!(&src[sites[0].name_range], "\\foo");
1498    }
1499
1500    #[test]
1501    fn def_site_xparse_command_name_span() {
1502        let src = "\\NewDocumentCommand{\\foo}{m O{d}}{x}\n";
1503        let sites = sites_of(src);
1504        assert_eq!(sites.len(), 1);
1505        assert_eq!(sites[0].name, "foo");
1506        assert_eq!(&src[sites[0].name_range], "\\foo");
1507    }
1508
1509    #[test]
1510    fn def_site_newenvironment_name_span() {
1511        let src = "\\newenvironment{myenv}{begin}{end}\n";
1512        let sites = sites_of(src);
1513        assert_eq!(sites.len(), 1);
1514        let site = &sites[0];
1515        assert_eq!(site.name, "myenv");
1516        assert_eq!(site.kind, DefSiteKind::Environment);
1517        assert_eq!(&src[site.name_range], "myenv");
1518    }
1519
1520    #[test]
1521    fn def_site_xparse_environment_name_span() {
1522        let src = "\\NewDocumentEnvironment{myenv}{m}{a}{b}\n";
1523        let sites = sites_of(src);
1524        assert_eq!(sites.len(), 1);
1525        assert_eq!(sites[0].name, "myenv");
1526        assert_eq!(sites[0].kind, DefSiteKind::Environment);
1527        assert_eq!(&src[sites[0].name_range], "myenv");
1528    }
1529
1530    #[test]
1531    fn def_site_keeps_every_redefinition() {
1532        let src = "\\newcommand{\\foo}{a}\n\\renewcommand{\\foo}{b}\n";
1533        let sites = sites_of(src);
1534        assert_eq!(sites.len(), 2);
1535        assert!(sites.iter().all(|s| s.name == "foo"));
1536        assert!(sites[0].name_range.start() < sites[1].name_range.start());
1537    }
1538
1539    #[test]
1540    fn def_site_none_for_malformed() {
1541        assert!(sites_of("\\newcommand\n").is_empty());
1542        assert!(sites_of("\\newenvironment{}{a}{b}\n").is_empty());
1543    }
1544
1545    const EQNARRAY_PAIR: &str =
1546        "\\newcommand{\\bea}{\\begin{eqnarray}}\n\\newcommand{\\eea}{\\end{eqnarray}}\n";
1547
1548    #[test]
1549    fn newcommand_env_alias_pair_is_recorded() {
1550        let db = db_of(EQNARRAY_PAIR);
1551        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
1552        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
1553        assert_eq!(db.env_begin_alias("eea"), None);
1554        assert_eq!(db.env_end_alias("bea"), None);
1555    }
1556
1557    #[test]
1558    fn def_env_alias_pair_is_recorded() {
1559        let db = db_of("\\def\\bea{\\begin{eqnarray}}\n\\def\\eea{\\end{eqnarray}}\n");
1560        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
1561        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
1562    }
1563
1564    #[test]
1565    fn xparse_env_alias_pair_is_recorded() {
1566        let db = db_of(
1567            "\\NewDocumentCommand{\\bea}{}{\\begin{eqnarray}}\n\
1568             \\NewDocumentCommand{\\eea}{}{\\end{eqnarray}}\n",
1569        );
1570        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
1571        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
1572    }
1573
1574    #[test]
1575    fn env_alias_body_tolerates_trivia() {
1576        let db = db_of(
1577            "\\newcommand{\\bea}{ \\begin{eqnarray} }\n\\newcommand{\\eea}{% why\n\\end{eqnarray}}\n",
1578        );
1579        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
1580        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
1581    }
1582
1583    #[test]
1584    fn a_lone_env_alias_half_is_recorded() {
1585        let db = db_of("\\newcommand{\\bea}{\\begin{eqnarray}}\n");
1586        assert_eq!(db.env_begin_alias("bea"), Some("eqnarray"));
1587        assert_eq!(db.env_end_alias("bea"), None);
1588
1589        let db = db_of("\\newcommand{\\eea}{\\end{eqnarray}}\n");
1590        assert_eq!(db.env_end_alias("eea"), Some("eqnarray"));
1591        assert_eq!(db.env_begin_alias("eea"), None);
1592    }
1593
1594    #[test]
1595    fn a_lone_half_still_obeys_every_target_rule() {
1596        assert_eq!(
1597            db_of("\\newcommand{\\bmy}{\\begin{notacuratedenv}}\n").env_begin_alias("bmy"),
1598            None
1599        );
1600        assert_eq!(
1601            db_of("\\newcommand{\\ev}{\\end{verbatim}}\n").env_end_alias("ev"),
1602            None
1603        );
1604        assert_eq!(
1605            db_of("\\newcommand{\\bt}{\\begin{tabular}}\n").env_begin_alias("bt"),
1606            None
1607        );
1608        assert_eq!(
1609            db_of("\\newcommand{\\bea}[1]{\\begin{eqnarray}}\n").env_begin_alias("bea"),
1610            None
1611        );
1612    }
1613
1614    #[test]
1615    fn env_alias_rejects_uncurated_target() {
1616        let db = db_of(
1617            "\\newcommand{\\bmy}{\\begin{notacuratedenv}}\n\
1618             \\newcommand{\\emy}{\\end{notacuratedenv}}\n",
1619        );
1620        assert_eq!(db.env_begin_alias("bmy"), None);
1621        assert_eq!(db.env_end_alias("emy"), None);
1622    }
1623
1624    #[test]
1625    fn env_alias_rejects_verbatim_target() {
1626        let db =
1627            db_of("\\newcommand{\\bv}{\\begin{verbatim}}\n\\newcommand{\\ev}{\\end{verbatim}}\n");
1628        assert_eq!(db.env_begin_alias("bv"), None);
1629    }
1630
1631    #[test]
1632    fn env_alias_rejects_argument_taking_target() {
1633        let db =
1634            db_of("\\newcommand{\\bt}{\\begin{tabular}}\n\\newcommand{\\et}{\\end{tabular}}\n");
1635        assert_eq!(db.env_begin_alias("bt"), None);
1636    }
1637
1638    #[test]
1639    fn env_alias_rejects_parameterized_definition() {
1640        let db = db_of(
1641            "\\newcommand{\\bt}[1]{\\begin{tabular}{#1}}\n\\newcommand{\\et}{\\end{tabular}}\n",
1642        );
1643        assert_eq!(db.env_begin_alias("bt"), None);
1644    }
1645
1646    #[test]
1647    fn env_alias_rejects_body_with_extra_content() {
1648        let db = db_of(
1649            "\\newcommand{\\bea}{\\begin{eqnarray}\\label{x}}\n\\newcommand{\\eea}{\\end{eqnarray}}\n",
1650        );
1651        assert_eq!(db.env_begin_alias("bea"), None);
1652    }
1653
1654    #[test]
1655    fn redefinition_retracts_an_earlier_env_alias() {
1656        let db = db_of(
1657            "\\newcommand{\\bea}{\\begin{eqnarray}}\n\
1658             \\newcommand{\\eea}{\\end{eqnarray}}\n\
1659             \\renewcommand{\\bea}{\\textbf}\n",
1660        );
1661        assert_eq!(db.env_begin_alias("bea"), None);
1662    }
1663
1664    #[test]
1665    fn env_alias_does_not_pollute_the_environment_namespace() {
1666        let db = db_of(EQNARRAY_PAIR);
1667        assert!(db.environment("bea").is_none());
1668        assert!(!db.environment_names().any(|n| n == "bea"));
1669    }
1670
1671    fn environment_node(src: &str) -> SyntaxNode {
1672        SyntaxNode::new_root(parse(src).green)
1673            .descendants()
1674            .find(|n| n.kind() == SyntaxKind::ENVIRONMENT)
1675            .expect("an environment")
1676    }
1677
1678    #[test]
1679    fn signatures_resolves_an_env_alias_to_the_curated_target() {
1680        use crate::semantic::signature::Signatures;
1681        let src = format!("{EQNARRAY_PAIR}\\bea a \\eea\n");
1682        let db = db_of(&src);
1683        let sigs = Signatures::new(&db);
1684        let sig = sigs
1685            .environment_at(&environment_node(&src))
1686            .expect("alias resolves");
1687        let target = builtin().environment("eqnarray").expect("curated target");
1688        assert_eq!(sig, target);
1689        assert!(sig.math && sig.align);
1690        assert!(sigs.environment("bea").is_none());
1691    }
1692
1693    #[test]
1694    fn a_literal_begin_does_not_inherit_the_alias_target() {
1695        use crate::semantic::signature::Signatures;
1696        let src = format!("{EQNARRAY_PAIR}\\begin{{bea}} a \\end{{bea}}\n");
1697        let db = db_of(&src);
1698        let sigs = Signatures::new(&db);
1699        assert!(sigs.environment_at(&environment_node(&src)).is_none());
1700    }
1701
1702    #[test]
1703    fn a_real_environment_wins_over_an_alias_of_the_same_name() {
1704        use crate::semantic::signature::Signatures;
1705        let defs = "\\newcommand{\\bea}{\\begin{eqnarray}}\n\
1706             \\newcommand{\\eea}{\\end{eqnarray}}\n\
1707             \\newenvironment{bea}{x}{y}\n";
1708        let db = db_of(&format!("{defs}\\begin{{bea}} a \\end{{bea}}\n"));
1709        let sigs = Signatures::new(&db);
1710        let sig = sigs
1711            .environment_at(&environment_node(&format!(
1712                "{defs}\\begin{{bea}} a \\end{{bea}}\n"
1713            )))
1714            .expect("real environment resolves");
1715        assert!(
1716            !sig.math,
1717            "the scanned \\newenvironment must win for a literal `\\begin{{bea}}`"
1718        );
1719        assert!(
1720            sigs.environment_at(&environment_node(&format!("{defs}\\bea a \\eea\n")))
1721                .is_some_and(|sig| sig.math),
1722            "while the alias delimiters still resolve to eqnarray"
1723        );
1724    }
1725
1726    #[test]
1727    fn merge_from_carries_env_aliases() {
1728        let mut target = SignatureDb::default();
1729        target.merge_from(&db_of(EQNARRAY_PAIR), None);
1730        assert_eq!(target.env_begin_alias("bea"), Some("eqnarray"));
1731        assert_eq!(target.env_end_alias("eea"), Some("eqnarray"));
1732    }
1733}