Skip to main content

badness_parser/semantic/
signature.rs

1//! The built-in **signature database**: command/environment argument shapes plus
2//! the semantic metadata a formatter/linter needs (sectioning level,
3//! verbatim-ness, math-ness). Meaning is assigned here rather than in the parser.
4//!
5//! The data is fully static, so it lives in a process-wide [`LazyLock`],
6//! consulted directly. Per-file `\newcommand`/`\newenvironment`/xparse
7//! signatures are scanned by [`super::define`] into a separate, per-document
8//! [`SignatureDb`] and overlaid via [`Signatures`] (scanned-first, built-in
9//! fallback). The greedy parser's argument attachment is unaffected either way.
10//!
11//! ## Source of truth: one granular JSON file
12//!
13//! The built-in data is a single curated JSON file (`data/signatures.json`,
14//! [`include_str!`]-ed, [`serde`]-deserialized) holding *all* the metadata in one
15//! typed place — argument shapes *and* sectioning level / verbatim-ness /
16//! math-ness together, keyed by name. This is the high-precision tier we maintain
17//! by hand.
18//!
19//! Lower-precision external sources layer *underneath* this, ingested into the
20//! same schema rather than replacing it. The TeXstudio/Kile **CWL corpus** is one
21//! such tier: a
22//! converter (`scripts/gen_cwl_signatures.py`) harvests command/environment names
23//! and argument shapes from a curated package subset into `data/cwl_signatures.json`,
24//! exposed by [`cwl`] and consulted *under* [`builtin`]. CWL is an import format,
25//! never the source of truth: only names and arity cross over (every behavior flag
26//! stays default), so it widens completion and arity coverage without its
27//! low-confidence data reaching a lexer/formatter/outline behavior decision. The
28//! file is compiled into a `phf` perfect-hash map at build time (`build.rs`) and
29//! `include!`-ed as read-only statics — zero runtime parse or decompress.
30
31use std::borrow::Cow;
32use std::collections::HashMap;
33use std::sync::LazyLock;
34
35use serde::Deserialize;
36use smol_str::SmolStr;
37
38use crate::syntax::{SyntaxKind, SyntaxNode};
39
40/// Which bracket delimits an argument. TeX has no other real argument grouping at
41/// the surface level the formatter cares about.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum ArgKind {
44    /// An argument delimited by `{…}`.
45    Brace,
46    /// An argument delimited by `[…]`.
47    Bracket,
48}
49
50/// The TeX mode a command or environment argument is proven to establish.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
52pub enum ArgumentDomain {
53    /// No safe text-or-math claim is available.
54    #[default]
55    Unknown,
56    /// The argument is parsed and interpreted as math.
57    Math,
58    /// The argument is parsed and interpreted as text.
59    Text,
60}
61
62/// How the formatter treats an argument's *content* — its whitespace and break
63/// policy. This metadata is for formatter consumers; the parser ignores it.
64#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub enum ContentKind {
66    /// Left exactly as authored: names, identifiers, code, or option lists
67    /// (`\label`, the `\newcommand` body). The default, so an unmarked argument
68    /// never reflows — for most arguments interior whitespace can matter (a
69    /// `minipage`/`\parbox` body, a label key).
70    #[default]
71    Opaque,
72    /// Running prose the formatter may reflow to the line width (e.g. a
73    /// `\footnote`/`\caption` body, a sectioning title).
74    Prose,
75    /// A comma-separated token list whose interior whitespace is *insignificant*,
76    /// so the formatter may collapse a multi-line authored form to a single line
77    /// (a `\citep`/`\cite` key list). Unlike [`Prose`](ContentKind::Prose), the
78    /// content participates in the surrounding paragraph fill only at its
79    /// top-level commas, so an over-width citation can wrap between keys without
80    /// splitting a key or detaching its delimiters. Incidental source line breaks
81    /// are normalized away, so `\citep{\n a,\n b\n}` formats identically to
82    /// `\citep{a, b}` (determinism).
83    TokenList,
84    /// A `key=value` list consumed by a keyval-family processor — keyval, xkeyval,
85    /// pgfkeys, l3keys, or LaTeX's own option-list scanner — every one of which
86    /// strips spaces around keys and values before acting on them. That is what
87    /// licenses the formatter to break the list at a comma the author *glued*
88    /// (`[xmin=-5,xmax=5]`), materializing a space token TeX will see: in a keyval
89    /// argument the space is discarded, so the typeset output cannot change.
90    ///
91    /// The distinction is load-bearing and was settled by compiling both spellings:
92    /// keyval brackets (`\usepackage`, `\includegraphics`, `tikz`/`pgfplots`,
93    /// `lstlisting`) render identically, while *textual* optionals do not
94    /// (`\item[red,green]`, `\caption[short,list]`, `\cite[see,also]`, and a
95    /// `\newcommand` default all gain a visible space). So this flag must never be
96    /// set on an argument whose content is typeset — hold it to the same curated
97    /// standard as the math-env routing.
98    ///
99    /// Unlike [`TokenList`](ContentKind::TokenList), which flows inline with its
100    /// surrounding paragraph, a keyval list expands as its own delimited group.
101    Keyval,
102}
103
104/// One argument slot in a command/environment signature.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct ArgSpec {
107    /// Whether the argument must be present, independently of its delimiter kind.
108    pub required: bool,
109    pub kind: ArgKind,
110    /// How the formatter treats this argument's content. See [`ContentKind`].
111    pub content: ContentKind,
112    /// The mode established by this positional argument, independently of
113    /// [`ContentKind`].
114    pub domain: ArgumentDomain,
115    /// Whether this braced argument is read under a curated raw-text lexer mode.
116    /// Independent of formatter [`ContentKind`] and text-or-math
117    /// [`ArgumentDomain`].
118    pub verbatim: bool,
119}
120
121/// Match an attached group to the next positional signature slot.
122///
123/// Omitted optional slots are skipped regardless of their delimiter kind. A
124/// mismatched group never consumes a pending required slot, and an unmatched
125/// group leaves `slot` at that required slot.
126pub fn match_arg_slot(args: &[ArgSpec], slot: &mut usize, kind: ArgKind) -> Option<ArgSpec> {
127    match_arg_slot_index(args, slot, kind).map(|index| args[index])
128}
129
130/// The index-returning form of [`match_arg_slot`], used by signature help.
131pub fn match_arg_slot_index(args: &[ArgSpec], slot: &mut usize, kind: ArgKind) -> Option<usize> {
132    while *slot < args.len() {
133        let index = *slot;
134        let spec = args[index];
135        if spec.kind == kind {
136            *slot += 1;
137            return Some(index);
138        }
139        if !spec.required {
140            *slot += 1;
141            continue;
142        }
143        return None;
144    }
145    None
146}
147
148/// Match an attached raw `VERB` token to the next positional verbatim slot.
149/// Existing whole-command captures (`\url`, `\lstinline`, …) are implicit and
150/// therefore match no slot.
151pub fn match_verbatim_arg_slot(args: &[ArgSpec], slot: &mut usize) -> Option<ArgSpec> {
152    while *slot < args.len() {
153        let spec = args[*slot];
154        if spec.verbatim {
155            *slot += 1;
156            return Some(spec);
157        }
158        if !spec.required {
159            *slot += 1;
160            continue;
161        }
162        return None;
163    }
164    None
165}
166
167/// The signature of a control sequence.
168#[derive(Debug, Clone, PartialEq, Eq, Default)]
169pub struct CommandSig {
170    /// The ordered argument slots. A [`Cow`] so the build-time CWL tier can hold a
171    /// `'static` slice baked into the binary (see [`command`]) while the runtime
172    /// builtin/scanned paths own a `Vec`.
173    pub args: Cow<'static, [ArgSpec]>,
174    /// `Some(level)` for a sectioning command, where `0` is the outermost
175    /// (`\part`) and larger numbers nest deeper. Relative depth only.
176    pub sectioning: Option<u8>,
177    /// `true` for commands whose final argument is raw text the formatter must
178    /// not reshape (`\verb`, `\lstinline`, `\url`, `\code`). The lexer captures
179    /// that argument as one `VERB` token. Any leading, non-verbatim arguments
180    /// (e.g. `\mintinline`'s language) are declared in `args`; the verbatim
181    /// argument itself is implicit and not listed there.
182    pub verbatim: bool,
183    /// `true` when the verbatim argument may also be a `\verb`-style delimiter
184    /// run (`\lstinline|…|`, `\url|…|`) instead of a balanced `{…}` group.
185    /// Braced-only commands (`\code`, `\path`) capture nothing when no brace
186    /// follows and lex normally — the name may be an unrelated user macro
187    /// (`\code` as a math operator, TikZ's `\path (0,0)`), and a wrong
188    /// delimiter capture swallows text across the line. Only meaningful when
189    /// `verbatim` is set.
190    pub verbatim_delimited: bool,
191    /// `true` for horizontal-rule commands (`\hline`, `\midrule`, `\toprule`, …).
192    /// In an alignment environment a physical line made up solely of rule
193    /// commands is a *passthrough* line the formatter keeps between grid rows
194    /// rather than treating as a cell (see the grid lowering in `formatter`).
195    pub rule: bool,
196    /// `true` for *inline* commands that sit in running text (`\citep`, `\ref`,
197    /// `\emph`, `\textbf`, …) rather than occupying their own line. Paragraph reflow
198    /// treats such a command as an atom that flows into the fill even when the author
199    /// isolated it on its own source line, instead of preserving it as a
200    /// command-only line (the way a `\usepackage`/`\section` line is kept). For a
201    /// command that *also* has a `prose` argument this additionally flattens the
202    /// command into the paragraph so its body wraps as running text with the `{`/`}`
203    /// glued to the adjacent words. Block-level commands that head their own line
204    /// (`\section`, `\caption`) leave this `false`. Only meaningful to the formatter;
205    /// the parser ignores it.
206    pub inline: bool,
207    /// `true` for *block-level* commands that conventionally own their physical
208    /// line (`\usepackage`, `\newcommand`, `\maketitle`, …): package/class
209    /// loading, preamble machinery, definitions, and document structure. Prose
210    /// reflow places such a command on its own line whatever trivia the author
211    /// wrote, instead of preserving the line only when the source happened to
212    /// break there (the lone-newline predicate trivia-invariant layout forbids).
213    /// Sectioning commands are block-level too, implied by [`Self::sectioning`]
214    /// at the formatter's query, so entries carrying `sectioning` do not also
215    /// set this. Curated-only, like [`Self::verbatim_delimited`]: never from
216    /// the CWL tier or scanned definitions — an unknown macro's block-ness is
217    /// undecidable without meaning, so those fall back to the formatter's
218    /// residual authored-break rule. `\caption` and `\label` are deliberately
219    /// excluded (a glued `\caption{…} \label{…}` pair must stay untouched), as
220    /// are `\item` (owned by list layout) and `\input` (its TeX-primitive bare
221    /// form `\input docstrip.tex` leaves the filename outside the node). Only
222    /// meaningful to the formatter; the parser ignores it.
223    pub block: bool,
224}
225
226/// How an environment appears in the document-symbol outline, if at all. A small
227/// curated category over the `block` environments: only floats and theorem-likes
228/// earn an outline entry, so layout environments (`center`, `quote`, `frame`, …)
229/// stay out of the symbol tree. Drives `SymbolKind` selection in the LSP layer.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum OutlineKind {
232    /// A float (`figure`, `table`, and their starred forms).
233    Float,
234    /// A theorem-like environment (`theorem`, `lemma`, `proof`, …).
235    Theorem,
236}
237
238/// The signature of an environment.
239#[derive(Debug, Clone, PartialEq, Eq)]
240pub struct EnvironmentSig {
241    /// The ordered argument slots that follow `\begin{name}` (e.g. `tabular`'s
242    /// column spec), *excluding* the name group itself. A [`Cow`] for the same
243    /// reason as [`CommandSig::args`]: a `'static` slice for the CWL tier, an owned
244    /// `Vec` for the runtime paths.
245    pub args: Cow<'static, [ArgSpec]>,
246    /// `true` for environments whose body is raw text (`verbatim`, `lstlisting`,
247    /// `minted`, …) and must never be reflowed.
248    pub verbatim_body: bool,
249    /// `true` for environments whose *name argument* is xparse `v`-type (l3doc's
250    /// `macro`/`function`/`variable`, declared `{ O{} +v }`): besides the usual
251    /// braced form, the argument may be delimited `\verb`-style
252    /// (`\begin{macro}+\@@_compile_{:+`), chosen precisely when the name holds
253    /// unbalanced braces. The lexer captures that delimited form as one opaque
254    /// `VERB` token; the braced form lexes normally. Curated only — a wrong
255    /// grant swallows real text, so the CWL/user tiers never set it.
256    pub verbatim_arg: bool,
257    /// `true` for math environments (`equation`, `align`, …).
258    pub math: bool,
259    /// `true` for environments whose body is *real parsed code*, not prose —
260    /// the doc/ltxdoc `macrocode`/`macrocode*` (whose body is LaTeX/expl3 code,
261    /// parsed and re-lexed under the package regime, *not* an opaque verbatim
262    /// blob like `verbatim_body`). The formatter preserves the body's layout and
263    /// never reflows it as prose; the distinction from `verbatim_body` is that the
264    /// content is a real CST, not a single `VERBATIM_BODY` token.
265    pub code: bool,
266    /// `true` for environments whose body is a sequence of *delimited
267    /// statements* rather than running prose — the TikZ/pgf picture family,
268    /// whose content is `;`-terminated paths (`\draw … ;`, `\node … ;`). The
269    /// parser wraps each run up to a top-level `;` in a `STATEMENT` node, and
270    /// the formatter derives one-statement-per-line, the continuation hang,
271    /// and unit-boundary wrapping (`semantic::tikz`) from it.
272    ///
273    /// The flag also carries a **whitespace-safety claim**, the
274    /// [`ContentKind::Keyval`] pattern: whitespace *between* a flagged body's
275    /// statements is insignificant to the package that consumes them, which is
276    /// what licenses the formatter to open a new line at a statement seam the
277    /// author glued (`…;\draw`) — an inserted space token TeX sees but the
278    /// package discards. `task typeset:check` carries the proving case
279    /// (`tests/typeset/statement_seams.tex`).
280    ///
281    /// Distinct from [`code`](Self::code), which is the `.dtx` documentation
282    /// layer's `macrocode` — code re-lexed under the package regime, a fact about
283    /// *lexing*. This one is a fact about statement structure and layout, so the
284    /// two must not be conflated: a future consumer of `code` is asking a `.dtx`
285    /// question.
286    ///
287    /// **Curated tier only.** The statement terminator is package grammar, not a
288    /// TeX-surface fact, so nothing mechanical can derive this; the CWL codegen
289    /// and the runtime definition scan never set it. A wrong grant reshapes
290    /// layout for the whole body *and* asserts the whitespace claim above, so
291    /// hold it to the standard of the `math` routing flag.
292    pub statement_body: bool,
293    /// `true` when a top-level `label` entry in the environment's first optional
294    /// argument creates a LaTeX label definition. This is narrower than
295    /// [`ContentKind::Keyval`]: many key-value processors have a `label` key whose
296    /// meaning is unrelated to `\label`, so only curated package facts may set it.
297    /// Project declarations inherit the fact through `like`; the CWL and scanned
298    /// tiers never grant it.
299    pub label_key: bool,
300    /// `true` for alignment environments whose `&` columns the formatter lays out
301    /// into a grid (`align`, `pmatrix`, …). Independent of `math`: every flagged
302    /// environment here is also math, but the formatter consults this flag, not
303    /// `math`, to decide column alignment.
304    pub align: bool,
305    /// `true` for sectioning-level *containers* whose body the formatter must
306    /// *not* indent (`document`, the appendix-package `appendix`, …). The shared
307    /// property is that the body is whole sections/paragraphs — content at the
308    /// same structural altitude as the sections the container sits among, not leaf
309    /// content like a `figure` or `minipage` — which is conventionally written
310    /// flush to the margin. The body is still laid out on its own lines, just at
311    /// the surrounding indentation level rather than nested one step in.
312    pub no_indent: bool,
313    /// `true` for list environments (`itemize`, `enumerate`, `description`, …)
314    /// whose `\item`s the formatter lays out one per line, reflowing each item's
315    /// body with continuation lines hanging-indented under the item text.
316    pub list: bool,
317    /// `true` when this environment is explicitly known to occupy its own vertical
318    /// space (`figure`, `center`, verbatim, …). Math, list, and no-indent
319    /// environments are inherently block-level and are included by [`Self::block`].
320    pub block_explicit: bool,
321    /// `Some(_)` for an environment that earns a document-symbol outline entry — a
322    /// float or a theorem-like. `None` for everything else. Only meaningful to the
323    /// language server's `documentSymbol`; the parser and formatter ignore it.
324    pub outline: Option<OutlineKind>,
325}
326
327impl EnvironmentSig {
328    /// Whether the body is ordinary prose that the formatter may reflow.
329    pub const fn reflow(&self) -> bool {
330        !(self.verbatim_body || self.math || self.code || self.statement_body)
331    }
332
333    /// Whether the environment occupies its own vertical space.
334    pub const fn block(&self) -> bool {
335        self.block_explicit || self.math || self.list || self.no_indent
336    }
337}
338
339// --- const constructors (shared by the runtime JSON path and build-time codegen)
340//
341// The build script (`build.rs`) emits the CWL tier as a `phf` map whose values
342// are calls to these `const fn`s, so the static data is baked into the binary
343// with no runtime parse (see `cwl`).
344
345/// One argument slot, const-constructible for the codegen path.
346pub(crate) const fn arg(required: bool, kind: ArgKind, content: ContentKind) -> ArgSpec {
347    ArgSpec {
348        required,
349        kind,
350        content,
351        domain: ArgumentDomain::Unknown,
352        verbatim: false,
353    }
354}
355
356/// Named inputs for a generated command signature.
357pub(crate) struct GeneratedCommand {
358    args: &'static [ArgSpec],
359    sectioning: Option<u8>,
360    verbatim: bool,
361    rule: bool,
362    inline: bool,
363}
364
365/// A command signature over a `'static` argument slice (the codegen path).
366pub(crate) const fn command(generated: GeneratedCommand) -> CommandSig {
367    CommandSig {
368        args: Cow::Borrowed(generated.args),
369        sectioning: generated.sectioning,
370        verbatim: generated.verbatim,
371        // The codegen (CWL) tier is arity-only, so the delimiter facet — like
372        // every behavior flag — never comes from it.
373        verbatim_delimited: false,
374        rule: generated.rule,
375        inline: generated.inline,
376        // Curated-only facet, like the delimiter one: block-ness never comes
377        // from the codegen (CWL) tier.
378        block: false,
379    }
380}
381
382/// Named inputs for a generated environment signature.
383pub(crate) struct GeneratedEnvironment {
384    args: &'static [ArgSpec],
385    verbatim_body: bool,
386    math: bool,
387    code: bool,
388    align: bool,
389    no_indent: bool,
390    list: bool,
391    block_explicit: bool,
392    outline: Option<OutlineKind>,
393}
394
395/// An environment signature over a `'static` argument slice (the codegen path),
396/// storing the explicit source facts from the generated data.
397pub(crate) const fn environment(generated: GeneratedEnvironment) -> EnvironmentSig {
398    EnvironmentSig {
399        args: Cow::Borrowed(generated.args),
400        verbatim_body: generated.verbatim_body,
401        // The codegen (CWL) tier is arity-only, so the verbatim-argument facet —
402        // like every behavior flag — never comes from it.
403        verbatim_arg: false,
404        math: generated.math,
405        code: generated.code,
406        // Curated-only facet, like the verbatim-argument one: a statement body is
407        // package grammar the mechanical tier cannot see.
408        statement_body: false,
409        // A key named `label` is not enough to prove `\label` semantics, so the
410        // mechanical CWL tier can never grant this fact.
411        label_key: false,
412        align: generated.align,
413        no_indent: generated.no_indent,
414        list: generated.list,
415        block_explicit: generated.block_explicit,
416        outline: generated.outline,
417    }
418}
419
420/// The built-in command and environment signatures, keyed by name (without the
421/// leading `\` for commands, the bare name for environments). Case-sensitive, as
422/// LaTeX names are (`Verbatim` ≠ `verbatim`).
423#[derive(Debug, Default, Clone, PartialEq, Eq)]
424pub struct SignatureDb {
425    commands: HashMap<SmolStr, CommandSig>,
426    environments: HashMap<SmolStr, EnvironmentSig>,
427    /// Which loaded package (by file stem) a command signature came from, when
428    /// it was merged with an explicit origin via [`merge_from`](Self::merge_from).
429    /// Absent for the document's own definitions and for every static tier
430    /// (built-in/CWL DBs never carry origins). A side map rather than a
431    /// `CommandSig` field so the phf-generated static tables stay untouched.
432    command_origins: HashMap<SmolStr, SmolStr>,
433    /// The environment mirror of [`command_origins`](Self::command_origins).
434    environment_origins: HashMap<SmolStr, SmolStr>,
435    /// File-local *environment aliases*, opener side: a command name (without the
436    /// leading `\`) whose definition body is exactly `\begin{X}`, mapped to the
437    /// target environment `X`. Populated only by the per-file definition scan
438    /// ([`super::define`]), which admits an alias solely when `X` is a curated
439    /// built-in environment that is non-verbatim and takes no arguments, and when
440    /// both halves of the pair are defined in the same file.
441    ///
442    /// A *side map*, deliberately not an [`EnvironmentSig`] cloned under the alias
443    /// name: the alias is a command, not an environment, so it must not appear in
444    /// [`environment_names`](Self::environment_names) (that would offer
445    /// `\begin{bea}` to completion) and must not mask a real
446    /// `\newenvironment{bea}`. Nor may a *literal* `\begin{bea}` acquire the
447    /// target's behavior — which is why the only lookup that consults this map is
448    /// [`Signatures::environment_at`], keyed on the node so it can tell an alias
449    /// delimiter from a spelled-out environment that happens to share the name.
450    /// The plain name-keyed [`Signatures::environment`] never reads it.
451    env_begin_aliases: HashMap<SmolStr, SmolStr>,
452    /// The closer mirror of [`env_begin_aliases`](Self::env_begin_aliases): a
453    /// command whose body is exactly `\end{X}`. Kept separate rather than tagged
454    /// with a side, so the parser's opener and closer indices cannot be confused
455    /// and [`Signatures::environment`] can consult the opener side alone.
456    env_end_aliases: HashMap<SmolStr, SmolStr>,
457    /// Which environment signatures came from a project *declaration*
458    /// ([`crate::declarations`]) rather than from a scan.
459    ///
460    /// Provenance, like the origin maps above, and needed for the same kind of
461    /// reason: [`Signatures::environment_at`] resolves an alias target against
462    /// *curated* data only, so it has to tell a declared entry (curated — `like`
463    /// copies a built-in and resolves against nothing else) from a scanned
464    /// `\newenvironment` of the same name (not curated, and deliberately unable
465    /// to lend an alias its behavior). Without the mark the two are
466    /// indistinguishable once merged into one scope.
467    declared_environments: std::collections::HashSet<SmolStr>,
468}
469
470impl SignatureDb {
471    /// The signature of command `name` (without the leading `\`), if known.
472    pub fn command(&self, name: &str) -> Option<&CommandSig> {
473        self.commands.get(name)
474    }
475
476    /// The signature of environment `name`, if known.
477    pub fn environment(&self, name: &str) -> Option<&EnvironmentSig> {
478        self.environments.get(name)
479    }
480
481    /// All known command names (without the leading `\`), in arbitrary order.
482    /// Backs name completion, which unions these with the per-document scanned
483    /// definitions; the lookup methods stay the only refinement path.
484    pub fn command_names(&self) -> impl Iterator<Item = &str> {
485        self.commands.keys().map(SmolStr::as_str)
486    }
487
488    /// All known environment names, in arbitrary order. See [`command_names`].
489    ///
490    /// [`command_names`]: Self::command_names
491    pub fn environment_names(&self) -> impl Iterator<Item = &str> {
492        self.environments.keys().map(SmolStr::as_str)
493    }
494
495    /// The environment `name` opens, if the per-file scan recorded it as an
496    /// environment alias ([`env_begin_aliases`](Self::env_begin_aliases)). The name
497    /// carries no leading `\`.
498    pub fn env_begin_alias(&self, name: &str) -> Option<&str> {
499        self.env_begin_aliases.get(name).map(SmolStr::as_str)
500    }
501
502    /// The closer mirror of [`env_begin_alias`](Self::env_begin_alias).
503    pub fn env_end_alias(&self, name: &str) -> Option<&str> {
504        self.env_end_aliases.get(name).map(SmolStr::as_str)
505    }
506
507    /// Every recorded opener alias, as `(alias, target)` pairs in arbitrary order.
508    /// Backs the parser's projection of the map into its parse context.
509    pub fn env_begin_aliases(&self) -> impl Iterator<Item = (&str, &str)> {
510        self.env_begin_aliases
511            .iter()
512            .map(|(k, v)| (k.as_str(), v.as_str()))
513    }
514
515    /// The closer mirror of [`env_begin_aliases`](Self::env_begin_aliases).
516    pub fn env_end_aliases(&self) -> impl Iterator<Item = (&str, &str)> {
517        self.env_end_aliases
518            .iter()
519            .map(|(k, v)| (k.as_str(), v.as_str()))
520    }
521
522    /// Record an opener alias, replacing any existing entry for `name`.
523    pub fn insert_env_begin_alias(&mut self, name: impl Into<SmolStr>, target: impl Into<SmolStr>) {
524        self.env_begin_aliases.insert(name.into(), target.into());
525    }
526
527    /// Record a closer alias, replacing any existing entry for `name`.
528    pub fn insert_env_end_alias(&mut self, name: impl Into<SmolStr>, target: impl Into<SmolStr>) {
529        self.env_end_aliases.insert(name.into(), target.into());
530    }
531
532    /// The package (file stem) whose merge supplied the current signature of
533    /// command `name`, if it came from a package
534    /// ([`merge_from`](Self::merge_from) with `Some(origin)`) rather than the
535    /// document or a static tier.
536    pub fn command_origin(&self, name: &str) -> Option<&str> {
537        self.command_origins.get(name).map(SmolStr::as_str)
538    }
539
540    /// The environment mirror of [`command_origin`](Self::command_origin).
541    pub fn environment_origin(&self, name: &str) -> Option<&str> {
542        self.environment_origins.get(name).map(SmolStr::as_str)
543    }
544
545    /// Record a command signature, replacing any existing entry for `name`. Used
546    /// by the per-file definition scan ([`super::define`]) to populate a fresh DB;
547    /// the built-in DB is built from JSON and never mutated. A redefinition wins,
548    /// mirroring TeX's last-`\newcommand`-wins behavior; any recorded package
549    /// origin is cleared, since it described the entry being replaced.
550    pub fn insert_command(&mut self, name: impl Into<SmolStr>, sig: CommandSig) {
551        let name = name.into();
552        self.command_origins.remove(&name);
553        self.commands.insert(name, sig);
554    }
555
556    /// Record an environment signature, replacing any existing entry for `name`.
557    pub fn insert_environment(&mut self, name: impl Into<SmolStr>, sig: EnvironmentSig) {
558        let name = name.into();
559        self.environment_origins.remove(&name);
560        self.declared_environments.remove(&name);
561        self.environments.insert(name, sig);
562    }
563
564    /// Record an environment signature that came from a project *declaration*,
565    /// replacing any existing entry for `name` and marking its provenance. See
566    /// [`declared_environments`](Self::declared_environments) for why the mark
567    /// exists.
568    pub fn insert_declared_environment(&mut self, name: impl Into<SmolStr>, sig: EnvironmentSig) {
569        let name = name.into();
570        self.insert_environment(name.clone(), sig);
571        self.declared_environments.insert(name);
572    }
573
574    /// Whether `name`'s signature came from a project declaration.
575    pub fn is_declared_environment(&self, name: &str) -> bool {
576        self.declared_environments.contains(name)
577    }
578
579    /// Merge every command and environment of `other` into `self`, with `other`
580    /// winning on a name clash (last-definition-wins, like an individual
581    /// `insert_*`). Used to fold a loaded package's scanned definitions into a
582    /// document's merged signature scope; the caller orders the merges so the
583    /// document's own definitions are applied last and override any package.
584    ///
585    /// When `origin` is `Some`, it replaces the provenance of every merged
586    /// signature. When it is `None`, each entry inherits `other`'s provenance,
587    /// clearing stale provenance when `other` has none.
588    pub fn merge_from(&mut self, other: &SignatureDb, origin: Option<&str>) {
589        for (name, sig) in &other.commands {
590            match origin
591                .map(SmolStr::new)
592                .or_else(|| other.command_origins.get(name).cloned())
593            {
594                Some(origin) => {
595                    self.command_origins.insert(name.clone(), origin);
596                }
597                None => {
598                    self.command_origins.remove(name);
599                }
600            }
601            self.commands.insert(name.clone(), sig.clone());
602        }
603        for (name, sig) in &other.environments {
604            match origin
605                .map(SmolStr::new)
606                .or_else(|| other.environment_origins.get(name).cloned())
607            {
608                Some(origin) => {
609                    self.environment_origins.insert(name.clone(), origin);
610                }
611                None => {
612                    self.environment_origins.remove(name);
613                }
614            }
615            // Declared-ness describes the *current* entry, exactly as the origin
616            // above does: an overwrite from a non-declared source clears it, so a
617            // scanned definition merged over a declared name cannot leave the
618            // alias resolver believing the entry is still curated.
619            if origin.is_none() && other.is_declared_environment(name) {
620                self.declared_environments.insert(name.clone());
621            } else {
622                self.declared_environments.remove(name);
623            }
624            self.environments.insert(name.clone(), sig.clone());
625        }
626        for (name, target) in &other.env_begin_aliases {
627            self.env_begin_aliases.insert(name.clone(), target.clone());
628        }
629        for (name, target) in &other.env_end_aliases {
630            self.env_end_aliases.insert(name.clone(), target.clone());
631        }
632    }
633
634    /// Overlay a project's resolved [declarations](crate::declarations) as the
635    /// **top tier** of this scope: a declaration is the user explicitly
636    /// correcting an inference, so it wins over scanned definitions and loaded
637    /// packages alike.
638    ///
639    /// A named entry rather than `merge_from(declared.as_db(), None)` at each call
640    /// site, so the precedence rule is stated once and the two scope builders
641    /// (the CLI's `collect_package_signatures` and the salsa `scope_signatures`)
642    /// cannot disagree about where in the order it goes.
643    pub fn merge_declarations(&mut self, declared: &crate::declarations::ResolvedDeclarations) {
644        self.merge_from(declared.as_db(), None);
645    }
646}
647
648/// A two-tier signature lookup: a per-document [`SignatureDb`] of scanned
649/// `\newcommand`/`\newenvironment`/xparse definitions consulted first, falling back
650/// to the process-wide [`builtin`] DB. Cheap to copy (it borrows the scanned DB),
651/// so it threads through the formatter's lowering like a context handle.
652///
653/// Scanned-first matches TeX scoping intuition: a locally (re)defined command
654/// shadows a built-in of the same name. (We do not yet model *where* a definition
655/// becomes visible — a whole-file union — which is sound for the formatter's arity
656/// needs; lexical/conditional visibility is out of scope, per AGENTS.md #1.)
657#[derive(Debug, Clone, Copy)]
658pub struct Signatures<'a> {
659    user: &'a SignatureDb,
660}
661
662impl<'a> Signatures<'a> {
663    /// Resolve against `user` first, then the built-in DB.
664    pub fn new(user: &'a SignatureDb) -> Self {
665        Self { user }
666    }
667
668    /// The signature of command `name`: scanned definition first, then the curated
669    /// built-in, then the bulk CWL tier. CWL is consulted last and contributes only
670    /// argument arity (its behavior flags are all default), so a CWL-only command is
671    /// laid out like any unknown command, just with its argument count known.
672    pub fn command(&self, name: &str) -> Option<&'a CommandSig> {
673        self.user
674            .command(name)
675            .or_else(|| builtin().command(name))
676            .or_else(|| cwl().command(name))
677    }
678
679    /// The signature of environment `name`: scanned, then built-in, then CWL. See
680    /// [`command`] for why the CWL tier is safe to consult here.
681    ///
682    /// Environment *aliases* are deliberately **not** consulted: an alias names a
683    /// command, and a name alone cannot tell a `\bea`-opened delimiter from a
684    /// literal `\begin{bea}` that happens to spell the same word. Resolve those
685    /// through [`environment_at`](Self::environment_at), which has the node.
686    ///
687    /// [`command`]: Self::command
688    pub fn environment(&self, name: &str) -> Option<&'a EnvironmentSig> {
689        self.user
690            .environment(name)
691            .or_else(|| builtin().environment(name))
692            .or_else(|| cwl().environment(name))
693    }
694
695    /// The signature `name` was *declared* with, if the scope carries one. The
696    /// curated half of the alias resolution above; never a scanned entry.
697    fn declared_environment(&self, name: &str) -> Option<&'a EnvironmentSig> {
698        self.user
699            .is_declared_environment(name)
700            .then(|| self.user.environment(name))
701            .flatten()
702    }
703
704    /// The signature governing `node` — an `ENVIRONMENT` or its `BEGIN` — which is
705    /// [`environment`](Self::environment) except that an *environment-alias*
706    /// delimiter resolves through the alias map instead.
707    ///
708    /// This is the node-keyed lookup every layout decision wants, because an alias
709    /// `BEGIN` (a bare control word, [`Begin::is_alias`]) and a literal `\begin{X}`
710    /// are indistinguishable once reduced to a name. Only the former inherits the
711    /// target's behavior; a literal `\begin{bea}` in a file that also defines `\bea`
712    /// as an alias is an unrelated environment of that name and stays unknown.
713    ///
714    /// The alias arm resolves against **curated data only**, for the same reason
715    /// the parser's `ParseCtx::is_math_environment` does: an alias declares a
716    /// *spelling*, never a *semantic*, so every behavior flag still comes from
717    /// curated data. That means [`builtin`] plus the scope's *declared* entries
718    /// — a declaration is curated (`like` copies a built-in entry and resolves
719    /// against nothing else), which is what lets `\startmyenv … \endmyenv` reach
720    /// the behavior of a `myenv` that has no built-in counterpart. A scanned
721    /// `\newenvironment` of the same name still lends an alias nothing.
722    ///
723    /// [`Begin::is_alias`]: crate::ast::Begin::is_alias
724    pub fn environment_at(&self, node: &SyntaxNode) -> Option<&'a EnvironmentSig> {
725        use crate::ast::{AstNode, Begin, child};
726        let begin = match node.kind() {
727            SyntaxKind::BEGIN => Begin::cast(node.clone())?,
728            _ => child::<Begin>(node)?,
729        };
730        let name = begin.name()?;
731        if begin.is_alias() {
732            return self.user.env_begin_alias(&name).and_then(|target| {
733                self.declared_environment(target)
734                    .or_else(|| builtin().environment(target))
735            });
736        }
737        self.environment(&name)
738    }
739}
740
741/// The bundled, curated signature data (see module docs).
742const SIGNATURES_JSON: &str = include_str!("../../data/signatures.json");
743
744static DB: LazyLock<SignatureDb> =
745    LazyLock::new(|| parse(SIGNATURES_JSON).expect("bundled data/signatures.json must be valid"));
746
747/// The process-wide built-in signature database.
748pub fn builtin() -> &'static SignatureDb {
749    &DB
750}
751
752/// The type of the build-generated CWL maps: a name-keyed perfect-hash map. The
753/// generated `static`s are spelled with this alias, so the dependency on `phf` is
754/// visible in checked-in source (not only in the generated file).
755type CwlSigMap<V> = phf::Map<&'static str, V>;
756
757// The bulk CWL tier is generated by `build.rs` from `data/cwl_signatures.json`
758// into two `CwlSigMap`s (`CWL_COMMANDS`, `CWL_ENVIRONMENTS`) whose values are
759// `command(...)`/`environment(...)`/`arg(...)` const-constructor calls — so the
760// data is baked into the binary as read-only statics with *zero* runtime parse
761// or decompress (it was a ~4.5 ms one-time `LazyLock` decompress+JSON-parse; now
762// ~0). The included file references the const constructors and `CwlSigMap` here.
763include!(concat!(env!("OUT_DIR"), "/cwl_signatures.rs"));
764
765/// Handle to the lower-precision **CWL tier**: a broad set of command/environment
766/// names plus argument shapes harvested from the TeXstudio CWL corpus (a curated
767/// package subset; see `scripts/gen_cwl_signatures.py`). It carries *names and
768/// arity only* — every behavior flag (`content`/`verbatim`/`sectioning`/`math`/…) is
769/// left at its default — so it can widen completion and the formatter's arity
770/// lookup without its low-confidence data ever reaching a lexer/outline behavior
771/// decision. Consulted strictly *under* [`builtin`] (via [`Signatures`]); the
772/// curated tier always wins. A ZST over the generated `phf` statics, so its query
773/// methods mirror [`SignatureDb`]'s without owning a heap map.
774#[derive(Debug, Clone, Copy)]
775pub struct CwlDb;
776
777impl CwlDb {
778    /// The signature of command `name` (without the leading `\`), if in the tier.
779    pub fn command(&self, name: &str) -> Option<&'static CommandSig> {
780        CWL_COMMANDS.get(name)
781    }
782
783    /// The signature of environment `name`, if in the tier.
784    pub fn environment(&self, name: &str) -> Option<&'static EnvironmentSig> {
785        CWL_ENVIRONMENTS.get(name)
786    }
787
788    /// All CWL command names (without the leading `\`), in arbitrary order. The
789    /// `&str` lifetime is tied to `&self` (not `'static`) so it unifies with the
790    /// borrowed scanned-definition names in a completion `chain` (see
791    /// `completion::command_candidates`), exactly like [`SignatureDb::command_names`].
792    pub fn command_names(&self) -> impl Iterator<Item = &str> {
793        CWL_COMMANDS.keys().map(|name| &**name)
794    }
795
796    /// All CWL environment names, in arbitrary order. See [`command_names`].
797    ///
798    /// [`command_names`]: Self::command_names
799    pub fn environment_names(&self) -> impl Iterator<Item = &str> {
800        CWL_ENVIRONMENTS.keys().map(|name| &**name)
801    }
802
803    /// All CWL command signatures (introspection; backs the invariant tests).
804    pub fn command_sigs(&self) -> impl Iterator<Item = &'static CommandSig> {
805        CWL_COMMANDS.values()
806    }
807
808    /// All CWL environment signatures (introspection; backs the invariant tests).
809    pub fn environment_sigs(&self) -> impl Iterator<Item = &'static EnvironmentSig> {
810        CWL_ENVIRONMENTS.values()
811    }
812}
813
814static CWL: CwlDb = CwlDb;
815
816/// The process-wide CWL tier (see [`CwlDb`]).
817pub fn cwl() -> &'static CwlDb {
818    &CWL
819}
820
821// --- On-disk schema (serde) ---------------------------------------------------
822//
823// A thin deserialization mirror of the in-memory types, kept separate so the
824// public API stays free of serde concerns and the JSON can use a compact,
825// hand-authorable spelling (`"req"`/`"opt"` for arguments; flags defaulting to
826// false; `reflow` derived rather than stored).
827
828/// An argument's bracket as written in the JSON: `"req"` (mandatory `{…}`) or
829/// `"opt"` (optional `[…]`).
830#[derive(Deserialize, Clone, Copy)]
831#[serde(rename_all = "lowercase")]
832enum RawArgKind {
833    Req,
834    Opt,
835}
836
837impl RawArgKind {
838    fn required(self) -> bool {
839        matches!(self, RawArgKind::Req)
840    }
841
842    fn kind(self) -> ArgKind {
843        match self {
844            RawArgKind::Req => ArgKind::Brace,
845            RawArgKind::Opt => ArgKind::Bracket,
846        }
847    }
848}
849
850/// An argument's content kind as written in the JSON: `"opaque"` (default),
851/// `"prose"`, `"tokenList"`, or `"keyval"`. Mirrors [`ContentKind`].
852#[derive(Deserialize, Clone, Copy, Default)]
853#[serde(rename_all = "camelCase")]
854enum RawContentKind {
855    #[default]
856    Opaque,
857    Prose,
858    TokenList,
859    Keyval,
860}
861
862#[derive(Deserialize, Clone, Copy, Default)]
863#[serde(rename_all = "lowercase")]
864enum RawArgumentDomain {
865    #[default]
866    Unknown,
867    Math,
868    Text,
869}
870
871impl From<RawArgumentDomain> for ArgumentDomain {
872    fn from(raw: RawArgumentDomain) -> Self {
873        match raw {
874            RawArgumentDomain::Unknown => ArgumentDomain::Unknown,
875            RawArgumentDomain::Math => ArgumentDomain::Math,
876            RawArgumentDomain::Text => ArgumentDomain::Text,
877        }
878    }
879}
880
881impl From<RawContentKind> for ContentKind {
882    fn from(raw: RawContentKind) -> Self {
883        match raw {
884            RawContentKind::Opaque => ContentKind::Opaque,
885            RawContentKind::Prose => ContentKind::Prose,
886            RawContentKind::TokenList => ContentKind::TokenList,
887            RawContentKind::Keyval => ContentKind::Keyval,
888        }
889    }
890}
891
892/// One argument as written in the JSON. Either the compact string shorthand
893/// (`"req"` / `"opt"`, the common case, content defaulting to `"opaque"`) or an
894/// object form `{ "kind": "req", "content": "prose" }` / `{ "kind": "req",
895/// "content": "tokenList" }` that additionally marks the argument's content kind
896/// (see [`ContentKind`]).
897#[derive(Deserialize)]
898#[serde(untagged)]
899enum RawArg {
900    Short(RawArgKind),
901    Full {
902        kind: RawArgKind,
903        #[serde(default)]
904        content: RawContentKind,
905        #[serde(default)]
906        domain: RawArgumentDomain,
907        #[serde(default)]
908        verbatim: bool,
909    },
910}
911
912impl From<RawArg> for ArgSpec {
913    fn from(raw: RawArg) -> Self {
914        match raw {
915            RawArg::Short(kind) => ArgSpec {
916                required: kind.required(),
917                kind: kind.kind(),
918                content: ContentKind::Opaque,
919                domain: ArgumentDomain::Unknown,
920                verbatim: false,
921            },
922            RawArg::Full {
923                kind,
924                content,
925                domain,
926                verbatim,
927            } => ArgSpec {
928                required: kind.required(),
929                kind: kind.kind(),
930                content: content.into(),
931                domain: domain.into(),
932                verbatim,
933            },
934        }
935    }
936}
937
938#[derive(Deserialize, Default)]
939#[serde(deny_unknown_fields)]
940struct RawCommand {
941    #[serde(default)]
942    args: Vec<RawArg>,
943    #[serde(default)]
944    sectioning: Option<u8>,
945    #[serde(default)]
946    verbatim: bool,
947    #[serde(default, rename = "verbatimDelimited")]
948    verbatim_delimited: bool,
949    #[serde(default)]
950    rule: bool,
951    #[serde(default)]
952    inline: bool,
953    #[serde(default)]
954    block: bool,
955}
956
957impl From<RawCommand> for CommandSig {
958    fn from(raw: RawCommand) -> Self {
959        CommandSig {
960            args: Cow::Owned(raw.args.into_iter().map(ArgSpec::from).collect()),
961            sectioning: raw.sectioning,
962            verbatim: raw.verbatim,
963            verbatim_delimited: raw.verbatim_delimited,
964            rule: raw.rule,
965            inline: raw.inline,
966            block: raw.block,
967        }
968    }
969}
970
971/// An environment's outline category as written in the JSON: `"float"` or
972/// `"theorem"` (absent → `None`, no outline entry).
973#[derive(Deserialize, Clone, Copy)]
974#[serde(rename_all = "lowercase")]
975enum RawOutlineKind {
976    Float,
977    Theorem,
978}
979
980impl From<RawOutlineKind> for OutlineKind {
981    fn from(raw: RawOutlineKind) -> Self {
982        match raw {
983            RawOutlineKind::Float => OutlineKind::Float,
984            RawOutlineKind::Theorem => OutlineKind::Theorem,
985        }
986    }
987}
988
989#[derive(Deserialize, Default)]
990#[serde(deny_unknown_fields)]
991struct RawEnvironment {
992    #[serde(default)]
993    args: Vec<RawArg>,
994    #[serde(default, rename = "verbatimBody")]
995    verbatim_body: bool,
996    #[serde(default, rename = "verbatimArg")]
997    verbatim_arg: bool,
998    #[serde(default)]
999    math: bool,
1000    #[serde(default)]
1001    code: bool,
1002    #[serde(default, rename = "statementBody")]
1003    statement_body: bool,
1004    #[serde(default, rename = "labelKey")]
1005    label_key: bool,
1006    #[serde(default)]
1007    align: bool,
1008    #[serde(default, rename = "noIndent")]
1009    no_indent: bool,
1010    #[serde(default)]
1011    list: bool,
1012    #[serde(default)]
1013    block: bool,
1014    #[serde(default)]
1015    outline: Option<RawOutlineKind>,
1016}
1017
1018impl From<RawEnvironment> for EnvironmentSig {
1019    fn from(raw: RawEnvironment) -> Self {
1020        EnvironmentSig {
1021            args: Cow::Owned(raw.args.into_iter().map(ArgSpec::from).collect()),
1022            verbatim_body: raw.verbatim_body,
1023            verbatim_arg: raw.verbatim_arg,
1024            math: raw.math,
1025            code: raw.code,
1026            statement_body: raw.statement_body,
1027            label_key: raw.label_key,
1028            align: raw.align,
1029            no_indent: raw.no_indent,
1030            list: raw.list,
1031            block_explicit: raw.block,
1032            outline: raw.outline.map(OutlineKind::from),
1033        }
1034    }
1035}
1036
1037#[derive(Deserialize, Default)]
1038#[serde(deny_unknown_fields)]
1039struct RawDb {
1040    /// An optional top-level provenance header (the generated `cwl_signatures.json`
1041    /// carries one); accepted and discarded so `deny_unknown_fields` still rejects
1042    /// genuine typos elsewhere.
1043    #[serde(default, rename = "_comment")]
1044    _comment: Option<serde::de::IgnoredAny>,
1045    #[serde(default)]
1046    commands: HashMap<String, RawCommand>,
1047    #[serde(default)]
1048    environments: HashMap<String, RawEnvironment>,
1049}
1050
1051/// Deserialize the bundled JSON into a [`SignatureDb`].
1052fn parse(json: &str) -> serde_json::Result<SignatureDb> {
1053    let raw: RawDb = serde_json::from_str(json)?;
1054    Ok(SignatureDb {
1055        commands: raw
1056            .commands
1057            .into_iter()
1058            .map(|(name, sig)| (SmolStr::new(name), sig.into()))
1059            .collect(),
1060        environments: raw
1061            .environments
1062            .into_iter()
1063            .map(|(name, sig)| (SmolStr::new(name), sig.into()))
1064            .collect(),
1065        command_origins: HashMap::new(),
1066        environment_origins: HashMap::new(),
1067        // Aliases are a per-file scan product only; the curated JSON never carries any.
1068        env_begin_aliases: HashMap::new(),
1069        env_end_aliases: HashMap::new(),
1070        // The built-in tier *is* the curated data a declaration copies from, so
1071        // nothing in it is itself declared.
1072        declared_environments: std::collections::HashSet::new(),
1073    })
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079
1080    #[test]
1081    fn bundled_json_loads() {
1082        let db = builtin();
1083        assert!(db.command("section").is_some());
1084        assert!(db.environment("tabular").is_some());
1085    }
1086
1087    #[test]
1088    fn loads_and_resolves_known_commands() {
1089        let db = builtin();
1090        assert_eq!(db.command("frac").map(|c| c.args.len()), Some(2));
1091        assert!(db.command("frac").unwrap().args.iter().all(|a| a.required));
1092    }
1093
1094    #[test]
1095    fn optional_then_mandatory_order_preserved() {
1096        let args = &builtin().command("includegraphics").unwrap().args;
1097        assert_eq!(args.len(), 2);
1098        assert_eq!(args[0].kind, ArgKind::Bracket);
1099        assert!(!args[0].required);
1100        assert_eq!(args[1].kind, ArgKind::Brace);
1101        assert!(args[1].required);
1102    }
1103
1104    #[test]
1105    fn mixed_argument_order_round_trips() {
1106        let args = &builtin().command("newcommand").unwrap().args;
1107        let kinds: Vec<_> = args.iter().map(|a| a.kind).collect();
1108        assert_eq!(
1109            kinds,
1110            vec![ArgKind::Brace, ArgKind::Bracket, ArgKind::Brace]
1111        );
1112    }
1113
1114    #[test]
1115    fn outline_categories_assigned() {
1116        let db = builtin();
1117        assert_eq!(
1118            db.environment("figure").unwrap().outline,
1119            Some(OutlineKind::Float)
1120        );
1121        assert_eq!(
1122            db.environment("table*").unwrap().outline,
1123            Some(OutlineKind::Float)
1124        );
1125        assert_eq!(
1126            db.environment("theorem").unwrap().outline,
1127            Some(OutlineKind::Theorem)
1128        );
1129        assert_eq!(db.environment("center").unwrap().outline, None);
1130    }
1131
1132    #[test]
1133    fn sectioning_levels_assigned() {
1134        let db = builtin();
1135        assert_eq!(db.command("part").unwrap().sectioning, Some(0));
1136        assert_eq!(db.command("section").unwrap().sectioning, Some(2));
1137        assert_eq!(db.command("subsubsection").unwrap().sectioning, Some(4));
1138        assert_eq!(db.command("section").unwrap().args.len(), 2);
1139        assert!(db.command("textbf").unwrap().sectioning.is_none());
1140    }
1141
1142    #[test]
1143    fn block_commands_flagged() {
1144        let db = builtin();
1145        assert!(db.command("usepackage").unwrap().block);
1146        assert!(db.command("newcommand").unwrap().block);
1147        assert!(db.command("maketitle").unwrap().block);
1148        assert!(db.command("title").unwrap().block);
1149        assert_eq!(db.command("usepackage").unwrap().args.len(), 2);
1150        assert!(!db.command("caption").unwrap().block);
1151        assert!(!db.command("label").unwrap().block);
1152        assert!(!db.command("textbf").unwrap().block);
1153        assert!(!db.command("section").unwrap().block);
1154    }
1155
1156    #[test]
1157    fn no_command_is_both_inline_and_block() {
1158        for name in builtin().command_names() {
1159            let sig = builtin().command(name).unwrap();
1160            assert!(
1161                !(sig.inline && sig.block),
1162                "`\\{name}` is flagged both inline and block"
1163            );
1164        }
1165    }
1166
1167    #[test]
1168    fn verbatim_commands_flagged() {
1169        assert!(builtin().command("verb").unwrap().verbatim);
1170        assert!(builtin().command("lstinline").unwrap().verbatim);
1171        assert!(!builtin().command("textbf").unwrap().verbatim);
1172        assert!(builtin().command("lstinline").unwrap().verbatim_delimited);
1173        assert!(!builtin().command("code").unwrap().verbatim_delimited);
1174        assert!(!builtin().command("path").unwrap().verbatim_delimited);
1175    }
1176
1177    #[test]
1178    fn content_kind_parses_from_both_forms() {
1179        let db = parse(
1180            r#"{ "commands": {
1181                "short": { "args": ["req"] },
1182                "full":  { "args": ["opt", { "kind": "req", "content": "prose" }] },
1183                "kv":    { "args": [{ "kind": "opt", "content": "keyval" }, "req"] },
1184                "list":  { "args": [{ "kind": "req", "content": "tokenList" }] }
1185            } }"#,
1186        )
1187        .expect("valid content schema");
1188        let short = &db.command("short").unwrap().args;
1189        assert_eq!(short[0].content, ContentKind::Opaque);
1190        let full = &db.command("full").unwrap().args;
1191        assert_eq!(full[0].kind, ArgKind::Bracket);
1192        assert_eq!(full[0].content, ContentKind::Opaque); // no `content` → default
1193        assert_eq!(full[1].kind, ArgKind::Brace);
1194        assert_eq!(full[1].content, ContentKind::Prose);
1195        let kv = &db.command("kv").unwrap().args;
1196        assert_eq!(kv[0].kind, ArgKind::Bracket);
1197        assert_eq!(kv[0].content, ContentKind::Keyval);
1198        assert_eq!(kv[1].content, ContentKind::Opaque);
1199        let list = &db.command("list").unwrap().args;
1200        assert_eq!(list[0].content, ContentKind::TokenList);
1201    }
1202
1203    #[test]
1204    fn positional_verbatim_defaults_off_and_parses_from_full_form() {
1205        let db = parse(
1206            r#"{ "commands": {
1207                "short": { "args": ["req"] },
1208                "raw": { "args": [{ "kind": "req", "verbatim": true }, "req"] }
1209            } }"#,
1210        )
1211        .expect("valid positional verbatim schema");
1212
1213        assert!(!db.command("short").unwrap().args[0].verbatim);
1214        let raw = &db.command("raw").unwrap().args;
1215        assert!(raw[0].verbatim);
1216        assert!(!raw[1].verbatim);
1217    }
1218
1219    #[test]
1220    fn positional_verbatim_slot_keeps_later_groups_aligned() {
1221        let args = &builtin().command("href").unwrap().args;
1222        let mut slot = 0;
1223
1224        assert_eq!(
1225            match_arg_slot_index(args, &mut slot, ArgKind::Bracket),
1226            Some(0)
1227        );
1228        assert!(match_verbatim_arg_slot(args, &mut slot).is_some());
1229        assert_eq!(
1230            match_arg_slot_index(args, &mut slot, ArgKind::Brace),
1231            Some(2)
1232        );
1233    }
1234
1235    #[test]
1236    fn argument_domain_defaults_and_json_values_are_independent_of_content() {
1237        let db = parse(
1238            r#"{ "commands": {
1239                "short": { "args": ["req"] },
1240                "math": { "args": [{ "kind": "req", "content": "prose", "domain": "math" }] },
1241                "text": { "args": [{ "kind": "opt", "domain": "text" }] }
1242            } }"#,
1243        )
1244        .unwrap();
1245        assert_eq!(
1246            db.command("short").unwrap().args[0].domain,
1247            ArgumentDomain::Unknown
1248        );
1249        assert_eq!(
1250            db.command("math").unwrap().args[0].domain,
1251            ArgumentDomain::Math
1252        );
1253        assert_eq!(
1254            db.command("math").unwrap().args[0].content,
1255            ContentKind::Prose
1256        );
1257        assert_eq!(
1258            db.command("text").unwrap().args[0].domain,
1259            ArgumentDomain::Text
1260        );
1261        assert!(
1262            cwl()
1263                .command("multicolumn")
1264                .unwrap()
1265                .args
1266                .iter()
1267                .all(|arg| arg.domain == ArgumentDomain::Unknown)
1268        );
1269    }
1270
1271    #[test]
1272    fn positional_matching_skips_only_omitted_optionals() {
1273        let args = &builtin().command("sqrt").unwrap().args;
1274        let mut slot = 0;
1275        assert_eq!(
1276            match_arg_slot_index(args, &mut slot, ArgKind::Brace),
1277            Some(1)
1278        );
1279        assert_eq!(slot, 2);
1280
1281        let mut slot = 0;
1282        assert_eq!(
1283            match_arg_slot_index(args, &mut slot, ArgKind::Bracket),
1284            Some(0)
1285        );
1286        assert_eq!(
1287            match_arg_slot_index(args, &mut slot, ArgKind::Brace),
1288            Some(1)
1289        );
1290        assert_eq!(match_arg_slot_index(args, &mut slot, ArgKind::Brace), None);
1291
1292        let frac = &builtin().command("frac").unwrap().args;
1293        let mut slot = 0;
1294        assert_eq!(
1295            match_arg_slot_index(frac, &mut slot, ArgKind::Bracket),
1296            None
1297        );
1298        assert_eq!(slot, 0);
1299        assert_eq!(
1300            match_arg_slot_index(frac, &mut slot, ArgKind::Brace),
1301            Some(0)
1302        );
1303
1304        let optional_brace_then_required_bracket = crate::semantic::xparse::parse_spec("d{} r[]");
1305        let mut slot = 0;
1306        assert_eq!(
1307            match_arg_slot_index(
1308                &optional_brace_then_required_bracket,
1309                &mut slot,
1310                ArgKind::Bracket,
1311            ),
1312            Some(1)
1313        );
1314
1315        let required_bracket_then_brace = crate::semantic::xparse::parse_spec("r[] m");
1316        let mut slot = 0;
1317        assert_eq!(
1318            match_arg_slot_index(&required_bracket_then_brace, &mut slot, ArgKind::Brace),
1319            None
1320        );
1321        assert_eq!(slot, 0);
1322        assert_eq!(
1323            match_arg_slot_index(&required_bracket_then_brace, &mut slot, ArgKind::Bracket),
1324            Some(0)
1325        );
1326    }
1327
1328    #[test]
1329    fn bundled_prose_args_flagged() {
1330        for name in builtin().command_names() {
1331            for argument in builtin().command(name).unwrap().args.iter() {
1332                if argument.content == ContentKind::Prose {
1333                    assert_eq!(argument.domain, ArgumentDomain::Text, "\\{name}");
1334                }
1335            }
1336        }
1337        let footnote = &builtin().command("footnote").unwrap().args;
1338        assert!(footnote.iter().any(|a| a.content == ContentKind::Prose));
1339        let section = &builtin().command("section").unwrap().args;
1340        assert!(
1341            section
1342                .iter()
1343                .all(|argument| argument.domain == ArgumentDomain::Text)
1344        );
1345        let label = &builtin().command("label").unwrap().args;
1346        assert!(label.iter().all(|a| a.content == ContentKind::Opaque));
1347    }
1348
1349    #[test]
1350    fn environment_argument_shapes() {
1351        let db = builtin();
1352        let tabular = db.environment("tabular").unwrap();
1353        assert_eq!(tabular.args.len(), 2);
1354        assert_eq!(tabular.args[0].kind, ArgKind::Bracket); // [pos]
1355        assert_eq!(tabular.args[1].kind, ArgKind::Brace); // {cols}
1356        assert!(db.environment("verbatim").unwrap().args.is_empty());
1357    }
1358
1359    #[test]
1360    fn environment_derived_flags_follow_source_mutation() {
1361        let mut sig = EnvironmentSig::from(RawEnvironment::default());
1362        assert!(sig.reflow());
1363        assert!(!sig.block());
1364
1365        sig.verbatim_body = true;
1366        assert!(!sig.reflow());
1367
1368        sig.block_explicit = true;
1369        assert!(sig.block());
1370        sig.block_explicit = false;
1371
1372        sig.math = true;
1373        assert!(sig.block());
1374    }
1375
1376    #[test]
1377    fn environment_flags_and_derived_reflow() {
1378        let db = builtin();
1379        let lstlisting = db.environment("lstlisting").unwrap();
1380        assert!(lstlisting.verbatim_body);
1381        assert!(!lstlisting.reflow());
1382        let equation = db.environment("equation").unwrap();
1383        assert!(equation.math);
1384        assert!(!equation.reflow());
1385        assert!(!equation.align);
1386        let align = db.environment("align").unwrap();
1387        assert!(align.math);
1388        assert!(align.align);
1389        let pmatrix = db.environment("pmatrix").unwrap();
1390        assert!(pmatrix.math);
1391        assert!(pmatrix.align);
1392        let tabular = db.environment("tabular").unwrap();
1393        assert!(!tabular.verbatim_body);
1394        assert!(!tabular.math);
1395        assert!(tabular.align);
1396        assert!(!tabular.list);
1397        for name in ["itemize", "enumerate", "description"] {
1398            let env = db.environment(name).unwrap();
1399            assert!(env.list, "{name} should be a list environment");
1400            assert!(env.reflow());
1401            assert!(!env.math);
1402        }
1403        for name in [
1404            "Code",
1405            "CodeInput",
1406            "CodeOutput",
1407            "Sinput",
1408            "Soutput",
1409            "Scode",
1410        ] {
1411            let env = db.environment(name).unwrap();
1412            assert!(env.verbatim_body, "{name} should be a verbatim environment");
1413            assert!(!env.reflow());
1414        }
1415    }
1416
1417    #[test]
1418    fn externally_defined_verbatim_environments() {
1419        let db = builtin();
1420        for name in ["filecontents", "filecontents*"] {
1421            let env = db.environment(name).unwrap();
1422            assert!(env.verbatim_body, "{name} body is written verbatim");
1423            assert!(!env.reflow());
1424            assert_eq!(env.args.len(), 2, "{name} arity");
1425            assert_eq!(env.args[0].kind, ArgKind::Bracket);
1426            assert_eq!(env.args[1].kind, ArgKind::Brace);
1427        }
1428        for name in ["ltxcode", "ltxexample"] {
1429            let env = db.environment(name).unwrap();
1430            assert!(env.verbatim_body, "{name} body is opaque");
1431            assert!(!env.reflow());
1432            assert_eq!(env.args.len(), 1, "{name} arity");
1433            assert_eq!(env.args[0].kind, ArgKind::Bracket);
1434        }
1435    }
1436
1437    #[test]
1438    fn block_flag_is_explicit_or_derived() {
1439        let db = builtin();
1440        assert!(db.environment("figure").unwrap().block());
1441        assert!(db.environment("center").unwrap().block());
1442        assert!(db.environment("verbatim").unwrap().block());
1443        assert!(db.environment("equation").unwrap().block());
1444        assert!(db.environment("itemize").unwrap().block());
1445        assert!(db.environment("document").unwrap().block());
1446        assert!(db.environment("center").unwrap().reflow());
1447    }
1448
1449    #[test]
1450    fn doc_ltxdoc_signatures() {
1451        let db = builtin();
1452        for name in ["DocInput", "DescribeMacro", "DescribeEnv", "StopEventually"] {
1453            let cmd = db
1454                .command(name)
1455                .unwrap_or_else(|| panic!("{name} signature"));
1456            assert_eq!(cmd.args.len(), 1, "{name} arity");
1457            assert!(cmd.args[0].required, "{name} arg is mandatory");
1458        }
1459        for name in ["macro", "environment"] {
1460            let env = db.environment(name).unwrap_or_else(|| panic!("{name} env"));
1461            assert_eq!(env.args.len(), 1, "{name} arity");
1462            assert!(env.block(), "{name} is a block env");
1463            assert!(env.reflow(), "{name} body reflows as prose");
1464            assert!(!env.code, "{name} is not a code env");
1465        }
1466        for name in ["macrocode", "macrocode*"] {
1467            let env = db.environment(name).unwrap_or_else(|| panic!("{name} env"));
1468            assert!(env.code, "{name} is code");
1469            assert!(!env.reflow(), "{name} never reflows");
1470            assert!(!env.verbatim_body, "{name} body is parsed, not verbatim");
1471            assert!(env.block(), "{name} is a block env");
1472        }
1473    }
1474
1475    #[test]
1476    fn code_flag_parses_and_drives_reflow() {
1477        let db = parse(
1478            r#"{ "environments": {
1479                "plain": {},
1480                "codeish": { "code": true }
1481            } }"#,
1482        )
1483        .expect("valid code schema");
1484        let plain = db.environment("plain").unwrap();
1485        assert!(!plain.code);
1486        assert!(plain.reflow());
1487        let codeish = db.environment("codeish").unwrap();
1488        assert!(codeish.code);
1489        assert!(!codeish.reflow());
1490        assert!(!codeish.verbatim_body);
1491    }
1492
1493    #[test]
1494    fn statement_body_flag_parses_and_drives_reflow() {
1495        let db = parse(
1496            r#"{ "environments": {
1497                "plain": {},
1498                "stmt": { "statementBody": true }
1499            } }"#,
1500        )
1501        .expect("valid statementBody schema");
1502        let plain = db.environment("plain").unwrap();
1503        assert!(!plain.statement_body);
1504        assert!(plain.reflow());
1505        let stmt = db.environment("stmt").unwrap();
1506        assert!(stmt.statement_body);
1507        assert!(!stmt.reflow());
1508        assert!(!stmt.code);
1509        assert!(!stmt.verbatim_body);
1510    }
1511
1512    #[test]
1513    fn label_key_flag_is_curated_and_defaults_false() {
1514        let db = parse(
1515            r#"{
1516              "environments": {
1517                "plain": {},
1518                "labels": { "labelKey": true }
1519              }
1520            }"#,
1521        )
1522        .expect("valid labelKey schema");
1523        assert!(!db.environment("plain").unwrap().label_key);
1524        assert!(db.environment("labels").unwrap().label_key);
1525
1526        assert!(builtin().environment("frame").unwrap().label_key);
1527        assert!(builtin().environment("lstlisting").unwrap().label_key);
1528        assert!(!builtin().environment("tikzpicture").unwrap().label_key);
1529    }
1530
1531    #[test]
1532    fn picture_environments_are_statement_bodies() {
1533        let db = builtin();
1534        for name in [
1535            "tikzpicture",
1536            "pgfpicture",
1537            "scope",
1538            "pgfonlayer",
1539            "axis",
1540            "loglogaxis",
1541            "semilogxaxis",
1542            "semilogyaxis",
1543            "groupplot",
1544            "polaraxis",
1545            "ternaryaxis",
1546        ] {
1547            let env = db.environment(name).unwrap_or_else(|| panic!("{name} env"));
1548            assert!(env.statement_body, "{name} holds statements, not prose");
1549            assert!(!env.reflow(), "{name} never reflows as prose");
1550            assert!(!env.code, "{name} is not `.dtx` macrocode");
1551            assert!(!env.verbatim_body, "{name} body is parsed, not verbatim");
1552            assert!(env.block(), "{name} is a block env");
1553        }
1554        for name in [
1555            "tikzpicture",
1556            "scope",
1557            "axis",
1558            "loglogaxis",
1559            "semilogxaxis",
1560            "semilogyaxis",
1561            "groupplot",
1562            "polaraxis",
1563            "ternaryaxis",
1564        ] {
1565            let env = db.environment(name).unwrap();
1566            assert_eq!(env.args.len(), 1, "{name} takes an option bracket");
1567            assert!(!env.args[0].required, "{name} option is optional");
1568            assert_eq!(env.args[0].content, ContentKind::Keyval, "{name} keyval");
1569        }
1570        assert_eq!(db.environment("pgfonlayer").unwrap().args.len(), 1);
1571        assert!(db.environment("pgfonlayer").unwrap().args[0].required);
1572        assert!(db.environment("pgfpicture").unwrap().args.is_empty());
1573    }
1574
1575    #[test]
1576    fn unknown_names_resolve_to_none() {
1577        let db = builtin();
1578        assert!(db.command("definitelynotacommand").is_none());
1579        assert!(db.environment("definitelynotanenv").is_none());
1580    }
1581
1582    #[test]
1583    fn rejects_unknown_fields() {
1584        let err = parse(r#"{ "commands": { "x": { "sektioning": 2 } } }"#);
1585        assert!(err.is_err());
1586    }
1587
1588    #[test]
1589    fn empty_document_is_valid() {
1590        let db = parse("{}").expect("empty object is valid");
1591        assert!(db.command("anything").is_none());
1592    }
1593
1594    #[test]
1595    fn cwl_tier_loads_and_covers_long_tail() {
1596        let db = cwl();
1597        assert!(db.command("siunitx").is_some() || db.command("SI").is_some());
1598        assert!(
1599            db.command_names().count() > 1000,
1600            "the CWL subset should contribute a broad name set"
1601        );
1602    }
1603
1604    #[test]
1605    fn cwl_entries_carry_only_arity_no_behavior_flags() {
1606        let db = cwl();
1607        for sig in db.command_sigs() {
1608            assert!(sig.sectioning.is_none());
1609            assert!(!sig.verbatim && !sig.rule && !sig.inline && !sig.block);
1610            assert!(sig.args.iter().all(|a| match a.content {
1611                ContentKind::Opaque => true,
1612                ContentKind::Keyval => !a.required,
1613                _ => false,
1614            }));
1615        }
1616        for sig in db.environment_sigs() {
1617            assert!(!sig.verbatim_body && !sig.math && !sig.code && !sig.align);
1618            assert!(!sig.no_indent && !sig.list && !sig.block());
1619            assert!(sig.outline.is_none());
1620            assert!(sig.args.iter().all(|a| match a.content {
1621                ContentKind::Opaque => true,
1622                ContentKind::Keyval => !a.required,
1623                _ => false,
1624            }));
1625        }
1626    }
1627
1628    #[test]
1629    fn curated_builtin_wins_over_cwl_tier() {
1630        let empty = SignatureDb::default();
1631        let sigs = Signatures::new(&empty);
1632        assert!(
1633            cwl().command("section").is_some(),
1634            "test premise: in CWL tier"
1635        );
1636        assert_eq!(sigs.command("section").unwrap().sectioning, Some(2));
1637    }
1638
1639    #[test]
1640    fn cwl_only_name_resolves_through_signatures() {
1641        let empty = SignatureDb::default();
1642        let sigs = Signatures::new(&empty);
1643        let Some(name) = cwl()
1644            .command_names()
1645            .find(|n| builtin().command(n).is_none())
1646        else {
1647            panic!("expected at least one CWL-only command name");
1648        };
1649        let sig = sigs.command(name).expect("CWL-only name resolves");
1650        assert!(sig.sectioning.is_none() && !sig.inline && !sig.verbatim && !sig.block);
1651    }
1652
1653    fn db_with_command(name: &str) -> SignatureDb {
1654        let mut db = SignatureDb::default();
1655        db.insert_command(name, CommandSig::default());
1656        db
1657    }
1658
1659    #[test]
1660    fn merge_with_package_origin_records_origin() {
1661        let mut scope = SignatureDb::default();
1662        scope.merge_from(&db_with_command("myfoo"), Some("mypkg"));
1663        assert_eq!(scope.command_origin("myfoo"), Some("mypkg"));
1664        assert!(scope.command("myfoo").is_some());
1665    }
1666
1667    #[test]
1668    fn plain_merge_clears_origin_on_shadow() {
1669        let mut scope = SignatureDb::default();
1670        scope.merge_from(&db_with_command("dup"), Some("mypkg"));
1671        scope.merge_from(&db_with_command("dup"), None);
1672        assert_eq!(scope.command_origin("dup"), None);
1673        assert!(scope.command("dup").is_some());
1674    }
1675
1676    #[test]
1677    fn later_package_merge_overwrites_origin() {
1678        let mut scope = SignatureDb::default();
1679        scope.merge_from(&db_with_command("shared"), Some("first"));
1680        scope.merge_from(&db_with_command("shared"), Some("second"));
1681        assert_eq!(scope.command_origin("shared"), Some("second"));
1682    }
1683
1684    #[test]
1685    fn insert_clears_origin() {
1686        let mut scope = SignatureDb::default();
1687        scope.merge_from(&db_with_command("myfoo"), Some("mypkg"));
1688        scope.insert_command("myfoo", CommandSig::default());
1689        assert_eq!(scope.command_origin("myfoo"), None);
1690    }
1691
1692    #[test]
1693    fn merge_propagates_existing_origins() {
1694        let mut inner = SignatureDb::default();
1695        inner.merge_from(&db_with_command("dep"), Some("deppkg"));
1696        let mut scope = SignatureDb::default();
1697        scope.merge_from(&inner, None);
1698        assert_eq!(scope.command_origin("dep"), Some("deppkg"));
1699    }
1700}