Skip to main content

badness_parser/parser/
core.rs

1//! The parser entry point and its output type.
2//!
3//! `parse` runs the pipeline: [`lex`](crate::parser::lex) → [`grammar::parse`] (the recursive
4//! descent, which emits events + errors) → [`build_tree`] (the green tree).
5//! Syntax errors ride a side channel and never abort the parse.
6
7use std::collections::HashMap;
8
9use rowan::GreenNode;
10use smol_str::SmolStr;
11
12use crate::declarations::ResolvedDeclarations;
13use crate::parser::grammar;
14use crate::parser::lexer::{LatexFlavor, LexConfig, ParseCtx, lex_with, lex_with_implicit_expl};
15use crate::parser::tree_builder::build_tree;
16use crate::semantic::define::scan_definitions;
17use crate::semantic::signature::builtin;
18use crate::syntax::SyntaxNode;
19
20/// A green tree and the syntax errors gathered while parsing it.
21#[derive(Debug, Clone)]
22pub struct Parse {
23    pub green: GreenNode,
24    pub errors: Vec<SyntaxError>,
25}
26
27impl Parse {
28    /// Returns a red-tree cursor over the parsed document.
29    pub fn syntax(&self) -> SyntaxNode {
30        SyntaxNode::new_root(self.green.clone())
31    }
32}
33
34/// A syntax error, carried on a side channel keyed by byte range.
35#[derive(Debug, Clone, PartialEq, Eq)]
36pub struct SyntaxError {
37    pub message: String,
38    pub start: usize,
39    pub end: usize,
40}
41
42/// Parse LaTeX source into a lossless CST.
43///
44/// A bounded two-pass parse handles user-defined verbatim-argument commands
45/// (`\newcommand`/xparse definitions that other a special char's catcode — see
46/// [`crate::semantic::define`]): the lexer needs to know such commands *before* it
47/// tokenizes their call sites, but they are only discoverable from the parsed tree.
48/// So pass 1 parses with built-in verbatim knowledge only, scans the result for
49/// catcode-verbatim definitions, and — *only* when it finds any — pass 2 re-parses
50/// with those commands fed into the lexer so their arguments become opaque `VERB`
51/// tokens. Two passes is a conservative bound: a definition visible
52/// only after the second pass's re-tokenization is a tolerated false negative. The
53/// common case is a single parse.
54pub fn parse(input: &str) -> Parse {
55    parse_with_flavor(input, LatexFlavor::Document)
56}
57
58/// Parse LaTeX source into a lossless CST under an explicit [`LexConfig`].
59///
60/// Identical to [`parse`] but fixes the lexer's initial catcode regime (a
61/// [`Package`](LatexFlavor::Package) flavor — `.sty`/`.cls` — starts with `@` as a
62/// letter) and whether to run the `.dtx` docstrip mode. A bare [`LatexFlavor`]
63/// coerces in, so most callers pass one directly; [`parse`] is the
64/// [`Document`](LatexFlavor::Document) wrapper.
65pub fn parse_with_flavor(input: &str, config: impl Into<LexConfig>) -> Parse {
66    parse_with_declarations(input, config, &ResolvedDeclarations::default())
67}
68
69/// Parse LaTeX source under an explicit [`LexConfig`] *and* a project's
70/// [declarations](crate::declarations) — the one input to the tree that is not
71/// the text (`AGENTS.md` decision #12).
72///
73/// The declarations are applied to **pass 1**, so a declaring project pays no
74/// extra parse: they are known before a byte is lexed, unlike the file's own
75/// definitions, which are what the two-pass scan exists to discover. The second
76/// pass is then decided by asking whether the *scan* contributed anything the
77/// declarations did not already say — not by asking whether the context is
78/// empty, which a seeded context never is.
79///
80/// [`ResolvedDeclarations`] rather than a bare `SignatureDb`: this is the only
81/// signature data the parser accepts, and a type that can only come from a
82/// declaration block is what keeps a document's merged scope (package scans,
83/// scanned definitions, the CWL tier) from reaching the tree.
84pub fn parse_with_declarations(
85    input: &str,
86    config: impl Into<LexConfig>,
87    declared: &ResolvedDeclarations,
88) -> Parse {
89    parse_with_declarations_resolved(input, config, declared).0
90}
91
92/// [`parse_with_declarations`], additionally handing back the [`ParseCtx`] the
93/// returned tree was parsed under.
94///
95/// The context is not a second output so much as a *witness*: an incremental
96/// reparse that relexes a fragment of this text must do so under the same context,
97/// or the fragment's tokens are not the ones the tree holds — a `\newcommand` the
98/// scan found makes its call sites lex differently, and a relex under a default
99/// context would silently disagree. It is free to hand back, since both passes
100/// compute it anyway (the one-pass case returns the seed it compared equal to).
101///
102/// The plain [`parse_with_declarations`] stays the entry point for everyone who
103/// only wants a tree.
104pub fn parse_with_declarations_resolved(
105    input: &str,
106    config: impl Into<LexConfig>,
107    declared: &ResolvedDeclarations,
108) -> (Parse, ParseCtx) {
109    let config = config.into();
110    let mut seed = ParseCtx::default();
111    seed.overlay_declarations(declared);
112
113    let pass1 = parse_with(input, &seed, config);
114    let mut ctx = parse_ctx(&pass1.syntax());
115    // Declared wins over scanned, so the overlay is applied *after* the scan.
116    ctx.overlay_declarations(declared);
117    if ctx == seed {
118        return (pass1, ctx);
119    }
120    let pass2 = parse_with(input, &ctx, config);
121    (pass2, ctx)
122}
123
124/// Run the lex → grammar → tree-build pipeline once with a fixed scan context.
125fn parse_with(input: &str, ctx: &ParseCtx, config: LexConfig) -> Parse {
126    let tokens = lex_with(input, ctx, config);
127    let (events, errors) = grammar::parse(&tokens, ctx);
128    let green = build_tree(&tokens, &events);
129    Parse { green, errors }
130}
131
132/// Parse a root fragment under the exact file-level context of an existing parse.
133///
134/// Unlike [`parse_with_declarations_resolved`], this does not rescan definitions
135/// from the fragment. Incremental tiers need the full file's context to remain the
136/// authority, including the full file's one-shot `.dtx` implicit-expl signal.
137pub(crate) fn parse_fragment_with_ctx(
138    input: &str,
139    ctx: &ParseCtx,
140    config: LexConfig,
141    implicit_expl: bool,
142) -> Parse {
143    let tokens = lex_with_implicit_expl(input, ctx, config, implicit_expl);
144    let (events, errors) = grammar::parse(&tokens, ctx);
145    let green = build_tree(&tokens, &events);
146    Parse { green, errors }
147}
148
149/// Scan `root` for user definitions and collect the facts pass 2 needs into a
150/// [`ParseCtx`]. Each scanned signature's verbatim flag is already resolved
151/// (`scan_definitions`); a command's `args` hold its leading, non-verbatim
152/// arguments and an environment's `args` its (all leading) arguments — the exact
153/// shapes the lexer needs.
154///
155/// The inverse case also feeds the context: a command the file redefines *non-verbatim*
156/// whose name collides with a built-in braced-verbatim command (`\code`, `\url`, …) is
157/// recorded as *suppressed*, so the local definition shadows the built-in and pass 2
158/// lexes `\code{…}` as an ordinary group (follow-up to issue #53).
159///
160/// Environment aliases (issue #109) are projected the same way, but only when the
161/// alias is *called* somewhere: a `.sty` that defines `\bea`/`\eea` for its users
162/// and never uses them must not pay a second parse for nothing. The occurrence
163/// count is a sound one-sided filter — a definition always contributes at least one
164/// `COMMAND` node, so a called alias always has two or more, and the worst a
165/// `\renewcommand` can do is admit an unused alias (one wasted pass, never a missed
166/// pairing).
167fn parse_ctx(root: &SyntaxNode) -> ParseCtx {
168    let db = scan_definitions(root);
169    let mut ctx = ParseCtx::default();
170    for name in db.command_names() {
171        match db.command(name) {
172            Some(sig) if sig.verbatim => ctx.insert(SmolStr::new(name), sig.args.to_vec()),
173            // Redefined non-verbatim but shadowing a built-in verbatim command: suppress
174            // the built-in capture.
175            Some(_) if builtin().command(name).is_some_and(|sig| sig.verbatim) => {
176                ctx.suppress(SmolStr::new(name));
177            }
178            _ => {}
179        }
180    }
181    for name in db.environment_names() {
182        if let Some(sig) = db.environment(name).filter(|sig| sig.verbatim_body) {
183            ctx.insert_environment(SmolStr::new(name), sig.args.to_vec());
184        }
185    }
186    // Gated on there being any alias at all: this is an extra tree walk, and the
187    // overwhelmingly common case is a file with no aliases, which must not pay for
188    // the feature.
189    if db.env_begin_aliases().next().is_some() || db.env_end_aliases().next().is_some() {
190        let called = command_call_counts(root);
191        let is_called = |name: &str| called.get(name).is_some_and(|n| *n >= 2);
192        for (name, target) in db.env_begin_aliases() {
193            if is_called(name) {
194                ctx.insert_begin_alias(SmolStr::new(name), SmolStr::new(target));
195            }
196        }
197        // No "its target must have a live opener" filter: since issue #117 the
198        // literal `\begin{X}` is an opener spelling too, so a closer alias whose
199        // partner is never defined still pairs. The `is_called` filter alone
200        // carries what that one was for — keeping an alias no call site uses from
201        // buying the file a second parse.
202        for (name, target) in db.env_end_aliases() {
203            if is_called(name) {
204                ctx.insert_end_alias(SmolStr::new(name), SmolStr::new(target));
205            }
206        }
207    }
208    ctx
209}
210
211/// How many `COMMAND` nodes name each control word in `root`. Used only for the
212/// alias "is it called anywhere" filter above, so it counts occurrences rather
213/// than distinguishing definitions from calls — see [`parse_ctx`] for why that
214/// one-sided approximation is sound.
215fn command_call_counts(root: &SyntaxNode) -> HashMap<SmolStr, usize> {
216    let mut counts: HashMap<SmolStr, usize> = HashMap::new();
217    for node in root
218        .descendants()
219        .filter(|n| n.kind() == crate::syntax::SyntaxKind::COMMAND)
220    {
221        if let Some(name) = crate::ast::command_name(&node) {
222            *counts.entry(SmolStr::new(name)).or_default() += 1;
223        }
224    }
225    counts
226}
227
228/// Parse `input` and render the CST back to source. By the losslessness
229/// invariant this always equals `input`.
230pub fn reconstruct(input: &str) -> String {
231    parse(input).syntax().to_string()
232}
233
234#[cfg(test)]
235mod tests {
236    use super::*;
237
238    #[test]
239    fn reconstruct_is_identity() {
240        let input = "\\section{Hi}\n\nbody $x^2$ % c\n";
241        assert_eq!(reconstruct(input), input);
242    }
243
244    /// The resolved context is the one the *returned* tree was parsed under, which
245    /// for a two-pass file is the scanned one, not the seed. An incremental reparse
246    /// relexes fragments under it, so handing back the seed here would relex a
247    /// `\shellcmd{…}` call site as an ordinary group and disagree with the tree.
248    #[test]
249    fn the_resolved_context_carries_the_second_pass_scan() {
250        let input = "\\newcommand\\shellcmd[1]{\\@makeother\\$#1}\n\\shellcmd{a_$b$}\n";
251        let (parse, ctx) =
252            parse_with_declarations_resolved(input, LatexFlavor::Document, &Default::default());
253
254        assert_ne!(
255            ctx,
256            ParseCtx::default(),
257            "the scan found a verbatim definition, so the context must not be the seed"
258        );
259        // The witness property: relexing the whole input under the resolved context
260        // reproduces the token run the tree holds. Under the seed it would not — the
261        // call site would lex as an ordinary group rather than a `VERB`.
262        let relexed: String = lex_with(input, &ctx, LatexFlavor::Document.into())
263            .iter()
264            .map(|t| t.text.as_str())
265            .collect();
266        assert_eq!(relexed, parse.syntax().to_string());
267        assert!(
268            parse.syntax().to_string().contains("a_$b$"),
269            "the call-site argument should be captured whole"
270        );
271    }
272
273    /// The one-pass case still hands back a usable witness rather than nothing: the
274    /// seed and the scan compared equal, so either is the context the tree was
275    /// parsed under.
276    #[test]
277    fn the_resolved_context_is_the_seed_when_no_scan_contributes() {
278        let input = "\\section{Hi}\n\nplain prose\n";
279        let (_, ctx) =
280            parse_with_declarations_resolved(input, LatexFlavor::Document, &Default::default());
281        assert_eq!(ctx, ParseCtx::default());
282    }
283
284    #[test]
285    fn command_wraps_its_argument_group() {
286        use crate::syntax::SyntaxKind;
287        let parse = parse(r"\a{b}");
288        let command = parse
289            .syntax()
290            .descendants()
291            .find(|n| n.kind() == SyntaxKind::COMMAND)
292            .expect("a COMMAND node");
293        assert!(
294            command.children().any(|n| n.kind() == SyntaxKind::GROUP),
295            "the argument should be a nested GROUP node"
296        );
297        assert!(parse.errors.is_empty());
298    }
299
300    /// A named math environment (`equation`, flagged `math` in the built-in DB)
301    /// parses its body in math mode: a `MATH` node whose scripts become `SCRIPTED`,
302    /// exactly as `\[…\]`. Previously the body was a prose `PARAGRAPH` of loose
303    /// tokens.
304    #[test]
305    fn math_environment_body_is_a_math_node() {
306        use crate::syntax::SyntaxKind;
307        let input = "\\begin{equation}\n  x_i^2 = y\n\\end{equation}\n";
308        let root = parse(input).syntax();
309        let math = root
310            .descendants()
311            .find(|n| n.kind() == SyntaxKind::MATH)
312            .expect("the equation body is wrapped in a MATH node");
313        assert!(
314            math.descendants().any(|n| n.kind() == SyntaxKind::SCRIPTED),
315            "scripts inside the math environment build SCRIPTED nodes"
316        );
317        assert!(
318            !root
319                .descendants()
320                .any(|n| n.kind() == SyntaxKind::PARAGRAPH),
321            "the body is math, not a prose PARAGRAPH"
322        );
323        assert_eq!(reconstruct(input), input);
324    }
325
326    /// An alignment math environment keeps its `&` columns and `\\` rows as
327    /// `AMPERSAND` / `LINE_BREAK` inside the `MATH` node, so the formatter's grid
328    /// builder still sees them.
329    #[test]
330    fn align_environment_keeps_grid_tokens_inside_math() {
331        use crate::syntax::SyntaxKind;
332        let input = "\\begin{align}\n  a &= b \\\\\n  c &= d\n\\end{align}\n";
333        let root = parse(input).syntax();
334        let math = root
335            .descendants()
336            .find(|n| n.kind() == SyntaxKind::MATH)
337            .expect("the align body is wrapped in a MATH node");
338        assert!(
339            math.children_with_tokens()
340                .any(|e| e.kind() == SyntaxKind::AMPERSAND),
341            "top-level `&` stays a direct MATH child"
342        );
343        assert!(
344            math.children().any(|n| n.kind() == SyntaxKind::LINE_BREAK),
345            "top-level `\\\\` stays a LINE_BREAK child of MATH"
346        );
347        assert_eq!(reconstruct(input), input);
348    }
349
350    /// A non-math environment (`itemize`, not flagged `math`) is unchanged: its body
351    /// stays a prose block with no `MATH` node.
352    #[test]
353    fn non_math_environment_body_is_unchanged() {
354        use crate::syntax::SyntaxKind;
355        let input = "\\begin{itemize}\n  \\item a\n\\end{itemize}\n";
356        let root = parse(input).syntax();
357        assert!(
358            !root.descendants().any(|n| n.kind() == SyntaxKind::MATH),
359            "a text environment never enters math mode"
360        );
361        assert_eq!(reconstruct(input), input);
362    }
363
364    /// An unclosed math environment recovers at EOF (the `MATH` body ends, the
365    /// `ENVIRONMENT` closes) rather than looping or corrupting; losslessness holds.
366    #[test]
367    fn unclosed_math_environment_recovers() {
368        use crate::syntax::SyntaxKind;
369        let input = "\\begin{equation}\n  a = b\n";
370        let parse = parse(input);
371        assert!(
372            parse
373                .syntax()
374                .descendants()
375                .any(|n| n.kind() == SyntaxKind::MATH),
376            "the body still parses as math"
377        );
378        assert!(!parse.errors.is_empty(), "an unclosed environment reports");
379        assert_eq!(reconstruct(input), input);
380    }
381}