techy 0.1.1

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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
//! [`EmbellishmentsArgumentParser`]: the embellishment-arguments parser
//! (pylatexenc's `LatexOptionalEmbellishmentArgsParser`, xparse's `e{<chars>}`
//! argument type, the preset's `e{…}` code).
//!
//! One argument position absorbing a run of *marker + expression* pairs: whenever one
//! of the configured markers (`^`, `_`, `'`, …) comes next, it must be followed —
//! at most plain whitespace apart — by one expression (a delimited group, a full
//! invocation, or a single char — the [`ExpressionParser`](super::ExpressionParser)
//! core), and the pair repeats until no marker matches. Each marker matches **at most
//! once** per invocation (xparse semantics; pylatexenc removes matched chars the same
//! way), in any source order — `\op^{a}_{b}` and `\op_{b}^{a}` both provide both
//! fields.
//!
//! # Record shape
//!
//! The whole run is **one argument** — per-marker `ParsedArgument` entries cannot
//! express free source order through sequential per-spec parsing — and each matched
//! pair stages one **classless wrapper `Group`** ([`GroupData::untyped`]): `open` =
//! the marker as written (span-backed), `close` empty, children = the expression's
//! node(s), preceded by a whitespace `Chars` node when whitespace separated marker
//! and expression (pylatexenc's `delimiters=(marker, '')` shape). The argument's content
//! designation covers the run of wrapper groups from the first one on — noise between
//! embellishments included, leading noise excluded. By-marker access is the read-side
//! helper [`split_embellishments`](crate::extract::split_embellishments).
//!
//! # Matching rules
//!
//! - **Noise before a marker; only whitespace before an expression**: whitespace and
//!   comments are scanned ahead of each marker (region noise, like every argument),
//!   and between a marker and its expression **plain whitespace** is tolerated
//!   (pylatexenc's
//!   `allow_pre_space` parity; TeX's `x^ 2`), staged *inside* the wrapper group as
//!   leading noise. Anything else — a comment, a paragraph break, end of input, a
//!   group close… — is **not a match**: the marker is rewound whole and the run
//!   ends, silently. Marker + expression stay atomic; a lone `^` is ordinary content
//!   of the enclosing level.
//! - **Longest match** among the still-available markers when several share a prefix
//!   (`'` vs. `''`) — a deliberate divergence from pylatexenc, whose accumulate-until-
//!   equal scan makes the shortest alternative win unconditionally. Multi-character
//!   markers must be contiguous (no intervening whitespace; the
//!   [`MarkerArgumentParser`](super::MarkerArgumentParser) precedent — no pylatexenc
//!   space-normalized accumulation).
//! - Markers are sequences of [`Char`](TokenKind::Char) tokens: a character claimed by
//!   another recognizer in the argument's state (a specials trigger, a group open)
//!   does not match. State-dependent tokenization is the law of the land — e.g. the
//!   latexlike `''` typography ligature outranks a `'` marker in text mode but not in
//!   math mode, where the ligature is not visible.
//!
//! Absent — no marker matches at the position — is a silent, valid outcome
//! (`can_match_empty` = `true`), consuming nothing.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::fmt;

use crate::node::{ArgumentExt, ContentNodes, GroupData, NodeKind};
use crate::source::{SourceSpan, TextContent};
use crate::spec::{ArgumentParser, ArgumentSpec, ParsedArgumentNodes};
use crate::state::Lang;
use crate::token::{Token, TokenEdge, TokenKind};

use super::argument_parsers::{
    parse_expression_node, scan_argument_noise, stage_pre_space,
};
use super::{node_text_content, ConstructParserResult, FromInvocation, ParseContext};

/// An argument position that absorbs a run of *marker + expression* pairs, such as
/// the sub- and superscripts of `\op^{a}_{b}` (xparse's `e{<chars>}` argument type).
///
/// The engine reaches for it when a callable's spec declares an argument with this
/// parser. Whenever one of the configured markers (`^`, `_`, `'`, …) comes next, it
/// must be followed — at most plain whitespace apart — by one expression: a
/// delimited group, a full invocation, or a single character. The pair repeats until
/// no still-available marker matches, in any source order, and each marker matches
/// at most once per invocation. Among available markers sharing a prefix the longest
/// one wins. A marker not followed by an expression is rewound whole and ends the run
/// silently, staying ordinary content of the enclosing level.
///
/// The whole run is recorded as **one argument**. Each matched pair stages one
/// classless wrapper `Group`
/// ([`GroupData::untyped`](crate::core::node::GroupData::untyped)) whose opening delimiter
/// is the marker as written and whose children are the expression's nodes; read the
/// pairs back by marker with
/// [`split_embellishments`](crate::extract::split_embellishments).
pub struct EmbellishmentsArgumentParser {
    markers: Vec<Box<str>>,
}

impl EmbellishmentsArgumentParser {
    /// An embellishments argument over the given markers (e.g. `["^", "_"]`; xparse's
    /// `e{^_}`). Markers must be non-empty; the list must be non-empty (violations are
    /// reported as implementation errors when the parser runs). Multi-character
    /// markers are allowed and win over shorter alternatives at the same position
    /// (longest match).
    pub fn new(
        markers: impl IntoIterator<Item = impl Into<Box<str>>>,
    ) -> EmbellishmentsArgumentParser {
        EmbellishmentsArgumentParser {
            markers: markers.into_iter().map(Into::into).collect(),
        }
    }
}

impl<L: Lang> ArgumentParser<L> for EmbellishmentsArgumentParser
where
    ArgumentExt<L>: Default,
    L::InvocationSyntax: FromInvocation<L>,
{
    fn parse_argument(
        &self,
        cx: &mut ParseContext<'_, '_, L>,
        _spec: &ArgumentSpec<L>,
    ) -> ConstructParserResult<L, Option<ParsedArgumentNodes<L>>> {
        // Spec-author contract, validated where the parser runs
        // ([§dd-dr:panic-policy]: an outer-layer contract violation is an `Err`).
        if self.markers.is_empty() {
            return Err(cx.implementation_error(
                "EmbellishmentsArgumentParser::new needs at least one marker",
                cx.here(),
            ));
        }
        if self.markers.iter().any(|marker| marker.is_empty()) {
            return Err(cx.implementation_error(
                "EmbellishmentsArgumentParser::new needs non-empty markers",
                cx.here(),
            ));
        }
        let mut nodes = Vec::new();
        let mut used = alloc::vec![false; self.markers.len()];
        let mut content_start: Option<u32> = None;

        loop {
            // Noise is allowed ahead of each marker; a failed probe rewinds exactly
            // this scan, keeping previously committed pairs.
            let noise = scan_argument_noise(cx)?;
            let Some(first) = noise.next.clone() else {
                noise.rewind(cx);
                break;
            };

            let Some((marker_index, marker_span)) =
                self.scan_marker(cx, &first, &used)?
            else {
                noise.rewind(cx);
                break;
            };

            // The expression follows the marker at most plain whitespace apart: the
            // probed token may carry pre-space, which the expression core stages
            // *inside* the wrapper as leading noise on commit. Anything else — a
            // comment, a paragraph break, end of input, any token that cannot begin
            // an expression — unmatches the marker whole (`parse_expression_node`
            // answers `None` for all of these, staging and consuming nothing).
            let mut wrapper_children = Vec::new();
            let state = Arc::clone(&cx.state);
            let expression = match cx.probe_token(&state)? {
                Some(token) => parse_expression_node(cx, &token, &mut wrapper_children)?,
                None => None,
            };
            if expression.is_none() {
                // Marker + expression are atomic: rewind the marker (and this
                // iteration's noise) and end the run, silently.
                cx.tokens.move_to_position(&noise.start);
                break;
            }

            // Committed: the wrapper group over the expression's nodes, the marker as
            // its open delimiter (pylatexenc's `(marker, '')` shape). The wrapper runs
            // from the marker to the end of the expression's last staged node, when
            // that node lies in the marker's own source; to the marker's end
            // otherwise.
            let span = match L::OBEYS_SPAN_TILING {
                true => {
                    let child_span = wrapper_children
                        .last()
                        .and_then(|last| cx.staged_nodes().get(*last))
                        .map(|child| child.span().clone())
                        .filter(|child| {
                            child.same_source(&marker_span)
                                && child.end() >= marker_span.end()
                        });
                    match child_span {
                        Some(child) => SourceSpan::new(
                            marker_span.source(),
                            marker_span.start()..child.end(),
                        ),
                        None => marker_span.clone(),
                    }
                }
                // No assumption about the staged child: a language that does not obey
                // span tiling gives no relation between its span and the marker's, and
                // the child's end is not a stream position to measure the wrapper
                // with. The span is what the reader describes for the stretch from the
                // marker's start to where the stream now stands — just past the
                // expression the wrapper holds.
                false => cx.source_span_within(
                    &cx.tokens.position_at(&first, TokenEdge::Start),
                    &cx.tokens.position_here(),
                )?,
            };
            let data = GroupData::untyped(
                node_text_content(&marker_span, &span),
                TextContent::empty(),
            );
            let wrapper = cx
                .stage_node(
                    NodeKind::group(data),
                    span.clone(),
                    Arc::clone(&cx.state),
                    wrapper_children,
                )
                .map_err(|error| cx.staging_error(error, span))?;

            used[marker_index] = true;
            nodes.extend(noise.nodes);
            stage_pre_space(cx, &mut nodes, &first)?;
            if content_start.is_none() {
                content_start = Some(nodes.len() as u32);
            }
            nodes.push(wrapper);

            if used.iter().all(|used| *used) {
                break; // every marker matched once — nothing left to probe for
            }
        }

        match content_start {
            // The content: the full run from the first wrapper group on (intermediate
            // noise included, leading noise excluded — module docs).
            Some(start) => {
                let end = nodes.len() as u32;
                Ok(Some(ParsedArgumentNodes::new(
                    nodes,
                    ContentNodes::InRegion(start..end),
                    Default::default(),
                )))
            }
            // No pair matched; the reader is back at the entry position (the first
            // iteration's rewind).
            None => Ok(None),
        }
    }

    /// Optional: absent is a valid, silent outcome (the trait default, stated
    /// explicitly — the expression-position guard leans on this answer).
    fn can_match_empty(&self) -> bool {
        true
    }
}

impl EmbellishmentsArgumentParser {
    /// Scan one marker starting at `first` (the noise scan's unconsumed stop token):
    /// consume contiguous `Char` tokens while they prefix a still-available marker,
    /// and settle on the **longest** fully matched one. On a match, the reader stands
    /// at the marker's end and `Some((marker index, marker span))` is returned; on a
    /// miss the reader is *not* rewound (the caller owns the rewind target).
    // The return type spells the scan's answer; an alias would name one method's
    // tuple, not a concept.
    #[allow(clippy::type_complexity)]
    fn scan_marker<'s, L: Lang>(
        &self,
        cx: &mut ParseContext<'_, 's, L>,
        first: &Token<L>,
        used: &[bool],
    ) -> ConstructParserResult<L, Option<(usize, SourceSpan<L::SourceOrigin>)>> {
        let TokenKind::Char(first_char) = cx.tokens.token_kind(first) else {
            return Ok(None);
        };

        let available = |candidate: &str| {
            self.markers
                .iter()
                .enumerate()
                .filter(|(index, _)| !used[*index])
                .find(|(_, marker)| &***marker == candidate)
                .map(|(index, _)| index)
        };
        let prefixes_any = |candidate: &str| {
            self.markers
                .iter()
                .enumerate()
                .any(|(index, marker)| !used[index] && marker.starts_with(candidate))
        };

        let mut run = String::new();
        run.push(first_char);
        if !prefixes_any(&run) {
            return Ok(None);
        }
        cx.tokens.move_to(first, TokenEdge::EndPastPostSpace);
        // The best-so-far match is kept as the *token* it ends on: only the reader can
        // say where that is.
        let mut best: Option<(usize, Token<L>)> =
            available(&run).map(|index| (index, first.clone()));

        let state = Arc::clone(&cx.state);
        loop {
            // Accumulate while the run still prefixes an available marker; each
            // continuation char must be contiguous (no pre-space).
            let Some(token) = cx.probe_token(&state)? else { break };
            let TokenKind::Char(c) = cx.tokens.token_kind(&token) else { break };
            if cx.tokens.position_at(&token, TokenEdge::StartBeforePreSpace)
                != cx.tokens.position_at(&token, TokenEdge::Start)
            {
                break;
            }
            run.push(c);
            if !prefixes_any(&run) {
                break;
            }
            cx.tokens.move_to(&token, TokenEdge::EndPastPostSpace);
            if let Some(index) = available(&run) {
                best = Some((index, token.clone()));
            }
        }

        let Some((index, last)) = best else { return Ok(None) };
        // The scan may have read past the settled match (a longer alternative that
        // never completed): stand the reader at the marker's end.
        cx.tokens.move_to(&last, TokenEdge::EndPastPostSpace);
        let span = cx.source_span_within(
            &cx.tokens.position_at(first, TokenEdge::Start),
            &cx.tokens.position_at(&last, TokenEdge::EndPastPostSpace),
        )?;
        Ok(Some((index, span)))
    }
}

impl fmt::Debug for EmbellishmentsArgumentParser {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EmbellishmentsArgumentParser")
            .field("markers", &self.markers)
            .finish()
    }
}

// The `e{…}`-code slice of the behavior (single-char markers, pylatexenc test ports)
// is covered in `latexlike::arguments`; here the marker-generality axes the code
// cannot spell — multi-character markers, longest match, expression forms.
#[cfg(test)]
mod tests {
    use super::*;
    use crate::engine::Language;
    use crate::latexlike::{CallableType, Latexlike, MacroSpec};
    use crate::extract::{content_as_chars, split_embellishments_drop_annotations};
    use crate::node::{check_tree_invariants, NodeRef};
    use crate::scopes::Package;
    use crate::state::ParsingState;
    use crate::error::{DiagnosticInfo, Recovery};
    use crate::latexlike::LatexlikeDriver;
    use alloc::string::ToString;
    use alloc::vec;

    /// A language defining `\m` with one embellishments argument over `markers`, and
    /// a zero-argument `\alpha`.
    fn language(markers: &[&str]) -> Language<Latexlike> {
        let parser = EmbellishmentsArgumentParser::new(markers.iter().copied());
        let mut package = Package::new("embellishment-tests");
        package.insert(
            CallableType::Macro,
            "m",
            Arc::new(MacroSpec::new(vec![Arc::new(ArgumentSpec::new_unnamed(Arc::new(parser)))])),
        );
        package.insert(CallableType::Macro, "alpha", Arc::new(MacroSpec::new(vec![])));
        Language::new(
            LatexlikeDriver::new(Recovery::Strict),
            ParsingState::lang_initial_with_packages([package]).expect("seed state"),
        )
    }

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

    fn keys(m: NodeRef<'_, Latexlike>) -> Vec<alloc::string::String> {
        split_embellishments_drop_annotations(m.argument_content_nodes(0).expect("provided"))
            .unwrap()
            .iter()
            .map(|entry| entry.key().to_string())
            .collect()
    }

    #[test]
    fn multi_char_markers_take_the_longest_available_match() {
        let result = parse(&["a", "ab"], r"\m ab{x}a{y}!");
        let m = result.tree.root().child(0).unwrap();
        assert_eq!(keys(m), ["ab", "a"]);
        let fields = split_embellishments_drop_annotations(m.argument_content_nodes(0).unwrap()).unwrap();
        assert_eq!(
            content_as_chars(fields.get("ab").unwrap().value_content().unwrap()).unwrap(),
            "x"
        );
        assert_eq!(
            content_as_chars(fields.get("a").unwrap().value_content().unwrap()).unwrap(),
            "y"
        );
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("!"));
    }

    #[test]
    fn a_longer_candidate_that_never_completes_falls_back_to_the_shorter_match() {
        // Markers `a` and `abc` on `ab{x}`: the scan reads `ab` chasing `abc`, settles
        // on the full match `a`, and the expression is then the immediately following
        // single char `b` — `{x}` stays enclosing content.
        let result = parse(&["a", "abc"], r"\m ab{x}");
        let m = result.tree.root().child(0).unwrap();
        assert_eq!(keys(m), ["a"]);
        let fields = split_embellishments_drop_annotations(m.argument_content_nodes(0).unwrap()).unwrap();
        assert_eq!(
            content_as_chars(fields.get("a").unwrap().value().unwrap()).unwrap(),
            "b"
        );
        assert!(result.tree.root().child(1).unwrap().is_group());
    }

    #[test]
    fn multi_char_markers_must_be_contiguous() {
        // `a b` is not the marker `ab`: nothing matches, the argument is silently
        // absent, and everything stays enclosing content.
        let result = parse(&["ab"], r"\m a b{x}");
        let m = result.tree.root().child(0).unwrap();
        assert!(!m.arguments().unwrap().get(0).unwrap().is_provided());
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some("a b"));
    }

    #[test]
    fn the_expression_takes_every_expression_form() {
        // A full invocation…
        let result = parse(&["^"], r"\m^\alpha rest");
        let m = result.tree.root().child(0).unwrap();
        let wrapper = m.argument_content_nodes(0).unwrap().first().unwrap();
        assert_eq!(wrapper.group_delimiters(), Some(("^", "")));
        assert!(wrapper.child(0).unwrap().is_callable());

        // …and a single character.
        let result = parse(&["^"], r"\m^2 rest");
        let m = result.tree.root().child(0).unwrap();
        let wrapper = m.argument_content_nodes(0).unwrap().first().unwrap();
        assert_eq!(wrapper.child(0).unwrap().chars(), Some("2"));
        assert_eq!(result.tree.root().child(1).unwrap().chars(), Some(" rest"));
    }

    // --- spec-author contract violations are implementation errors ([§dd-dr:panic-policy]) --

    #[test]
    fn an_empty_marker_list_is_an_implementation_error() {
        let err = language(&[]).parse(r"\m x").unwrap_err();
        assert_eq!(err.identifier(), super::super::ImplementationError::IDENTIFIER);
    }

    #[test]
    fn an_empty_marker_is_an_implementation_error() {
        let err = language(&["^", ""]).parse(r"\m^2").unwrap_err();
        assert_eq!(err.identifier(), super::super::ImplementationError::IDENTIFIER);
    }
}