techy 0.1.2

A fast, extensible LaTeX parser for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//! A mandatory group argument whose contents are read as plain characters:
//! [`CharsGroupArgumentParser`].
//!
//! It accepts a group of a configured class — `{…}` for the latexlike content class —
//! and parses that group's contents under a restricted state in which commands and
//! specials are off, so `\input{my_file.tex}` keeps its underscore and
//! `\input{\jobname.tex}` yields the literal characters `\jobname.tex`. The group's
//! children are the argument's content and the delimiters are argument syntax, exactly as
//! in [`GroupArgumentParser`](super::GroupArgumentParser)'s class form. pylatexenc calls
//! this parser `LatexCharsGroupParser`.
//!
//! No latexlike argument code selects it; attach it to an [`ArgumentSpec`] yourself. The
//! preset uses it for the file-name argument of its `\input`-style macros.
//!
//! It is distinct from [`read_rigid_name_group`](super::read_rigid_name_group), which
//! reads an environment name and returns it as a value without recording any node; this
//! parser stages nodes like any other argument parser.
//!
//! # When the group is not there
//!
//! The argument is mandatory and has **no** single-expression fallback: where no group of
//! the configured class opens,
//! [`MissingMandatoryArgument`](super::MissingMandatoryArgument) is recorded under
//! tolerant recovery, or the parse aborts under strict recovery, and the argument is
//! reported absent with nothing consumed. `\input a` reports a missing mandatory
//! argument rather than taking `a`.
//!
//! Whitespace and comments ahead of the `{` are scanned under the argument's own state,
//! not the restricted one — the restriction covers the group's interior only. That is why
//! this is a parser rather than a plain state delta on the argument: an
//! [`ArgumentSpec::parsing_state_delta`] would cover the probe as well.
//!
//! # The restricted contents state
//!
//! Inside the group, commands and specials are off, so `\foo` and `~` read as ordinary
//! characters. Two settings adjust the rest:
//!
//! - comments ([`with_comments`](CharsGroupArgumentParser::with_comments), default on);
//! - nested groups ([`with_nested_groups`](CharsGroupArgumentParser::with_nested_groups),
//!   default on).
//!
//! Together these are pylatexenc's `enable_macros=False, enable_specials=False,
//! enable_math=False` recipe. The core has no math gate, so "math off" follows from the
//! group rules instead: with nested groups on, the contents keep only those of the base
//! state's group rules that belong to the class entered. The latexlike `{…}` content
//! class therefore keeps `{}`, while the math delimiter pairs — another class — drop away
//! and `$` reads as a plain character.
//!
//! With nested groups off, the groups feature is disabled outright and interior `{` and
//! `}` become plain characters. The *outer* close still ends the group, because the
//! expected close delimiter is recognized whether or not groups are enabled, so the first
//! close of the entered pairing ends the group, as in pylatexenc.
//!
//! # Nested groups and the descent policy
//!
//! By default a nested group's interior restores the outer, unrestricted state — the
//! pylatexenc behavior, wanted for shapes like `\cite{manual:{… \emph{Title} …}}` where
//! the first level is characters only but a braced value regains full parsing. The
//! one-level-deep [`ChildStateSpec`] carries that revert, and deeper levels inherit the
//! outer state.
//! [`with_restricted_descent`](CharsGroupArgumentParser::with_restricted_descent) keeps
//! the restriction at every depth instead, so nested groups stay characters only.

use alloc::sync::Arc;
use core::fmt;

use crate::node::{ArgumentExt, ContentNodes};
use crate::spec::{ArgumentParser, ArgumentSpec, ParsedArgumentNodes};
use crate::state::{
    CommandOverrides, CommentOverrides, FeaturePresence, Lang, LangFeatures,
    ParsingStateDelta, SpecialsOverrides, TokenRulesOverrides,
};
use crate::token::{TokenEdge, TokenKind};

use super::argument_parsers::{
    missing_mandatory, scan_argument_noise, stage_pre_space, staged_child_count,
};
use super::child_state::{ChildStateSpec, GroupChildState, InvocationChildState};
use super::{ConstructParserResult, FromInvocation, ParseContext};

/// A mandatory `{…}` argument whose contents are read as plain characters, as in
/// `\label{sec:intro}` or `\input{my_file.tex}`.
///
/// The group must be of the class this parser was configured with. Its contents parse
/// under a restricted state: commands and specials are off, so `\foo` and `~` read as
/// ordinary characters, while comments and nested groups follow the settings below. The
/// group's children are the argument's content.
///
/// By default a nested group's interior restores the outer, unrestricted state;
/// [`with_restricted_descent`](CharsGroupArgumentParser::with_restricted_descent) keeps
/// the restriction at every depth.
///
/// # When the group is not there
///
/// The argument is mandatory and has no single-expression fallback. Where no group of the
/// configured class opens, [`MissingMandatoryArgument`](super::MissingMandatoryArgument)
/// is recorded under tolerant recovery, or the parse aborts under strict recovery, and
/// the argument is reported absent with nothing consumed.
pub struct CharsGroupArgumentParser<L: Lang> {
    group_type: L::GroupTypeId,
    comments: bool,
    nested_groups: bool,
    restricted_descent: bool,
}

impl<L: Lang> CharsGroupArgumentParser<L> {
    /// A characters-only argument delimited by any group rule of class `group_type`.
    ///
    /// The defaults are comments on, nested groups on, and nested group interiors
    /// restored to the outer, unrestricted state.
    pub fn new(group_type: L::GroupTypeId) -> CharsGroupArgumentParser<L> {
        CharsGroupArgumentParser {
            group_type,
            comments: true,
            nested_groups: true,
            restricted_descent: false,
        }
    }

    /// Sets whether comments stay recognized inside the group; on by default
    /// (pylatexenc's `enable_comments`).
    pub fn with_comments(mut self, comments: bool) -> Self {
        self.comments = comments;
        self
    }

    /// Sets whether nested groups of the entered class stay recognized inside the group;
    /// on by default (pylatexenc's `enable_groups`).
    ///
    /// With `false`, interior open and close delimiters read as plain characters. The
    /// outer close still ends the group — the expected close delimiter is recognized even
    /// with groups disabled — so the first close of the entered pairing ends it.
    pub fn with_nested_groups(mut self, nested_groups: bool) -> Self {
        self.nested_groups = nested_groups;
        self
    }

    /// Keeps the restriction in force inside nested groups; off by default.
    ///
    /// With the default, a nested group's interior restores the outer, unrestricted
    /// state, so a braced value inside a characters-only argument is parsed in full.
    pub fn with_restricted_descent(mut self, restricted_descent: bool) -> Self {
        self.restricted_descent = restricted_descent;
        self
    }

    /// The contents-restriction delta, built against `base` (the argument's state):
    /// commands/specials off, comments per setting, groups per setting — the group-rule
    /// list filtered to the entered class (the data-driven "math off"; module docs).
    fn contents_delta(
        &self,
        base: &crate::state::ParsingState<L>,
    ) -> ParsingStateDelta<L> {
        // Built through the store projections (`L` carries no feature bounds here):
        // a feature the language does not have needs no disabling — nothing exists
        // to recognize — and its override field is the zero-sized store.
        let mut rules = TokenRulesOverrides {
            commands: <L::Features as LangFeatures>::Commands::store_with(
                CommandOverrides::disable,
            ),
            specials: <L::Features as LangFeatures>::Specials::store_with(
                SpecialsOverrides::disable,
            ),
            comments: <L::Features as LangFeatures>::Comments::store_with(|| {
                CommentOverrides {
                    enabled: Some(self.comments),
                    ..CommentOverrides::default()
                }
            }),
            ..TokenRulesOverrides::default()
        };
        if let Some(groups) = <L::Features as LangFeatures>::Groups::store_get_mut::<
            crate::state::GroupOverrides<L>,
        >(&mut rules.groups)
        {
            if self.nested_groups {
                groups.rules = Some(
                    base.rules()
                        .group_rules()
                        .iter()
                        .filter(|rule| rule.group_type == self.group_type)
                        .cloned()
                        .collect(),
                );
            } else {
                groups.enabled = Some(false);
            }
        }
        ParsingStateDelta::new().rules(rules)
    }
}

impl<L: Lang> ArgumentParser<L> for CharsGroupArgumentParser<L>
where
    ArgumentExt<L>: Default,
    L::InvocationSyntax: FromInvocation<L>,
{
    fn parse_argument(
        &self,
        cx: &mut ParseContext<'_, '_, L>,
        spec: &ArgumentSpec<L>,
    ) -> ConstructParserResult<L, Option<ParsedArgumentNodes<L>>> {
        let mut noise = scan_argument_noise(cx)?;
        let open = match noise.next.clone() {
            Some(next) => match cx.tokens.token_kind(&next) {
                TokenKind::GroupOpen { rule, .. }
                    if rule.group_type == self.group_type =>
                {
                    Some((next.clone(), Arc::clone(rule)))
                }
                _ => None,
            },
            None => None,
        };
        let Some((open, rule)) = open else {
            return missing_mandatory(cx, noise, spec);
        };

        // The outer (unrestricted) state, kept for the default descent policy; the
        // restriction applies to the group's interior only.
        let outer = Arc::clone(&cx.state);
        let contents_state = cx.derive_state(&self.contents_delta(&outer))?;

        stage_pre_space(cx, &mut noise.nodes, &open)?;
        cx.tokens.move_to(&open, TokenEdge::EndPastPostSpace);
        let child_states = if self.restricted_descent {
            ChildStateSpec::inherit()
        } else {
            // Nested interiors revert to the outer state (one level deep; deeper
            // levels inherit the outer state naturally — module docs). Invocations
            // cannot arise at the restricted first level (commands are off).
            ChildStateSpec {
                group: GroupChildState::Fixed(outer),
                invocation: InvocationChildState::Inherit,
            }
        };
        let (id, _delta) =
            cx.parse_group(contents_state, &open, rule, child_states, None)?;

        // The id routes through the driver's group-parser factory: a bogus id from a
        // misbehaving custom driver degrades to a zero-child region rather than
        // panicking, and is diagnosed by `builder.add` when the region is staged
        // ([§dd-dr:panic-policy] staged-id rule — `staged_child_count`'s contract).
        let child_count = staged_child_count(cx, id);
        noise.nodes.push(id);
        Ok(Some(ParsedArgumentNodes::new(
            noise.nodes,
            ContentNodes::InChildrenOf(id, 0..child_count),
            Default::default(),
        )))
    }

    /// The argument is mandatory: absent is a diagnosed recovery, not a valid match.
    fn can_match_empty(&self) -> bool {
        false
    }
}

impl<L: Lang> fmt::Debug for CharsGroupArgumentParser<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("CharsGroupArgumentParser")
            .field("group_type", &self.group_type)
            .field("comments", &self.comments)
            .field("nested_groups", &self.nested_groups)
            .field("restricted_descent", &self.restricted_descent)
            .finish()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::Language;
    use crate::error::Recovery;
    use crate::latexlike::{
        argument_specs, CallableType, Latexlike, LatexlikeDriver, GroupType, MacroSpec,
    };
    use crate::extract::content_as_chars;
    use crate::node::{check_tree_invariants, NodeRef};
    use crate::scopes::Package;
    use crate::state::ParsingState;
    use alloc::vec;
    use alloc::vec::Vec;

    /// A language defining `\label` with the given chars-group parser as its one
    /// argument, plus `\emph{…}` for the nested-richness tests.
    fn language(parser: CharsGroupArgumentParser<Latexlike>, recovery: Recovery) -> Language<Latexlike> {
        let mut package = Package::new("chars-group-tests");
        package.insert(
            CallableType::Macro,
            "label",
            Arc::new(MacroSpec::new(vec![Arc::new(ArgumentSpec::new_unnamed(Arc::new(parser)))])),
        );
        package.insert(
            CallableType::Macro,
            "emph",
            Arc::new(MacroSpec::new(argument_specs(["m"]).unwrap())),
        );
        Language::new(
            LatexlikeDriver::new(recovery),
            ParsingState::lang_initial_with_packages([package]).expect("seed state"),
        )
        // Explicit guard: these inputs nest enough construct levels to trip the
        // unconfigured default's half-budget warning in debug builds.
        .with_descent_guard_init(crate::engine::StdDescentGuardInit::depth_limit(64))
    }

    fn parser() -> CharsGroupArgumentParser<Latexlike> {
        CharsGroupArgumentParser::new(GroupType::Content)
    }

    fn parse_ok(
        parser: CharsGroupArgumentParser<Latexlike>,
        input: &str,
    ) -> crate::engine::ParseResult<Latexlike> {
        let result = language(parser, Recovery::Strict).parse(input).unwrap();
        check_tree_invariants(&result.tree);
        assert!(
            result.diagnostics.is_empty(),
            "unexpected diagnostics: {:?}",
            result.diagnostics
        );
        result
    }

    fn label_node(result: &crate::engine::ParseResult<Latexlike>) -> NodeRef<'_, Latexlike> {
        let node = result.tree.root().child(0).expect("the label node");
        assert_eq!(node.macro_name(), Some("label"));
        node
    }

    #[test]
    fn contents_read_as_plain_characters() {
        // Commands, specials, and math delimiters are all inert inside — the exact
        // raw text is the content, and the strict parse stays clean.
        let result = parse_ok(parser(), r"\label{sec:in$t~o \emph x} rest");
        let label = label_node(&result);
        let content = label.argument_content_nodes(0).unwrap();
        assert_eq!(content_as_chars(content).unwrap(), r"sec:in$t~o \emph x");
        assert!(content.iter().all(|node| !node.is_callable()));
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" rest"));
    }

    #[test]
    fn nested_groups_restore_the_outer_state_by_default() {
        // The `\cite{key:value,manual:{…}}` shape: chars at the first level, full
        // parsing richness inside braced values (pylatexenc's descent behavior).
        let result = parse_ok(parser(), r"\label{manual:{a \emph{x} b}}");
        let label = label_node(&result);
        let content: Vec<_> = label.argument_content_nodes(0).unwrap().iter().collect();
        assert_eq!(content.len(), 2);
        assert_eq!(content[0].chars(), Some("manual:"));
        let braced = content[1];
        assert!(braced.is_group());
        let emph = braced.child(1).unwrap();
        assert!(emph.is_callable());
        assert_eq!(emph.macro_name(), Some("emph"));
    }

    #[test]
    fn restricted_descent_keeps_the_restriction_at_depth() {
        let result = parse_ok(
            parser().with_restricted_descent(true),
            r"\label{manual:{a \emph{x} b}}",
        );
        let label = label_node(&result);
        let braced = label.argument_content_nodes(0).unwrap().get(1).unwrap();
        assert!(braced.is_group());
        // `\emph` reads as characters; the nested `{x}` still groups (same class).
        assert!(braced.children().iter().all(|node| !node.is_callable()));
        assert!(braced.children().iter().any(|node| node.is_group()));
        assert_eq!(content_as_chars(braced.children()).unwrap(), r"a \emphx b");
    }

    #[test]
    fn nested_groups_off_ends_at_the_first_close() {
        // pylatexenc's `enable_groups=False` behavior: interior braces are plain
        // characters and the first close terminates the group.
        let result = parse_ok(parser().with_nested_groups(false), r"\label{a{b}");
        let label = label_node(&result);
        assert_eq!(
            content_as_chars(label.argument_content_nodes(0).unwrap()).unwrap(),
            "a{b"
        );
        assert_eq!(label.span().range(), 0..11);
    }

    #[test]
    fn comments_knob_gates_interior_comments() {
        // Default: `%` starts a comment inside (a node, skipped by chars flattening).
        let result = parse_ok(parser(), "\\label{a%c\nb}");
        let label = label_node(&result);
        let content = label.argument_content_nodes(0).unwrap();
        assert!(content.iter().any(|node| node.comment().is_some()));
        assert_eq!(content_as_chars(content).unwrap(), "ab");

        // Off: `%` is an ordinary character.
        let result = parse_ok(parser().with_comments(false), "\\label{a%c\nb}");
        let label = label_node(&result);
        let content = label.argument_content_nodes(0).unwrap();
        assert!(content.iter().all(|node| node.comment().is_none()));
        assert_eq!(content_as_chars(content).unwrap(), "a%c\nb");
    }

    #[test]
    fn leading_noise_scans_under_the_outer_state() {
        // The restriction scopes the interior only: a comment ahead of the `{` is
        // region noise even with interior comments off.
        let result = parse_ok(parser().with_comments(false), "\\label %n\n{x}");
        let label = label_node(&result);
        let region: Vec<_> = label.argument_nodes(0).unwrap().iter().collect();
        assert!(region.iter().any(|node| node.comment().is_some()));
        assert_eq!(
            content_as_chars(label.argument_content_nodes(0).unwrap()).unwrap(),
            "x"
        );
    }

    #[test]
    fn missing_group_is_diagnosed_with_nothing_consumed() {
        let err = language(parser(), Recovery::Strict).parse(r"\label x").unwrap_err();
        assert!(err.to_string().contains("missing mandatory argument"), "{err}");

        let result = language(parser(), Recovery::Tolerant).parse(r"\label x").unwrap();
        check_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1);
        let label = label_node(&result);
        assert!(!label.arguments().unwrap().get(0).unwrap().is_provided());
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("x"));
    }
}