techy 0.2.0

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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
//! Attached-source parsing: [`ParseContext::parse_attached_source`], which parses a
//! second source into the running parse, and
//! [`ParseContext::attach_source_reference`], which resolves a reference and then
//! does the same — the engine half of `\input`-style inclusion ([`SourceResolver`]
//! is the lookup half).
//!
//! Both parse the attached [`Source`] **into the running session**: included content
//! must parse under the parsing state at the inclusion point, which the running
//! session already has, and the staged nodes join the same builder, so a tree
//! drawing on several sources is still one tree (`BuildId`s are session-global).
//! Assembling a slot from the result stays the calling invocation parser's job: both
//! methods return an [`AttachedSourceOutcome`] — content nodes plus the included
//! run's merged after-effect record — and the caller stages the nodes (for `\input`,
//! as an [`Attached`](crate::core::node::SlotRole::Attached) slot of its callable node)
//! and decides whether the record continues past the inclusion.
//!
//! The reference itself is the caller's to read, and the rule on it is one line: an
//! `\input`-style construct's reference argument carries **plain text**. A caller that
//! finds anything else in the argument (a nested group, a callable, a comment) raises
//! [`InvalidSourceReferenceArgument`] and resolves nothing — the condition is defined
//! here, beside the two that [`ParseContext::attach_source_reference`] raises, so the
//! three ways an inclusion fails read the same across every `\input`-variant spec and
//! framework.
//!
//! Recursion control is deliberately **not** here: the core never interprets
//! reference strings, and legitimate self-inclusion exists (`.dtx`-style
//! self-documenting files). An embedder that wants a cycle or depth bound
//! enforces it in its resolver —
//! [`check_include_chain`](crate::source::check_include_chain) and
//! [`Source::including_sources`] are the ready-made tools.

use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::vec::Vec;

use core::fmt;

use crate::engine::{Frame, FrameTitle, ParseDriver};
use crate::error::{DiagnosticInfo, ToDiagnosticValue};
use crate::node::{BuildId, NodeKind};
use crate::source::{resolve_source_reference, ResolveError, Source, SourceSpan};
use crate::state::{Lang, ParsingState, ParsingStateDelta};

use super::{
    ConstructParser, ConstructParserResult, NodesOutcome, ParseContext, StopCause,
    StrayGroupClose,
};

/// The result of parsing an attached source: the staged content nodes of the
/// included run, plus the run's merged after-effect record.
///
/// Returned by [`ParseContext::parse_attached_source`] and
/// [`ParseContext::attach_source_reference`]. The nodes are staged in the running
/// parse's tree and their spans point into the attached [`Source`], not into the
/// document that included it.
pub struct AttachedSourceOutcome<L: Lang> {
    /// The staged content nodes, in source order — no wrapper `List`, no slot record:
    /// slot assembly stays the calling invocation parser's job.
    pub nodes: Vec<BuildId>,
    /// The sibling after-effect deltas the included run applied, merged into one
    /// replayable delta in application order
    /// ([`NodesOutcome::after_effects`] semantics, merged across resumed runs);
    /// `None` = the run applied none. Whether the included content's state effects
    /// continue past the inclusion is the **caller's choice**: an `\input`-style
    /// spec that persists them returns this delta as its own after-effect through
    /// the ordinary sibling channel (the preset's
    /// `input_macro_spec(persist_state: true, …)`); a state-transparent spec drops
    /// it. Boxed like [`NodesOutcome::after_effects`]: the common `None` costs one
    /// pointer-sized slot on a stack frame that stays live across the whole nested parse.
    pub after_effects: Option<Box<ParsingStateDelta<L>>>,
}

// Manual impls: derives would demand `L: Debug`/`L: Clone` (the `NodesOutcome`
// pattern).
impl<L: Lang> fmt::Debug for AttachedSourceOutcome<L> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AttachedSourceOutcome")
            .field("nodes", &self.nodes)
            .field("after_effects", &self.after_effects)
            .finish()
    }
}

impl<L: Lang> Clone for AttachedSourceOutcome<L> {
    fn clone(&self) -> Self {
        AttachedSourceOutcome {
            nodes: self.nodes.clone(),
            after_effects: self.after_effects.clone(),
        }
    }
}

impl<L: Lang> ParseContext<'_, '_, L> {
    /// Parses `source` as **attached content** of the construct being parsed: the
    /// sub-parse entry point of `\input`-style inclusion.
    ///
    /// The caller supplies everything the sub-parse needs: the [`Source`] to parse
    /// (already built — [`resolve_source_reference`] is what builds one from a
    /// reference, and [`attach_source_reference`](ParseContext::attach_source_reference)
    /// composes the two steps), the input parsing state (for inclusion semantics,
    /// the state at the inclusion point — `Arc::clone(&cx.state)`), and the parser
    /// that drives the run. The method builds a fresh inner context over its own
    /// reader for `source`, leaving the outer reader untouched on the outer source,
    /// and uses the **same session and node builder**, so the staged nodes belong to
    /// the running parse.
    ///
    /// # Spans and the including source
    ///
    /// Every node staged from the attached content carries a span into `source`, not
    /// into the document that included it, so one tree can name several sources; a
    /// [`SourceSpan`] always says which. The link back to the inclusion is the
    /// attached source's own provenance: [`resolve_source_reference`] stamps the
    /// including construct's span on it as
    /// [`triggered_at`](crate::source::SourceProvenance::triggered_at), which is what
    /// lets a diagnostic raised inside the inclusion be reported with the include
    /// chain that led to it. Byte accounting holds per source: the included nodes
    /// tile the attached content, and no span of theirs relates to the includer's
    /// bytes.
    ///
    /// # The parser to pass
    ///
    /// The caller supplies the construct parser driving the sub-parse; for
    /// `\input`-style inclusion that is the root nodes-parse shape,
    /// `&mut *cx.driver.make_nodes_parser(StopSpec::none(),
    /// ChildStateSpec::inherit())?`. The parser speaks the nodes-run vocabulary
    /// ([`NodesOutcome`]) so this method can drive it like the standard root parser
    /// ([`RootNodesParser`](super::RootNodesParser)) drives the
    /// root loop, and it **must tolerate re-invocation**: after a recovered stop
    /// this method calls `parse` again to resume (the standard
    /// [`NodesParser`](super::NodesParser) does — its working state drains at every
    /// return).
    ///
    /// Returns an [`AttachedSourceOutcome`]: the staged **content nodes only** — no
    /// wrapper `List` and no slot record, since assembling those stays the calling
    /// invocation parser's job, through the same
    /// [`stage_node`](ParseContext::stage_node) entry point as everything else —
    /// plus the included run's merged after-effect record
    /// ([`AttachedSourceOutcome::after_effects`]), which the caller forwards or
    /// drops (the persist-vs-transparent choice of `\input`-style specs). The whole
    /// sub-parse runs under a traceback [`Frame`] (`attached source`, anchored at
    /// the source's [`triggered_at`](crate::source::SourceProvenance::triggered_at)
    /// when it has one), so conditions inside the attached content point back at
    /// the inclusion.
    ///
    /// # Recovery
    ///
    /// A stray group close in the attached source is recovered **locally**: it is
    /// diagnosed as [`StrayGroupClose`] through the recovery entry point, consumed, and
    /// staged as a span-backed `Chars` node (the markup-in-chars recovery
    /// artifact — per-source byte accounting stays exact), and the parser is
    /// re-invoked — an included file's stray `}` never unwinds the includer's own
    /// group structure. Under
    /// [`Recovery::Strict`](crate::error::Recovery::Strict) recovery aborts the
    /// parse as usual (the `Err` propagates). A stop on the parser's **own** stop
    /// conditions ends the sub-parse normally — unlike the root loop, this method
    /// does not know the caller's stop spec, so a token/node-condition stop means
    /// "this run is complete" (content past it stays unparsed, the caller's
    /// choice). The sub-parse's pass-through state delta channel is discarded
    /// (the standard nodes parser returns `None` there by convention); the run's
    /// **applied** after-effects travel as the outcome's merged record instead.
    pub fn parse_attached_source<P>(
        &mut self,
        source: Arc<Source<L::SourceOrigin>>,
        state: Arc<ParsingState<L>>,
        parser: &mut P,
    ) -> ConstructParserResult<L, AttachedSourceOutcome<L>>
    where
        P: ConstructParser<L, Output = NodesOutcome<L>> + ?Sized,
    {
        // The traceback frame: anchored at the inclusion site when the source's
        // provenance records one (the rendered report's provenance-chain section
        // names the reference itself, so a static title carries no less
        // information and stays allocation-free to push).
        let frame = Frame {
            title: FrameTitle::Static("attached source"),
            span: source
                .provenance()
                .triggered_at()
                .cloned()
                .unwrap_or_else(|| SourceSpan::new(&source, 0..0)),
        };

        // The fresh inner context: its own reader over the attached content, the
        // same session/builder/driver. The outer reader (and the outer ambient
        // state) are untouched — `self` is shadowed for the sub-parse's extent.
        let mut reader = self.driver.make_token_reader(&source);
        let mut inner = ParseContext::new(
            &mut *reader,
            state,
            &mut *self.session,
            self.driver);

        inner.with_frame(frame, |cx| {
            let mut nodes: Vec<BuildId> = Vec::new();
            let mut after_effects: Option<Box<ParsingStateDelta<L>>> = None;
            loop {
                // `state: None` — each run re-enters under the loop's live ambient
                // state (re-anchored below to the previous run's exit state).
                let (outcome, _delta) = cx.parse_construct(&mut *parser, None, None)?;
                nodes.extend(outcome.nodes);
                // Merge each resumed run's after-effect record into one bundle
                // record (application order — later runs are sequentially later).
                // The run's record arrives boxed ([`NodesOutcome::after_effects`]);
                // the first run's box moves in whole, later runs merge into it.
                if let Some(run_effects) = outcome.after_effects {
                    match &mut after_effects {
                        Some(merged) => merged.merge_from(*run_effects),
                        None => after_effects = Some(run_effects),
                    }
                }
                // Thread the segment's exit state (the root-loop discipline):
                // resume and diagnosis run under the state the run reached.
                cx.state = outcome.state;
                match outcome.stop {
                    StopCause::EndOfInput => break,
                    StopCause::UnexpectedGroupClose { span, after } => {
                        // Local recovery: diagnose, consume, stage the delimiter
                        // as chars, resume — the includer never sees the close.
                        let delim = span.content().to_string();
                        cx.recover(StrayGroupClose { delim }, span.clone())?;
                        cx.tokens.move_to_position(&after);
                        let id = cx
                            .stage_node(
                                NodeKind::chars(span.span()),
                                span.clone(),
                                Arc::clone(&cx.state),
                                Vec::new(),
                            )
                            .map_err(|error| cx.staging_error(error, span))?;
                        nodes.push(id);
                    }
                    // The caller-supplied parser's own stop conditions ended the
                    // run — the door does not second-guess them (see above).
                    StopCause::TokenCondition { .. } | StopCause::NodeCondition => break,
                }
            }
            Ok(AttachedSourceOutcome { nodes, after_effects })
        })
    }

    /// Resolves `reference` through the driver's source resolver and parses the
    /// resolved source as attached content.
    ///
    /// This is the composition an `\input`-style construct performs once it has read
    /// its reference argument: it looks the reference up, and on success delegates to
    /// [`parse_attached_source`](ParseContext::parse_attached_source). Being the one
    /// place both lookup failures are raised, it gives them one wording across every
    /// `\input`-variant spec and framework:
    ///
    /// - no resolver configured on the driver
    ///   ([`ParseDriver::source_resolver`](crate::core::ParseDriver::source_resolver)
    ///   is `None`) → [`NoSourceResolver`];
    /// - the resolver returned an error → [`UnresolvableSourceReference`]
    ///   (reference + the live [`ResolveError`], cause chain included).
    ///
    /// Both are raised through the recovery entry point at `at` — the invocation span
    /// of the triggering construct, which is also what the minted source's
    /// provenance records as its
    /// [`triggered_at`](crate::source::SourceProvenance::triggered_at). Under
    /// [`Recovery::Tolerant`](crate::error::Recovery::Tolerant) the failure is
    /// recorded and `Ok(None)` is returned — nothing was attached, and the
    /// calling spec stages its callable without an attached slot; under
    /// [`Recovery::Strict`](crate::error::Recovery::Strict) recovery aborts.
    ///
    /// On success, delegates to
    /// [`parse_attached_source`](ParseContext::parse_attached_source) (whose
    /// parser/state/recovery contracts apply) and returns `Ok(Some(outcome))` —
    /// the staged nodes plus the included run's merged after-effect record
    /// ([`AttachedSourceOutcome`]). Resolution itself stays outside this method — the
    /// composition is accessor → [`resolve_source_reference`] →
    /// [`parse_attached_source`](ParseContext::parse_attached_source), so a caching
    /// framework can substitute either half by composing the pieces itself.
    pub fn attach_source_reference<P>(
        &mut self,
        reference: &str,
        at: &SourceSpan<L::SourceOrigin>,
        state: Arc<ParsingState<L>>,
        parser: &mut P,
    ) -> ConstructParserResult<L, Option<AttachedSourceOutcome<L>>>
    where
        P: ConstructParser<L, Output = NodesOutcome<L>> + ?Sized,
    {
        // The driver field is a shared reference with the context's own lifetime:
        // copy it out so the resolver borrow is independent of `&mut self`.
        let driver = self.driver;
        let Some(resolver) = crate::engine::ParseDriver::source_resolver(driver) else {
            self.recover(NoSourceResolver::new(reference), at.clone())?;
            return Ok(None);
        };
        match resolve_source_reference(resolver, reference, at) {
            Ok(source) => self.parse_attached_source(source, state, parser).map(Some),
            Err(error) => {
                self.recover(UnresolvableSourceReference::new(reference, error), at.clone())?;
                Ok(None)
            }
        }
    }
}

/// The error that is reported when a document includes a source by reference and the
/// parse driver has no source resolver (id `core.sources.no-resolver`).
///
/// A construct such as `\input{chapter1.tex}` includes the source that its reference
/// argument refers to. The reference is looked up with the
/// [`SourceResolver`](crate::source::SourceResolver) that
/// [`ParseDriver::source_resolver`](crate::core::ParseDriver::source_resolver) returns.
/// A driver has no resolver by default. A program that supports inclusion configures
/// one, for instance with
/// [`StdParseDriver::with_source_resolver`](crate::core::StdParseDriver::with_source_resolver)
/// or
/// [`LatexlikeDriver::with_source_resolver`](crate::latexlike::LatexlikeDriver::with_source_resolver).
///
/// Reported by [`ParseContext::attach_source_reference`], at the span of the invocation
/// that includes the source. Nothing is included: the invocation is parsed without the
/// included content (for `\input`, a callable node without an attached slot).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(
    id = "core.sources.no-resolver",
    message = "Unsupported inclusion of ‘{reference}’ (missing source resolver)"
)]
pub struct NoSourceResolver {
    /// The source reference (e.g. a file name), as written in the document.
    pub reference: String,
}

/// The error that is reported when a document includes a source that the source
/// resolver of the parse driver cannot provide (id
/// `core.sources.unresolvable-reference`).
///
/// A construct such as `\input{chapter1.tex}` includes the source that its reference
/// argument refers to. The [`SourceResolver`](crate::source::SourceResolver) of the parse
/// driver returns a [`ResolveError`] when it cannot provide that source, for instance
/// because no file of that name exists. The message contains the reference as written
/// in the document, followed by the [`message`](ResolveError::message) of the
/// [`ResolveError`].
///
/// Reported by [`ParseContext::attach_source_reference`], at the span of the invocation
/// that includes the source. Nothing is included: the invocation is parsed without the
/// included content (for `\input`, a callable node without an attached slot).
#[derive(Debug, Clone, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.sources.unresolvable-reference")]
pub struct UnresolvableSourceReference {
    /// The source reference, as written in the document.
    pub reference: String,
    /// The error that the source resolver returned.
    ///
    /// Its [`reference`](ResolveError::reference) can differ from the `reference`
    /// field, for instance when the resolver reports a canonical path. A program can
    /// inspect the underlying error (for instance an `io::Error`) through
    /// [`Error::source`](core::error::Error::source).
    pub error: ResolveError,
}

// Hand-written (the derive's `message` string cannot reach `error.message()`):
// the prefix names the reference as written in the document, never the
// resolver's possibly rewritten spelling — see the type docs.
impl fmt::Display for UnresolvableSourceReference {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "Failed to include ‘{}’: {}",
            self.reference,
            self.error.message()
        )
    }
}

/// The error that is reported when the reference argument of an `\input`-style
/// construct does not consist of plain text (id
/// `core.sources.invalid-reference-argument`).
///
/// The source reference is read from the characters of the argument's content. The
/// content must therefore consist of characters only, as in `\input{chapter1.tex}`.
///
/// Reported by the invocation parser that reads the argument, for instance the parser
/// of the preset's [`input_macro_spec`](crate::latexlike::input_macro_spec), at the span
/// of the argument. Nothing is resolved or included: the invocation is parsed without
/// the included content (for `\input`, a callable node without an attached slot).
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[non_exhaustive]
#[diagnostic(id = "core.sources.invalid-reference-argument")]
pub struct InvalidSourceReferenceArgument {
    /// The reason why the argument cannot be read as a source reference.
    pub reason: InvalidReferenceReason,
}

/// The reason why the argument of an [`InvalidSourceReferenceArgument`] cannot be read
/// as a source reference.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ToDiagnosticValue)]
#[non_exhaustive]
pub enum InvalidReferenceReason {
    /// The content of the argument contains nodes other than character nodes.
    NotPlainCharacters,
}

// Hand-written wording: the message varies by reason (a match, which the message
// format string cannot express), and the reason's own wire value is the enum's, not
// this English phrasing.
impl fmt::Display for InvalidSourceReferenceArgument {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.reason {
            InvalidReferenceReason::NotPlainCharacters => f.write_str(
                "Invalid source reference argument: the argument must contain only plain \
                 text",
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::constructs::{ChildStateSpec, StopSpec};
    use crate::engine::{ParseDriver, ParserSession, StdParseDriver};
    use crate::error::Recovery;
    use crate::scopes::ScopeStack;
    use crate::source::MapResolver;
    use crate::token::StdTokenReader;
    use crate::state::{ParsingState, StateData, TrivialLang};
    use crate::token::{
        CommandRule, CommandRules, CommentRules, ForbiddenCharsRules, GroupRule, GroupRules,
        ParagraphRules, SpecialsRules, TokenRules, WhitespaceRules,
    };
    use alloc::boxed::Box;
    use alloc::vec;
    use alloc::vec::Vec;

    /// A brace-group test lang over the std driver (commands off, groups on) —
    /// the DocLang shape of the engine tests.
    #[derive(Debug, Clone, Copy)]
    struct DocLang;
    impl Lang for DocLang {
        type Features = crate::state::AllLangFeatures;
        type GroupTypeId = u32;
        type CallableTypeId = u32;
        type ModeId = ();
        type StateExt = ();
        type Event = ();
        type SessionExt = ();
        type SourceOrigin = Option<String>;
        type Tokenization = crate::token::StdTokenization;
        type NodeExts = ();
        type InvocationSyntax = ();
        type Driver = StdParseDriver;

        fn initial_state_data() -> Result<StateData<Self>, crate::state::FinalizeError> {
            Ok(StateData {
                rules: TokenRules {
                    whitespace: WhitespaceRules { enabled: true, chars: " \t\n".into() },
                    paragraphs: ParagraphRules { enabled: true },
                    groups: GroupRules {
                        enabled: true,
                        rules: vec![Arc::new(GroupRule {
                            group_type: 0,
                            open: "{".into(),
                            close: "}".into(),
                        })],
                        temporary: Vec::new(),
                        expecting_close: None,
                    },
                    commands: CommandRules {
                        enabled: true,
                        rules: vec![Arc::new(CommandRule {
                            escape_char: '\\',
                            name_chars:
                                "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".into(),
                        })],
                    },
                    comments: CommentRules {
                        enabled: false,
                        rules: Vec::new(),
                    },
                    specials: SpecialsRules { enabled: false },
                    forbidden_chars: ForbiddenCharsRules { chars: "".into() },
                },
                scopes: ScopeStack::new(),
                mode: (),
                ext: (),
            })
        }
        fn make_node_ext(
            _kind: &NodeKind<Self>,
            _span: &SourceSpan<Self::SourceOrigin>,
            _state: &Arc<ParsingState<Self>>,
            _children: crate::node::StagedChildren<'_, Self>,
        ) -> Result<(), crate::node::NodeBuildError> {
            Ok(())
        }
    }

    fn driver(recovery: Recovery) -> StdParseDriver {
        StdParseDriver::new(recovery, ())
    }

    fn driver_resolving(recovery: Recovery, entries: &[(&str, &str)]) -> StdParseDriver {
        let mut resolver = MapResolver::new();
        for (reference, content) in entries {
            resolver.insert(*reference, *content);
        }
        StdParseDriver::new(recovery, ())
            .with_source_resolver(resolver.with_reference_as_origin())
    }

    /// Run `f` inside a context over `content` (an outer primary source).
    fn with_context<R>(
        driver: &StdParseDriver,
        content: &str,
        f: impl FnOnce(&mut ParseContext<'_, '_, DocLang>, &Arc<Source>) -> R,
    ) -> (R, ParserSession<DocLang>) {
        let source: Arc<Source> = Arc::new(Source::new(content));
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<DocLang> = ParserSession::new();
        let state = Arc::new(ParsingState::<DocLang>::lang_initial().expect("seed state"));
        let result = {
            let mut cx =
                ParseContext::new(&mut reader, state, &mut session, driver);
            // The test's own source: a construct parser gets its spans from the
            // reader, so the fixtures build theirs from the binding here.
            f(&mut cx, &source)
        };
        (result, session)
    }

    /// The nodes-run parser the door is driven with in `\input` position.
    fn nodes_parser<'p>(
        driver: &'p StdParseDriver,
    ) -> Box<dyn ConstructParser<DocLang, Output = NodesOutcome<DocLang>> + 'p> {
        ParseDriver::<DocLang>::make_nodes_parser(
            driver,
            StopSpec::none(),
            ChildStateSpec::inherit(),
        )
        .expect("infallible factory")
    }

    #[test]
    fn identifiers_are_the_ruled_slate_strings() {
        assert_eq!(NoSourceResolver::IDENTIFIER, "core.sources.no-resolver");
        assert_eq!(
            UnresolvableSourceReference::IDENTIFIER,
            "core.sources.unresolvable-reference"
        );
        assert_eq!(
            InvalidSourceReferenceArgument::IDENTIFIER,
            "core.sources.invalid-reference-argument"
        );
    }

    #[test]
    fn an_invalid_reference_argument_projects_its_reason() {
        use crate::error::DiagnosticValue;

        let condition =
            InvalidSourceReferenceArgument::new(InvalidReferenceReason::NotPlainCharacters);
        // The wire value is the reason's own name, not the rendered English.
        let projected = crate::error::DiagnosticInfo::serializable_data(&condition);
        assert_eq!(
            projected,
            DiagnosticValue::Map(vec![(
                "reason".into(),
                DiagnosticValue::Str("not-plain-characters".into())
            )])
        );
    }

    #[test]
    fn the_door_parses_attached_content_into_the_same_session() {
        let driver = driver(Recovery::Strict);
        let (nodes, session) = with_context(&driver, r"\input{chapter.tex}", |cx, source| {
            let trigger = SourceSpan::entire(source);
            let attached: Arc<Source> =
                Arc::new(Source::resolved("hello {world}", "chapter.tex", trigger));
            let mut parser = nodes_parser(cx.driver);
            let outer_pos_before = cx.here().start();
            let outcome = cx
                .parse_attached_source(
                    Arc::clone(&attached),
                    Arc::clone(&cx.state),
                    &mut *parser,
                )
                .unwrap();
            let nodes = outcome.nodes;
            // The outer reader did not move: the sub-parse ran a fresh inner one.
            assert_eq!(cx.here().start(), outer_pos_before);
            // Content nodes only, staged into the *same* builder, with spans in
            // the attached source.
            let staged = cx.staged_nodes();
            for id in &nodes {
                let view = staged.get(*id).unwrap();
                assert!(Arc::ptr_eq(view.span().source(), &attached));
            }
            assert_eq!(staged.get(nodes[0]).unwrap().span().range(), 0..6);
            nodes
        });
        assert_eq!(nodes.len(), 2); // "hello " chars + the group
        assert!(session.diagnostics.is_empty());
    }

    #[test]
    fn a_stray_close_in_the_attached_source_recovers_locally() {
        // Tolerant: the included file's stray `}` is diagnosed, staged as chars,
        // and the run resumes — the includer is never unwound.
        let driver = driver(Recovery::Tolerant);
        let (nodes, session) = with_context(&driver, "outer", |cx, source| {
            let trigger = SourceSpan::new(source, 0..5);
            let attached: Arc<Source> =
                Arc::new(Source::resolved("a}b", "frag.tex", trigger));
            let mut parser = nodes_parser(cx.driver);
            let nodes = cx
                .parse_attached_source(attached, Arc::clone(&cx.state), &mut *parser)
                .unwrap()
                .nodes;
            let staged = cx.staged_nodes();
            let texts: Vec<String> = nodes
                .iter()
                .map(|id| staged.get(*id).unwrap().span().content().into())
                .collect();
            assert_eq!(texts, ["a", "}", "b"]);
            nodes
        });
        assert_eq!(nodes.len(), 3);
        assert_eq!(session.diagnostics.len(), 1);
        let diagnostic = session.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), StrayGroupClose::IDENTIFIER);
        // The condition carries the door's traceback frame, anchored at the
        // inclusion site in the *outer* source.
        assert_eq!(diagnostic.frames().last().unwrap().span().range(), 0..5);

        // Strict: the funnel aborts, as everywhere.
        let strict = self::driver(Recovery::Strict);
        let (result, _session) = with_context(&strict, "outer", |cx, source| {
            let trigger = SourceSpan::new(source, 0..5);
            let attached: Arc<Source> =
                Arc::new(Source::resolved("a}b", "frag.tex", trigger));
            let mut parser = nodes_parser(cx.driver);
            cx.parse_attached_source(attached, Arc::clone(&cx.state), &mut *parser)
        });
        assert_eq!(result.unwrap_err().identifier(), StrayGroupClose::IDENTIFIER);
    }

    #[test]
    fn core_performs_no_recursion_checking_self_inclusion_is_legal() {
        // A source whose provenance chain already contains its own origin — the
        // `.dtx` self-inclusion shape. The door parses it without complaint:
        // recursion policy belongs to the embedder's resolver
        // ([`check_include_chain`]), never to the core.
        let driver = driver(Recovery::Strict);
        let ((), session) = with_context(&driver, "outer", |cx, source| {
            let trigger = SourceSpan::new(source, 0..5);
            let first: Arc<Source> = Arc::new(
                Source::resolved("self", "self.tex", trigger)
                    .with_origin(Some("self.tex".into())),
            );
            let second: Arc<Source> = Arc::new(
                Source::resolved("self again", "self.tex", SourceSpan::entire(&first))
                    .with_origin(Some("self.tex".into())),
            );
            let mut parser = nodes_parser(cx.driver);
            let outcome = cx
                .parse_attached_source(second, Arc::clone(&cx.state), &mut *parser)
                .unwrap();
            assert_eq!(outcome.nodes.len(), 1);
        });
        assert!(session.diagnostics.is_empty());
    }

    #[test]
    fn attach_without_a_resolver_diagnoses_no_source_resolver() {
        // Tolerant: recorded at `at`, Ok(None) — nothing attached.
        let tolerant = driver(Recovery::Tolerant);
        let (result, session) = with_context(&tolerant, r"\input{chapter.tex}", |cx, source| {
            let at = SourceSpan::entire(source);
            let mut parser = nodes_parser(cx.driver);
            cx.attach_source_reference(
                "chapter.tex",
                &at,
                Arc::clone(&cx.state),
                &mut *parser,
            )
        });
        assert!(result.unwrap().is_none());
        assert_eq!(session.diagnostics.len(), 1);
        let diagnostic = session.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), NoSourceResolver::IDENTIFIER);
        assert_eq!(diagnostic.span().range(), 0..19);
        let condition =
            diagnostic.data().downcast_ref::<NoSourceResolver>().unwrap();
        assert_eq!(condition.reference, "chapter.tex");

        // Strict: the funnel aborts with the condition.
        let strict = driver(Recovery::Strict);
        let (result, _session) = with_context(&strict, r"\input{chapter.tex}", |cx, source| {
            let at = SourceSpan::entire(source);
            let mut parser = nodes_parser(cx.driver);
            cx.attach_source_reference(
                "chapter.tex",
                &at,
                Arc::clone(&cx.state),
                &mut *parser,
            )
        });
        assert_eq!(result.unwrap_err().identifier(), NoSourceResolver::IDENTIFIER);
    }

    #[test]
    fn a_failing_resolver_diagnoses_unresolvable_reference_with_the_live_error() {
        let tolerant = driver_resolving(Recovery::Tolerant, &[]); // empty map
        let (result, session) = with_context(&tolerant, r"\input{missing.tex}", |cx, source| {
            let at = SourceSpan::entire(source);
            let mut parser = nodes_parser(cx.driver);
            cx.attach_source_reference(
                "missing.tex",
                &at,
                Arc::clone(&cx.state),
                &mut *parser,
            )
        });
        assert!(result.unwrap().is_none());
        assert_eq!(session.diagnostics.len(), 1);
        let diagnostic = session.diagnostics.iter().next().unwrap();
        assert_eq!(
            diagnostic.identifier(),
            UnresolvableSourceReference::IDENTIFIER
        );
        let condition = diagnostic
            .data()
            .downcast_ref::<UnresolvableSourceReference>()
            .unwrap();
        assert_eq!(condition.reference, "missing.tex");
        assert_eq!(condition.error.reference(), "missing.tex");
        // The message carries the resolver's own message as the detail.
        assert!(diagnostic.message().contains(condition.error.message()));
    }

    /// A resolver may spell the reference differently in its own error (e.g. a
    /// canonicalized path). The diagnostic's message must name the reference as
    /// written in the document; the resolver's spelling stays available on the
    /// structured `error` field.
    #[test]
    fn the_message_names_the_reference_as_written_not_the_resolvers_spelling() {
        #[derive(Debug)]
        struct RewritingResolver;
        impl crate::source::SourceResolver for RewritingResolver {
            fn resolve(
                &self,
                reference: &str,
                _triggered_at: &SourceSpan,
            ) -> Result<crate::source::ResolvedContent, ResolveError> {
                Err(ResolveError::new(
                    alloc::format!("/texmf/{reference}"),
                    "no file at this path",
                ))
            }
        }

        let driver = StdParseDriver::new(Recovery::Tolerant, ())
            .with_source_resolver(RewritingResolver);
        let (result, session) = with_context(&driver, r"\input{missing.tex}", |cx, source| {
            let at = SourceSpan::entire(source);
            let mut parser = nodes_parser(cx.driver);
            cx.attach_source_reference(
                "missing.tex",
                &at,
                Arc::clone(&cx.state),
                &mut *parser,
            )
        });
        assert!(result.unwrap().is_none());
        let diagnostic = session.diagnostics.iter().next().unwrap();
        // The texts below are the test's own: the reference as written and the
        // resolver's message appear in the message, the resolver's spelling does not.
        let message = diagnostic.message();
        assert!(message.contains("missing.tex"), "{message}");
        assert!(message.contains("no file at this path"), "{message}");
        assert!(!message.contains("/texmf/"), "{message}");
        let condition = diagnostic
            .data()
            .downcast_ref::<UnresolvableSourceReference>()
            .unwrap();
        assert_eq!(condition.reference, "missing.tex");
        assert_eq!(condition.error.reference(), "/texmf/missing.tex");
    }

    #[test]
    fn attach_resolves_and_parses_with_provenance_stamped_at_the_trigger() {
        let driver =
            driver_resolving(Recovery::Strict, &[("chapter.tex", "chapter {content}")]);
        let ((), session) = with_context(&driver, r"\input{chapter.tex} tail", |cx, source| {
            let at = SourceSpan::new(source, 0..19);
            let mut parser = nodes_parser(cx.driver);
            let nodes = cx
                .attach_source_reference(
                    "chapter.tex",
                    &at,
                    Arc::clone(&cx.state),
                    &mut *parser,
                )
                .unwrap()
                .expect("resolved and attached")
                .nodes;
            assert_eq!(nodes.len(), 2);
            let staged = cx.staged_nodes();
            let attached_source =
                Arc::clone(staged.get(nodes[0]).unwrap().span().source());
            // The minted source records this trigger and the resolver's origin.
            match attached_source.provenance() {
                crate::source::SourceProvenance::Resolved { reference, triggered_at } => {
                    assert_eq!(reference, "chapter.tex");
                    assert_eq!(triggered_at, &at);
                }
                other => panic!("expected Resolved provenance, got {:?}", other),
            }
            assert_eq!(
                attached_source.origin().as_deref(),
                Some("chapter.tex")
            );
        });
        assert!(session.diagnostics.is_empty());
    }

    #[test]
    fn serializable_data_renders_reference_message_and_cause_chain() {
        use crate::error::{DiagnosticValue, ToDiagnosticValue};

        #[derive(Debug)]
        struct Underlying;
        impl core::fmt::Display for Underlying {
            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                f.write_str("file not found (os error 2)")
            }
        }
        impl core::error::Error for Underlying {}

        let condition = UnresolvableSourceReference::new(
            "chapter.tex",
            ResolveError::new("chapter.tex", "cannot read file").with_cause(Underlying),
        );
        let projected = crate::error::DiagnosticInfo::serializable_data(&condition);
        let DiagnosticValue::Map(fields) = projected else {
            panic!("expected a map projection")
        };
        assert_eq!(
            fields[0],
            ("reference".into(), DiagnosticValue::Str("chapter.tex".into()))
        );
        let DiagnosticValue::Map(error_fields) = &fields[1].1 else {
            panic!("expected the error field to project as a map")
        };
        assert_eq!(
            error_fields[1],
            ("message".into(), DiagnosticValue::Str("cannot read file".into()))
        );
        assert_eq!(error_fields[2], ("kind".into(), DiagnosticValue::Str("other".into())));
        assert_eq!(
            error_fields[3],
            (
                "cause_chain".into(),
                DiagnosticValue::List(vec![DiagnosticValue::Str(
                    "file not found (os error 2)".into()
                )])
            )
        );
        // The stand-alone projection of the error type itself matches.
        assert_eq!(fields[1].1, condition.error.to_diagnostic_value());
    }

    #[test]
    fn trivial_lang_smoke_the_default_driver_resolves_nothing() {
        // The `()`-resolver pairing: no resolver, so the bundle diagnoses — the
        // resolver-choice pairing documented with `TrivialLang`.
        #[derive(Debug, Clone, Copy)]
        struct PlainLang;
        impl TrivialLang for PlainLang {}

        let driver: StdParseDriver = StdParseDriver::new(Recovery::Tolerant, ());
        let source: Arc<Source> = Arc::new(Source::new("x"));
        let mut reader = StdTokenReader::new(&source);
        let mut session: ParserSession<PlainLang> = ParserSession::new();
        let state = Arc::new(ParsingState::<PlainLang>::lang_initial().expect("seed state"));
        let mut cx = ParseContext::new(&mut reader, state, &mut session, &driver);
        let at = SourceSpan::entire(&source);
        let mut parser = ParseDriver::<PlainLang>::make_nodes_parser(
            &driver,
            StopSpec::none(),
            ChildStateSpec::inherit(),
        )
        .expect("infallible factory");
        let attached = cx
            .attach_source_reference("a.tex", &at, Arc::clone(&cx.state), &mut *parser)
            .unwrap();
        assert!(attached.is_none());
        assert_eq!(session.diagnostics.len(), 1);
    }

    #[test]
    fn a_run_without_after_effects_bundles_none() {
        // Persist test (e): an included run whose constructs apply no after-effect
        // deltas exports `after_effects: None` — the ruled `Option` spelling, so a
        // persisting caller forwards nothing rather than an empty delta.
        let driver = driver(Recovery::Strict);
        let ((), session) = with_context(&driver, r"\input{plain.tex}", |cx, source| {
            let trigger = SourceSpan::entire(source);
            let attached: Arc<Source> =
                Arc::new(Source::resolved("plain {content}", "plain.tex", trigger));
            let mut parser = nodes_parser(cx.driver);
            let outcome = cx
                .parse_attached_source(attached, Arc::clone(&cx.state), &mut *parser)
                .unwrap();
            assert_eq!(outcome.nodes.len(), 2);
            assert!(outcome.after_effects.is_none());
        });
        assert!(session.diagnostics.is_empty());
    }
}