techy 0.1.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
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
//! The preset's `\input`-shaped macro: [`InputMacroSpec`] and its constructor
//! [`input_macro_spec`].
//!
//! An invocation resolves the reference its argument names through the driver's
//! [`SourceResolver`](crate::source::SourceResolver) and parses the resolved content
//! into the same tree, at the point of invocation.

// This module is private; the public story lives on the items' own docs.

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

use crate::constructs::{
    parse_declared_arguments, CharsGroupArgumentParser, ChildStateSpec, ConstructParser,
    ConstructParserResult, InvalidReferenceReason, InvalidSourceReferenceArgument, Invocation,
    ParseContext, PlainCharsError, StopSpec,
};
use crate::node::{
    ArgumentExt, BuildId, ChildRegion, ContentNodes,
    ParsedArgument, ParsedArguments, ParsedSlot, ParsedSlots, SlotExt, SlotRole,
};
use crate::engine::ParseDriver;
use crate::scopes::SpecProvenance;
use crate::source::SourceSpan;
use crate::spec::{ArgumentSpec, CallableSpec, FrameRole};
use crate::token::TokenEdge;
use crate::state::ParsingStateDelta;

use super::lang::LatexlikeGroupType;
use super::spec::frame_title;
use super::{Latexlike, LatexlikeLang};

/// An `\input`-shaped macro definition: it resolves the source its argument names and
/// parses that content into the same tree, at the point of invocation.
///
/// Create one with [`input_macro_spec`] and register it in a package of your own, under
/// any command name and the macro callable type. The spec is **never preloaded** — it is
/// no part of [`builtin_package`](super::builtin_package), because an always-on `\input`
/// under a driver with no source resolver would only diagnose every use.
///
/// # What the embedder supplies
///
/// **The lookup.** techy performs no input/output of its own: reading the referenced
/// content is the embedding program's work, plugged in through the
/// [`SourceResolver`](crate::source::SourceResolver) trait and configured on the driver
/// with [`with_source_resolver`](super::LatexlikeDriver::with_source_resolver). The
/// resolver is called with the reference string exactly as the document wrote it, plus
/// the span of the invocation that asked for it, and returns either the content
/// ([`ResolvedContent`](crate::source::ResolvedContent)) or a
/// [`ResolveError`](crate::source::ResolveError). A driver with no resolver looks nothing
/// up. [`MapResolver`](crate::source::MapResolver) is the ready-made in-memory
/// implementation for tests and preloaded setups, and the guide chapter
/// [Defining macros, environments, and specials](crate::guide::specs#resolving-external-sources-input-like-inclusion)
/// gives a file-system recipe.
///
/// **The two constructor choices** of [`input_macro_spec`]: whether state changes made
/// inside the included content continue past the `\input`, and what [`SlotExt`] value the
/// attached slot records. Both have their own section below.
///
/// **The argument structure**, optionally. [`input_macro_spec`] declares the one standard
/// argument; [`InputMacroSpec::new`] takes an argument list of your own instead, for an
/// invocation shape of your choosing — see
/// [The reference argument](#the-reference-argument-carries-plain-text).
///
/// # The node an invocation stages
///
/// One callable node, whose own span is the invocation in the *including* source
/// (`\input{…}`). The content parsed out of the resolved source becomes an
/// [`Attached`](SlotRole::Attached) slot named `"attached"`, read back with
/// [`slot_content_nodes_named("attached")`](crate::core::node::NodeRef::slot_content_nodes_named).
/// Its nodes carry spans into the resolved source, so one tree names several sources and
/// each source is accounted for on its own: re-emitting the including source writes the
/// `\input{…}` invocation, not the included text.
///
/// # The reference argument carries plain text
///
/// The reference is read from the declared argument named `"reference"`
/// ([`REFERENCE_ARGUMENT_NAME`](InputMacroSpec::REFERENCE_ARGUMENT_NAME)); the other
/// declared arguments, if any, are parsed and staged like any macro's and play no part in
/// the inclusion.
///
/// Under [`input_macro_spec`] it is the only argument: a mandatory `{…}` group whose
/// contents read as plain characters — a chars-group
/// ([`CharsGroupArgumentParser`](crate::core::constructs::CharsGroupArgumentParser),
/// pylatexenc's chars-name argument). Commands and specials are off inside the braces,
/// because a file name is a name and not markup: `\input{my_file.tex}` keeps its
/// underscore, and `\input{\jobname.tex}` asks the resolver for the literal
/// `"\jobname.tex"`. Comments and nested groups stay recognized (pylatexenc's defaults).
/// There is no single-token fallback: `\input a` reports a missing mandatory argument.
///
/// Under [`InputMacroSpec::new`] the argument list is yours, and so is the reference
/// argument's parser: what it stages must still read as plain characters, by the rule
/// below, for the reference to be read at all.
///
/// The reference is the character payloads of the argument's content nodes, concatenated
/// in order and read off the nodes themselves. Characters are taken as written, with no
/// trimming: whitespace inside the braces is part of the reference (`\input{ chap.tex }`
/// resolves `" chap.tex "`), so tolerating padding is the resolver's choice.
///
/// Content that is anything else carries no such text: a protective group
/// (`\input{{chap.tex}}`) or a comment inside the braces raises
/// [`InvalidSourceReferenceArgument`](crate::core::constructs::InvalidSourceReferenceArgument)
/// at the argument's span, and nothing is resolved or attached. What counts is the staged
/// *nodes*, not the source text: a driver configured with
/// [`ParagraphBreakStyle::Specials`](super::ParagraphBreakStyle::Specials) stages a
/// paragraph break as a callable node, so a blank line inside the argument raises the
/// condition, where the default whitespace-characters shape would not.
///
/// Reading the reference from node data assumes nothing about where the tokens came from,
/// so the rule is the same under every language — including one declaring
/// [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`, whose argument
/// may be read from several sources.
///
/// # When inclusion fails
///
/// Three conditions, all raised through the parse's recovery entry point: under
/// [`Recovery::Tolerant`](crate::error::Recovery::Tolerant) each is recorded as a
/// diagnostic and the callable is staged **without** an attached slot, and the rest of the
/// document parses on; under [`Recovery::Strict`](crate::error::Recovery::Strict) the
/// parse aborts with it.
///
/// - [`InvalidSourceReferenceArgument`](crate::core::constructs::InvalidSourceReferenceArgument)
///   — the argument's content is not plain characters (above). Raised at the argument's
///   span, before any resolution is attempted.
/// - [`NoSourceResolver`](crate::core::constructs::NoSourceResolver) — no resolver is
///   configured on the driver. Raised at the invocation span.
/// - [`UnresolvableSourceReference`](crate::core::constructs::UnresolvableSourceReference)
///   — the resolver returned an error: no such file, reading it failed, the reference is
///   malformed, the resolver's own include policy refused it. The condition carries the
///   [`ResolveError`](crate::source::ResolveError) itself, cause chain included. Raised at
///   the invocation span.
///
/// The last two are raised at one site,
/// [`ParseContext::attach_source_reference`](crate::core::constructs::ParseContext::attach_source_reference),
/// which every `\input`-variant spec shares. An argument that is missing altogether is a
/// fourth case, reported by the argument parser as a missing mandatory argument; nothing
/// is resolved then either.
///
/// # Include chains, cycles, and depth
///
/// Every inclusion mints a fresh [`Source`](crate::source::Source) for the resolved
/// content, stamped with the invocation's span as its
/// [`triggered_at`](crate::source::SourceProvenance::triggered_at). A file included twice
/// therefore gets one source per inclusion site, and a diagnostic raised inside an
/// inclusion is reported with the chain of inclusions that led to it; the chain is
/// walkable from any source with
/// [`including_sources`](crate::source::Source::including_sources).
///
/// The parser never interprets a reference — no path semantics, no canonicalization, and
/// **no cycle check**: self-inclusion is legitimate in `.dtx`-style self-documenting
/// files, so the policy belongs to the resolver.
/// [`check_include_chain`](crate::source::check_include_chain) is the ready-made
/// cycle-and-depth check to call inside `resolve`, and a reference it refuses reaches the
/// document as an ordinary `UnresolvableSourceReference` diagnostic at the inner `\input`.
///
/// A resolver that enforces no policy of its own still cannot cause unbounded recursion:
/// the included content parses on the same session, and therefore under the same descent
/// guard, as the including document, so an inclusion cycle ends the parse with
/// [`DescentLimitExceeded`](crate::core::constructs::DescentLimitExceeded) at the
/// configured limit — an error under every recovery policy, never a crash. The limit is
/// configured with
/// [`Language::with_descent_guard_init`](crate::core::Language::with_descent_guard_init).
///
/// # Whether included state changes persist
///
/// The included content always parses under the parsing state at the `\input` point, so
/// definitions in force there apply inside it. What happens to the included content's
/// **own** after-effects — a `\newcommand`-style definition made *inside* the included
/// file — is the mandatory `persist_state` constructor choice:
///
/// - **`false` — transparent**: the included run's after-effects end with the file, and
///   the rest of the including document is unaffected.
/// - **`true` — persisting**: the after-effect deltas the included run applied, merged
///   into one record
///   ([`AttachedSourceOutcome::after_effects`](crate::core::constructs::AttachedSourceOutcome::after_effects)),
///   are returned as the `\input` invocation's own after-effect through the ordinary
///   sibling channel — the paradigm case is a preamble file whose definitions must hold
///   for the rest of the document. Nested inclusions compose: an inner file's persisted
///   effects join the outer file's record.
///
/// Either way the included content sees its own definitions as it parses: transparent
/// means the after-effects end with the file, not that they never applied.
///
/// # The attached slot's ext value
///
/// The attached slot's [`SlotExt`] value is supplied at construction and cloned into every
/// invocation's slot record; the spec does not decide what the value means. The preset's
/// recipe passes [`BodyMarker::not_body`](super::BodyMarker::not_body), so
/// [`NodeRef::body`](crate::core::node::NodeRef::body) does **not** select the attached
/// content and retrieval is by slot name — the preset's `\input` does not reuse the
/// environment-body marker. A framework that *wants* the attached content to be the node's
/// body passes a body-marked value instead
/// ([`BodySlotExt::make_body`](crate::core::node::BodySlotExt::make_body)), and `body()`
/// then finds it: `body()` selects on the ext value alone, with no additional condition on
/// the slot's role, precisely so that this choice cannot become silently unfindable.
///
/// # Variants
///
/// An invocation shape that is still an argument list — `\input[options]{file}`, or a
/// reference argument parsed differently — is [`InputMacroSpec::new`] with that list. A
/// shape that is not — `\input*{f1,f2,f3}` naming several sources, say — is a spec of
/// your own: it parses its own argument shapes and then reuses the same two steps, the
/// argument's text and
/// [`attach_source_reference`](crate::core::constructs::ParseContext::attach_source_reference),
/// staging the returned nodes as an [`Attached`](SlotRole::Attached) slot. This spec is
/// the short template for that.
///
/// # Serialization
///
/// A spec built by [`input_macro_spec`] serializes in a self-contained form, the two
/// constructor choices, unless it is stamped with a provenance
/// ([`with_provenance`](InputMacroSpec::with_provenance)), in which case it serializes by
/// identity like every other stamped spec. A spec built by [`InputMacroSpec::new`] carries
/// argument parsers, which have no serialized form, so it serializes by identity only: an
/// unstamped one is
/// [`SerializeError::MissingProvenance`](crate::serialize::SerializeError::MissingProvenance),
/// as for [`MacroSpec`](super::MacroSpec).
pub struct InputMacroSpec<LLL: LatexlikeLang = Latexlike> {
    /// The argument structure. Invariant: one argument is named
    /// [`REFERENCE_ARGUMENT_NAME`](InputMacroSpec::REFERENCE_ARGUMENT_NAME); both
    /// constructors establish it.
    arguments: Vec<Arc<ArgumentSpec<LLL>>>,
    /// Whether `arguments` is the standard structure [`input_macro_spec`] declares —
    /// then the spec is rebuildable from its two choices, and serializes in that
    /// self-contained form. `pub(super)`: read by the preset's wire layer.
    pub(super) standard_arguments: bool,
    /// Whether the included run's merged after-effects continue past the `\input`.
    persist_state: bool,
    /// The ext value cloned into every invocation's attached slot.
    attached_slot_ext: SlotExt<LLL>,
    /// Where the spec was defined, when known. `pub(super)`: the preset's wire
    /// layer reads the stamp directly — the `CallableSpec` impl (and so its
    /// `provenance()`) carries a bound the `SerializableObject` impl does not.
    pub(super) provenance: Option<SpecProvenance<LLL>>,
}

impl<LLL: LatexlikeLang> InputMacroSpec<LLL> {
    /// The name of the declared argument the reference is read from: `"reference"`.
    pub const REFERENCE_ARGUMENT_NAME: &'static str = "reference";

    /// An `\input`-shaped spec with an argument structure of your own.
    ///
    /// `arguments` is the full declared list, in invocation order, exactly as for
    /// [`MacroSpec::new`](super::MacroSpec::new). One of them must be named
    /// [`REFERENCE_ARGUMENT_NAME`](InputMacroSpec::REFERENCE_ARGUMENT_NAME): the
    /// reference is read from that argument, and the others are parsed and staged like
    /// any macro's. A list with no argument of that name is
    /// [`NoReferenceArgumentError`] — a mistake in a definition, reported when the spec
    /// is built rather than diagnosed during a parse.
    ///
    /// `persist_state` and `attached_slot_ext` are the two choices documented on
    /// [`input_macro_spec`], which is this constructor with the standard argument
    /// structure. A spec built here serializes by identity only — see
    /// [Serialization](InputMacroSpec#serialization).
    ///
    /// ```
    /// use techy::latexlike::{argument_specs_named, BodyMarker, InputMacroSpec, Latexlike};
    ///
    /// // `\include[options]{file}`: an optional argument ahead of the reference, and the
    /// // reference parsed as an ordinary `{…}` group (code `m`) rather than as plain
    /// // characters.
    /// let arguments = argument_specs_named::<Latexlike, _, _, _>([
    ///     ("o", "options"),
    ///     ("m", InputMacroSpec::<Latexlike>::REFERENCE_ARGUMENT_NAME),
    /// ])
    /// .unwrap();
    /// let spec = InputMacroSpec::new(arguments, false, BodyMarker::not_body()).unwrap();
    /// assert_eq!(spec.persist_state(), false);
    ///
    /// // No argument named "reference": refused when the spec is built.
    /// let arguments = argument_specs_named::<Latexlike, _, _, _>([("m", "file")]).unwrap();
    /// assert!(InputMacroSpec::new(arguments, false, BodyMarker::not_body()).is_err());
    /// ```
    pub fn new(
        arguments: Vec<Arc<ArgumentSpec<LLL>>>,
        persist_state: bool,
        attached_slot_ext: SlotExt<LLL>,
    ) -> Result<InputMacroSpec<LLL>, NoReferenceArgumentError> {
        let has_reference = arguments
            .iter()
            .any(|argument| argument.name.as_deref() == Some(Self::REFERENCE_ARGUMENT_NAME));
        if !has_reference {
            return Err(NoReferenceArgumentError {
                declared_names: arguments.iter().map(|argument| argument.name.clone()).collect(),
            });
        }
        Ok(InputMacroSpec {
            arguments,
            standard_arguments: false,
            persist_state,
            attached_slot_ext,
            provenance: None,
        })
    }

    /// Whether state changes made inside the included content continue past the
    /// `\input` — the `persist_state` choice made at construction
    /// ([`input_macro_spec`]).
    pub fn persist_state(&self) -> bool {
        self.persist_state
    }

    /// Returns the ext value recorded on every invocation's attached slot — the
    /// `attached_slot_ext` choice made at construction ([`input_macro_spec`]).
    pub fn attached_slot_ext(&self) -> &SlotExt<LLL> {
        &self.attached_slot_ext
    }

    /// Records where this spec is defined, so that it serializes by identity rather
    /// than in its self-contained form (`persist_state` plus the slot ext).
    ///
    /// The stamp is the [`SpecProvenance`] value a shared package provides for the
    /// name it defines. A stamp already recorded is replaced.
    pub fn with_provenance(mut self, provenance: SpecProvenance<LLL>) -> InputMacroSpec<LLL> {
        self.provenance = Some(provenance);
        self
    }
}

/// Creates the preset's opt-in `\input` spec: a macro that resolves the source its
/// argument names and parses that content into the same tree, at the point of invocation.
///
/// Register the returned [`InputMacroSpec`] in a package of your own — it is never
/// preloaded — and configure a [`SourceResolver`](crate::source::SourceResolver) on the
/// driver. The type's documentation carries the full contract: the parsed shape, the rule
/// on the reference argument, and what a failed resolution does.
///
/// The argument structure is the standard one: a single mandatory `{…}` argument named
/// `"reference"` whose contents read as plain characters (a
/// [`CharsGroupArgumentParser`](crate::core::constructs::CharsGroupArgumentParser)). For
/// a structure of your own — an options argument, a differently parsed reference — build
/// the spec with [`InputMacroSpec::new`] instead.
///
/// ```
/// use techy::core::{Language, ParsingState};
/// use techy::core::specs::Package;
/// use techy::error::Recovery;
/// use techy::latexlike::{
///     input_macro_spec, BodyMarker, CallableType, Latexlike, LatexlikeDriver,
/// };
/// use techy::source::MapResolver;
///
/// // A real embedder implements `SourceResolver` to read files; this one is in memory.
/// let mut resolver = MapResolver::new();
/// resolver.insert("chapter.tex", "included {content}");
///
/// let mut package: Package<Latexlike> = Package::new("mydefs");
/// package.insert(
///     CallableType::Macro,
///     "input",
///     input_macro_spec(false, BodyMarker::not_body()),
/// );
///
/// let language = Language::new(
///     LatexlikeDriver::new(Recovery::Strict).with_source_resolver(resolver),
///     ParsingState::lang_initial_with_packages([package]).expect("seed state"),
/// );
/// let result = language.parse(r"a \input{chapter.tex} b").unwrap();
/// let input = result.tree.root().child(1).unwrap();
/// // The invocation's own span is in the including source; the attached content —
/// // parsed out of the resolved source — is retrieved by its slot name.
/// assert_eq!(input.span_content(), r"\input{chapter.tex}");
/// assert_eq!(
///     input.slot_content_nodes_named("attached").unwrap().source_text().unwrap(),
///     "included {content}",
/// );
/// ```
///
/// # The two mandatory choices
///
/// Both parameters are deliberate embedder decisions with **no defaults**:
///
/// - `persist_state` — whether state changes made inside the included file (the
///   after-effects of its constructs) continue past the `\input` into the rest of the
///   including document. See
///   [Whether included state changes persist](InputMacroSpec#whether-included-state-changes-persist).
/// - `attached_slot_ext` — the [`SlotExt`] value recorded on the `"attached"` slot, cloned
///   per invocation. The preset's recipe passes
///   [`BodyMarker::not_body`](super::BodyMarker::not_body); a body-marked value makes the
///   attached content the node's [`body()`](crate::core::node::NodeRef::body) — the
///   framework's choice, never a shipped default. See
///   [The attached slot's ext value](InputMacroSpec#the-attached-slots-ext-value).
///
/// # Included content is read at parse time
///
/// The referenced content is resolved and parsed where the `\input` stands, and techy
/// caches nothing: the parsing state at that point governs how the content tokenizes, and
/// with `persist_state: true` the included content feeds state back into the including
/// document, so a cache of trees parsed without attachment would be unsound for any
/// document whose included files carry definitions. Caching the *content* is a different
/// matter and is the resolver's to do (the
/// [`SourceResolver`](crate::source::SourceResolver) contract allows it) — that is the
/// part that costs input/output. Caching parsed trees and splicing them in is sound only
/// when the inclusion is known to be state-transparent — `persist_state: false` **and** no
/// out-of-band state coupling — and is then an embedder-level optimization, not something
/// techy provides.
pub fn input_macro_spec<LLL>(
    persist_state: bool,
    attached_slot_ext: SlotExt<LLL>,
) -> InputMacroSpec<LLL>
where
    LLL: LatexlikeLang,
    ArgumentExt<LLL>: Default,
{
    InputMacroSpec {
        arguments: vec![Arc::new(ArgumentSpec::new(
            Arc::new(CharsGroupArgumentParser::new(LLL::GroupTypeId::content_group())),
            InputMacroSpec::<LLL>::REFERENCE_ARGUMENT_NAME,
        ))],
        standard_arguments: true,
        persist_state,
        attached_slot_ext,
        provenance: None,
    }
}

// The `SerializableObject`/`DeserializableObject` impls (identity when stamped, the
// two constructor choices otherwise) live in `super::serialize`.

impl<LLL> CallableSpec<LLL> for InputMacroSpec<LLL>
where
    LLL: LatexlikeLang,
    ArgumentExt<LLL>: Default,
{
    fn provenance(&self) -> Option<&SpecProvenance<LLL>> {
        self.provenance.as_ref()
    }

    fn arguments(&self) -> &[Arc<ArgumentSpec<LLL>>] {
        &self.arguments
    }

    fn stack_frame_title(&self, role: FrameRole, name: &str) -> String {
        frame_title("macro", role, name)
    }

    /// Infallible: `Ok(...)` wrapping is this implementation's whole use of the
    /// `Result`.
    fn make_invocation_parser<'a>(
        &'a self,
        invocation: Invocation<'a, LLL>,
    ) -> Result<
        alloc::boxed::Box<dyn ConstructParser<LLL, Output = BuildId> + 'a>,
        crate::error::ParseError<LLL::SourceOrigin>,
    >
    {
        Ok(alloc::boxed::Box::new(InputInvocationParser {
            invocation,
            persist_state: self.persist_state,
            attached_slot_ext: &self.attached_slot_ext,
        }))
    }
}

// Manual impls: derives would demand `LLL: Debug`/`Clone` although only `Arc`s and
// the `NodeExtTypes`-bounded ext are stored (the MacroSpec/SpecialsSpec pattern;
// `SlotExt` is `Clone + Debug` by the `NodeExtTypes` bounds).

impl<LLL: LatexlikeLang> fmt::Debug for InputMacroSpec<LLL> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InputMacroSpec")
            .field("arguments", &self.arguments)
            .field("standard_arguments", &self.standard_arguments)
            .field("persist_state", &self.persist_state)
            .field("attached_slot_ext", &self.attached_slot_ext)
            .field("provenance", &self.provenance)
            .finish()
    }
}

impl<LLL: LatexlikeLang> Clone for InputMacroSpec<LLL> {
    fn clone(&self) -> Self {
        InputMacroSpec {
            arguments: self.arguments.clone(),
            standard_arguments: self.standard_arguments,
            persist_state: self.persist_state,
            attached_slot_ext: self.attached_slot_ext.clone(),
            provenance: self.provenance.clone(),
        }
    }
}

/// The `\input` invocation parser — the **brief form** the attachment helpers
/// exist for: declared arguments → argument text → attach → `Attached` slot.
struct InputInvocationParser<'a, LLL: LatexlikeLang> {
    invocation: Invocation<'a, LLL>,
    persist_state: bool,
    attached_slot_ext: &'a SlotExt<LLL>,
}

impl<LLL> ConstructParser<LLL> for InputInvocationParser<'_, LLL>
where
    LLL: LatexlikeLang,
    ArgumentExt<LLL>: Default,
{
    type Output = BuildId;

    fn parse(
        &mut self,
        cx: &mut ParseContext<'_, '_, LLL>,
    ) -> ConstructParserResult<LLL, (BuildId, Option<Box<ParsingStateDelta<LLL>>>)> {
        let token = self.invocation.token;
        let name = cx.tokens.source_span_between(token, TokenEdge::Start, TokenEdge::End);

        // 1. The declared arguments (the shared core loop).
        let (mut children, arguments) =
            parse_declared_arguments(cx, self.invocation.spec, &name)?;

        // The invocation's extent in the *includer's* source: trigger through the
        // last argument node — where the reader now stands (the trigger's own end
        // when the argument is absent).
        let end = cx.tokens.position_here();
        let at = cx.source_span_within(
            &cx.tokens.position_at(token, TokenEdge::Start),
            &end,
        )?;

        // 2. The reference, exactly as written. It drives source resolution, so it is
        //    read where it can be read exactly: off the staged argument's own node data
        //    — the character payloads of its content nodes — under every language,
        //    whether or not it obeys span tiling. (A span covering several tokens is
        //    only what the reader described for them; for a language that obeys span
        //    tiling it describes them exactly, and then it says nothing the node data
        //    does not.) The argument's content must be plain characters: anything else
        //    is diagnosed here and no reference is read.
        //
        //    The argument is the declared one named `"reference"`, wherever it stands in
        //    the list. Both constructors guarantee one exists; a spec without it is an
        //    invariant break in the machinery, never the document's doing.
        let reference_argument = arguments
            .iter()
            .find(|argument| argument.name() == Some(InputMacroSpec::<LLL>::REFERENCE_ARGUMENT_NAME))
            .ok_or_else(|| {
                cx.implementation_error(
                    "the input spec declares no argument named \"reference\"",
                    at.clone(),
                )
            })?;
        let reference: Option<String> =
            match cx.argument_content_as_plain_chars(reference_argument, &children) {
                // `None`: an absent argument — the argument parser already diagnosed the
                // missing mandatory argument, and there is nothing here to add to it.
                Ok(text) => text,
                // The document's mistake: recovered, nothing resolved.
                Err(PlainCharsError::NotPlainCharacters { .. }) => {
                    let anchor = argument_span(cx, reference_argument, &children)
                        .unwrap_or_else(|| at.clone());
                    cx.recover(
                        InvalidSourceReferenceArgument::new(
                            InvalidReferenceReason::NotPlainCharacters,
                        ),
                        anchor,
                    )?;
                    None
                }
                // A staged record that does not resolve is a bug in the machinery, never
                // the document's doing — it aborts under any recovery policy.
                Err(PlainCharsError::MalformedRecord(error)) => {
                    return Err(cx.implementation_error(error, at.clone()))
                }
            };

        // 3. Resolve + attach through the single raising site, driving the root
        //    nodes-parse shape under the state at the `\input` point.
        let attached = match &reference {
            Some(reference) => {
                // A factory Err aborts under any policy ("could not build the
                // parser"), with the live traceback attached here.
                let driver = cx.driver;
                let mut parser = driver
                    .make_nodes_parser(StopSpec::none(), ChildStateSpec::inherit())
                    .map_err(|error| cx.attach_hook_frames(error))?;
                cx.attach_source_reference(
                    reference,
                    &at,
                    Arc::clone(&cx.state),
                    &mut *parser,
                )?
            }
            // No reference to resolve, and the failure is already diagnosed: an
            // absent argument by the argument parser, a provided argument whose
            // content is not plain characters by step 2's
            // `InvalidSourceReferenceArgument`. Nothing is resolved and nothing is
            // attached in either case.
            None => None,
        };

        // 4. The attached content becomes the `Attached` slot — present exactly
        //    when a source was attached (an empty file attaches an empty slot;
        //    a diagnosed resolution failure attaches none). The slot's ext is the
        //    embedder-supplied value, cloned per invocation — this spec never
        //    decides body-ness itself.
        let (slots, after_effects) = match attached {
            Some(outcome) => {
                let offset = children.len() as u32;
                let count = outcome.nodes.len() as u32;
                children.extend(outcome.nodes);
                let slots = ParsedSlots::new(vec![ParsedSlot::new(
                    ChildRegion::new(offset..offset + count, ContentNodes::InRegion(0..count)),
                    "attached",
                    SlotRole::Attached,
                    self.attached_slot_ext.clone(),
                )]);
                // The persist_state choice: forward the included run's merged
                // after-effect record — already boxed, moved as-is — as this
                // invocation's own after-effect (the existing sibling channel),
                // or stay transparent.
                let after_effects = if self.persist_state {
                    outcome.after_effects
                } else {
                    None
                };
                (slots, after_effects)
            }
            None => (ParsedSlots::empty(), None),
        };

        // 5. Stage. `Some(end)` pins the node's span to its invocation in the
        //    includer's source — the std last-child rule would reach into the
        //    attached source.
        let id = cx.stage_invocation(
            &self.invocation,
            ParsedArguments::from(arguments),
            slots,
            children,
            Some(&end),
        )?;
        Ok((id, after_effects))
    }
}

/// The span of a staged argument itself, for a diagnostic to point at: a delimited
/// argument's own node (delimiters included), or the extent of the nodes a bare
/// argument staged. `None` when the argument has no single span to point at — it was
/// not provided, it staged no node, or its nodes lie in more than one source (which a
/// language with [`OBEYS_SPAN_TILING`](crate::core::Lang::OBEYS_SPAN_TILING) `= false`
/// allows); the caller then points at the invocation instead.
fn argument_span<LLL: LatexlikeLang>(
    cx: &ParseContext<'_, '_, LLL>,
    argument: &ParsedArgument<LLL>,
    children: &[BuildId],
) -> Option<SourceSpan<LLL::SourceOrigin>> {
    let region = argument.region.as_ref()?;
    // At parse time the region is staged by construction (`finish` has not run).
    let (offsets, content) = region.staged()?;
    let staged = cx.staged_nodes();
    if let ContentNodes::InChildrenOf(id, _) = content {
        return Some(staged.get(*id)?.span().clone());
    }
    let region_nodes = children.get(offsets.start as usize..offsets.end as usize)?;
    let first = staged.get(*region_nodes.first()?)?.span().clone();
    let last = staged.get(*region_nodes.last()?)?.span();
    if !first.same_source(last) || last.end() < first.start() {
        return None;
    }
    Some(SourceSpan::new(first.source(), first.start()..last.end()))
}

/// The argument list handed to [`InputMacroSpec::new`] declares no argument named
/// [`REFERENCE_ARGUMENT_NAME`](InputMacroSpec::REFERENCE_ARGUMENT_NAME), so the spec
/// would have no argument to read the reference from.
///
/// A mistake in a definition, reported when the spec is built rather than diagnosed
/// during a parse.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NoReferenceArgumentError {
    /// The names of the declared arguments, in order; `None` for an unnamed one.
    pub declared_names: Vec<Option<Box<str>>>,
}

impl fmt::Display for NoReferenceArgumentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "the input spec's argument list declares no argument named {:?}",
            InputMacroSpec::<Latexlike>::REFERENCE_ARGUMENT_NAME
        )?;
        if self.declared_names.is_empty() {
            return write!(f, " (the list is empty)");
        }
        write!(f, " (declared: ")?;
        for (i, name) in self.declared_names.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            match name {
                Some(name) => write!(f, "{name:?}")?,
                None => write!(f, "<unnamed>")?,
            }
        }
        write!(f, ")")
    }
}

impl core::error::Error for NoReferenceArgumentError {}

#[cfg(test)]
mod tests {
    use super::super::test_support::root_shapes;
    use super::super::{
        argument_specs, argument_specs_named, check_latexlike_tree_invariants, BodyMarker,
        CallableType, GroupType, Latexlike, LatexlikeDriver, MacroSpec, SpecialsSpec,
    };
    use super::*;
    use crate::constructs::{
        GroupArgumentParser, InvalidReferenceReason, InvalidSourceReferenceArgument,
        MissingMandatoryArgument, NoSourceResolver, StrayGroupClose, UnresolvableCommand,
        UnresolvableSourceReference,
    };
    use crate::engine::Language;
    use crate::error::{DiagnosticInfo, Recovery};
    use crate::node::BodySlotExt;
    use crate::scopes::Package;
    use crate::source::{
        check_include_chain, MapResolver, ResolveError, ResolvedContent,
        SourceProvenance, SourceResolver, SourceSpan,
    };
    use crate::state::{CommentOverrides, ParsingState, TokenRulesOverrides};

    // The shipped registration recipe: `\input` state-transparent, the attached slot
    // recording the preset's not-body marker (Ruling A: the preset never overloads the
    // environment-body marker).
    fn input_package() -> Package<Latexlike> {
        input_package_with(false, BodyMarker::not_body())
    }

    fn input_package_with(persist_state: bool, ext: BodyMarker) -> Package<Latexlike> {
        let mut package = Package::new("inputs");
        package.insert(CallableType::Macro, "input", input_macro_spec(persist_state, ext));
        package
    }

    /// A language whose driver resolves the given references (origins labeled with
    /// the reference — the canonical-origin invariant) and defines `\input` under
    /// the shipped registration recipe.
    fn language(recovery: Recovery, entries: &[(&str, &str)]) -> Language<Latexlike> {
        language_with_packages(recovery, entries, [input_package()])
    }

    fn language_with_packages(
        recovery: Recovery,
        entries: &[(&str, &str)],
        packages: impl IntoIterator<Item = Package<Latexlike>>,
    ) -> Language<Latexlike> {
        let mut resolver = MapResolver::new();
        for (reference, content) in entries {
            resolver.insert(*reference, *content);
        }
        Language::new(
            LatexlikeDriver::new(recovery)
                .with_source_resolver(resolver.with_reference_as_origin()),
            ParsingState::lang_initial_with_packages(packages).expect("seed state"),
        )
        // Explicit guard: nested inclusions stack 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))
    }

    /// `\input` defined but no resolver configured.
    fn language_without_resolver(recovery: Recovery) -> Language<Latexlike> {
        Language::new(
            LatexlikeDriver::new(recovery),
            ParsingState::lang_initial_with_packages([input_package()]).expect("seed state"),
        )
    }

    #[test]
    fn a_self_including_source_is_refused_by_the_shared_session_guard() {
        // The attached-source sub-parse runs on the SAME session — and therefore
        // under the same descent guard — as the includer: an inclusion cycle (a
        // source `\input`-ing itself through a resolver with no cycle check of
        // its own) is cut off at the configured depth limit as an ordinary
        // error, aborting under the tolerant policy too — never unbounded
        // recursion. (`language()` configures `depth_limit(64)`.)
        use crate::constructs::DescentLimitExceeded;

        let language =
            language(Recovery::Tolerant, &[("self.tex", r"\input{self.tex}")]);
        let err = language.parse(r"\input{self.tex}").unwrap_err();
        assert_eq!(err.identifier(), DescentLimitExceeded::IDENTIFIER);
    }

    #[test]
    fn input_attaches_the_resolved_content_as_the_attached_slot() {
        let language =
            language(Recovery::Strict, &[("chapter.tex", "hello {world}")]);
        let result = language.parse(r"A\input{chapter.tex}B").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        assert_eq!(root_shapes(&result), ["chars(A)", "Macro(input)", "chars(B)"]);

        let input = result.tree.root().child(1).unwrap();
        // The node's span is its invocation in the *includer's* source.
        assert_eq!(input.span().range(), 1..20);
        assert_eq!(input.span_content(), r"\input{chapter.tex}");
        assert!(Arc::ptr_eq(input.span().source(), result.tree.root().span().source()));

        // The argument records the reference.
        let arguments = input.arguments().unwrap();
        assert_eq!(arguments.len(), 1);
        assert!(arguments.get(0).unwrap().is_provided());
        assert_eq!(
            input.argument_content_nodes_named("reference").unwrap().unwrap().source_text(),
            Some("chapter.tex")
        );

        // The attached slot: role `Attached`, named "attached", carrying the
        // embedder-supplied ext — the shipped recipe's not-body marker (Ruling A:
        // the preset does not overload the environment-body marker), so `body()`
        // does NOT select it and retrieval is by slot name.
        let slots = input.slots().unwrap();
        assert_eq!(slots.len(), 1);
        let slot = slots.get(0).unwrap();
        assert_eq!(slot.name(), Some("attached"));
        assert_eq!(slot.role, SlotRole::Attached);
        assert!(!slot.ext.is_body());
        assert!(input.body().is_none());

        // Per-source facts: the attached children live in the resolved source and
        // tile it in full — the named slot reads them back as one single-source
        // slice.
        let attached = input.slot_content_nodes_named("attached").unwrap();
        assert_eq!(attached.source_text(), Some("hello {world}"));
        let attached_span = attached.span().unwrap();
        assert!(!Arc::ptr_eq(attached_span.source(), input.span().source()));
        assert_eq!(attached_span.range(), 0..13);
        match attached_span.source().provenance() {
            SourceProvenance::Resolved { reference, triggered_at } => {
                assert_eq!(reference, "chapter.tex");
                assert_eq!(triggered_at.range(), 1..20);
            }
            other => panic!("expected Resolved provenance, got {:?}", other),
        }
        // The resolver labeled the origin with the reference.
        assert_eq!(attached_span.source().origin().as_deref(), Some("chapter.tex"));
    }

    #[test]
    fn nested_inputs_attach_recursively_with_chained_provenance() {
        let language = language(
            Recovery::Strict,
            &[("outer.tex", r"x\input{inner.tex}y"), ("inner.tex", "deep")],
        );
        let result = language.parse(r"\input{outer.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());

        let outer = result.tree.root().child(0).unwrap();
        let outer_attached = outer.slot_content_nodes_named("attached").unwrap();
        assert_eq!(outer_attached.len(), 3); // "x", \input{inner.tex}, "y"
        let inner = outer_attached.get(1).unwrap();
        assert_eq!(inner.name(), Some("input"));
        let inner_attached = inner.slot_content_nodes_named("attached").unwrap();
        assert_eq!(inner_attached.source_text(), Some("deep"));

        // The include chain is walkable from the innermost source: inner →
        // outer → primary.
        assert_eq!(
            inner_attached.span().unwrap().source().including_sources().count(),
            3
        );
    }

    #[test]
    fn input_without_a_resolver_diagnoses_and_stages_no_attached_slot() {
        let language = language_without_resolver(Recovery::Tolerant);
        let result = language.parse(r"A\input{chapter.tex}B").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), NoSourceResolver::IDENTIFIER);
        // Raised at the invocation span.
        assert_eq!(diagnostic.span().range(), 1..20);

        // The callable is staged with its argument but no attached slot; the
        // rest of the document still parses.
        assert_eq!(root_shapes(&result), ["chars(A)", "Macro(input)", "chars(B)"]);
        let input = result.tree.root().child(1).unwrap();
        assert!(input.slots().unwrap().is_empty());
        assert!(input.body().is_none());

        // Strict parses abort with the same condition.
        let strict = language_without_resolver(Recovery::Strict);
        let err = strict.parse(r"A\input{chapter.tex}B").unwrap_err();
        assert_eq!(err.identifier(), NoSourceResolver::IDENTIFIER);
    }

    #[test]
    fn input_with_an_unknown_reference_diagnoses_unresolvable() {
        let language = language(Recovery::Tolerant, &[]);
        let result = language.parse(r"\input{missing.tex} tail").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), UnresolvableSourceReference::IDENTIFIER);
        let condition = diagnostic
            .data()
            .downcast_ref::<UnresolvableSourceReference>()
            .unwrap();
        assert_eq!(condition.reference, "missing.tex");
        let input = result.tree.root().child(0).unwrap();
        assert!(input.slots().unwrap().is_empty());
    }

    #[test]
    fn the_reference_is_the_arguments_characters_whitespace_included() {
        // The reference is the argument's content characters as read, unnormalized:
        // whitespace inside the braces belongs to the chars node and therefore to the
        // reference. The resolver keyed on the padded name is what resolves.
        let padded = language(Recovery::Tolerant, &[(" chap.tex", "included")]);
        let result = padded.parse(r"\input{ chap.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        let input = result.tree.root().child(0).unwrap();
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("included")
        );
        // Trailing whitespace belongs to the chars node too, and so to the reference.
        let plain = language(Recovery::Tolerant, &[("chap.tex ", "included")]);
        let result = plain.parse(r"\input{chap.tex }").unwrap();
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        let input = result.tree.root().child(0).unwrap();
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("included")
        );
    }

    #[test]
    fn a_reference_argument_that_is_not_plain_characters_is_diagnosed() {
        // The reference argument carries plain text — that is the rule. Here the
        // content is a protective group (`\input{{chap.tex}}`), which carries no text
        // to resolve: the condition is raised at the argument's span, nothing is
        // attached, and the rest of the document parses.
        let language = language(Recovery::Tolerant, &[("chap.tex", "included")]);
        let result = language.parse(r"\input{{chap.tex}} tail").unwrap();
        check_latexlike_tree_invariants(&result.tree);

        assert_eq!(result.diagnostics.len(), 1, "{:?}", result.diagnostics);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), InvalidSourceReferenceArgument::IDENTIFIER);
        let condition = diagnostic
            .data()
            .downcast_ref::<InvalidSourceReferenceArgument>()
            .unwrap();
        assert_eq!(condition.reason, InvalidReferenceReason::NotPlainCharacters);
        // The rendered wording names the reason.
        assert_eq!(
            diagnostic.message(),
            "invalid source reference argument: its content is not plain characters"
        );
        // Anchored at the argument, delimiters included — `{{chap.tex}}`.
        assert_eq!(diagnostic.span().range(), 6..18);
        assert_eq!(diagnostic.span().content(), "{{chap.tex}}");

        // Nothing was resolved: no attached slot, and the resolver — which *does* know
        // `chap.tex` — was never asked for the braces-included literal.
        let input = result.tree.root().child(0).unwrap();
        assert!(input.slots().unwrap().is_empty());
        assert_eq!(root_shapes(&result), ["Macro(input)", "chars( tail)"]);
    }

    #[test]
    fn a_comment_in_the_reference_argument_is_diagnosed_too() {
        // The same condition for the other way an argument's content stops being
        // plain characters under the chars-group: a comment node (comments stay
        // recognized inside the braces, pylatexenc's default).
        let language = language(Recovery::Tolerant, &[("chap.tex", "included")]);
        let result = language.parse("\\input{chap%c\n.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1, "{:?}", result.diagnostics);
        assert_eq!(
            result.diagnostics.iter().next().unwrap().identifier(),
            InvalidSourceReferenceArgument::IDENTIFIER
        );
        assert!(result.tree.root().child(0).unwrap().slots().unwrap().is_empty());
    }

    #[test]
    fn commands_and_specials_in_the_argument_read_as_characters() {
        // The chars-group argument: a file name is a name, not markup. Commands and
        // specials inside the braces read as plain characters — no callable node is
        // staged and no unresolvable-command condition fires — and the literal text
        // is the reference the resolver is asked for. pylatexenc's own example: the
        // underscore in `\input{my_file.tex}` must stay part of the name.
        let mut defs = Package::new("defs");
        defs.insert(CallableType::Macro, "x", MacroSpec::new(vec![]));
        defs.insert_specials(CallableType::Specials, "_", SpecialsSpec::new(vec![]));
        let language = language_with_packages(
            Recovery::Strict,
            &[
                ("my_file.tex", "underscore"),
                (r"\x.tex", "defined command"),
                (r"\undefined.tex", "unknown command"),
            ],
            [input_package(), defs],
        );
        for (source, expected) in [
            (r"\input{my_file.tex}", "underscore"),
            (r"\input{\x.tex}", "defined command"),
            (r"\input{\undefined.tex}", "unknown command"),
        ] {
            let result = language.parse(source).unwrap();
            check_latexlike_tree_invariants(&result.tree);
            assert!(result.diagnostics.is_empty(), "{source}: {:?}", result.diagnostics);
            let input = result.tree.root().child(0).unwrap();
            assert_eq!(
                input.slot_content_nodes_named("attached").unwrap().source_text(),
                Some(expected),
                "{source}"
            );
        }
        // The same definitions are live outside the braces: there `_` is a specials.
        let result = language.parse("a_b").unwrap();
        assert!(result.tree.root().child(1).unwrap().is_callable());
    }

    #[test]
    fn a_strict_parse_aborts_on_a_reference_argument_that_is_not_plain_characters() {
        let strict = language(Recovery::Strict, &[("chap.tex", "included")]);
        let err = strict.parse(r"\input{{chap.tex}}").unwrap_err();
        assert_eq!(err.identifier(), InvalidSourceReferenceArgument::IDENTIFIER);
    }

    #[test]
    fn an_empty_included_file_attaches_an_empty_slot() {
        let language = language(Recovery::Strict, &[("empty.tex", "")]);
        let result = language.parse(r"\input{empty.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        let input = result.tree.root().child(0).unwrap();
        // The slot exists (the file *was* attached), with zero children.
        let slot = input.slots().unwrap().get(0).unwrap();
        assert_eq!(slot.role, SlotRole::Attached);
        assert_eq!(input.slot_content_nodes_named("attached").unwrap().len(), 0);
    }

    #[test]
    fn a_stray_close_in_the_included_file_never_unwinds_the_includer() {
        // The `\input` sits *inside a group*; the included file has a stray `}`.
        // Local recovery: the includer's group still closes at its own `}` —
        // the included close is diagnosed and staged as chars in the attached
        // source.
        let language = language(Recovery::Tolerant, &[("frag.tex", "a}b")]);
        let result = language.parse(r"{\input{frag.tex}}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), StrayGroupClose::IDENTIFIER);
        // The diagnostic points into the *attached* source, inside the door's frame.
        assert_eq!(diagnostic.span().range(), 1..2);
        assert!(diagnostic.frames().iter().any(|f| f.title() == "attached source"));

        // The outer group is intact and spans the whole input.
        let group = result.tree.root().child(0).unwrap();
        assert!(group.is_group());
        assert_eq!(group.span().range(), 0..18);
        let input = group.child(0).unwrap();
        assert_eq!(input.name(), Some("input"));
        // The attached content carries all three pieces, `}` included.
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("a}b")
        );
    }

    #[test]
    fn input_is_never_preloaded() {
        // Plain Latexlike (the canonical seed): `\input` is not defined — the
        // spec is strictly opt-in.
        let language = Language::new(
            LatexlikeDriver::new(Recovery::Tolerant),
            ParsingState::<Latexlike>::lang_initial().expect("seed state"),
        );
        let result = language.parse(r"\input{chapter.tex}").unwrap();
        assert_eq!(result.diagnostics.len(), 1);
        assert_eq!(
            result.diagnostics.iter().next().unwrap().identifier(),
            UnresolvableCommand::IDENTIFIER
        );
    }

    /// The embedder-policy recipe: a resolver enforcing cycle/depth policy with
    /// [`check_include_chain`] before delegating (origins = canonical names).
    #[derive(Debug)]
    struct PolicyResolver {
        map: MapResolver,
    }

    impl SourceResolver for PolicyResolver {
        fn resolve(
            &self,
            reference: &str,
            triggered_at: &SourceSpan,
        ) -> Result<ResolvedContent, ResolveError> {
            check_include_chain(
                &String::from(reference),
                triggered_at,
                |origin: &Option<String>| origin.clone(),
                Some(8),
            )?;
            SourceResolver::<Option<String>>::resolve(&self.map, reference, triggered_at)
        }
    }

    #[test]
    fn a_policy_resolver_turns_self_inclusion_into_a_diagnosed_cycle() {
        // `a.tex` includes itself. The *core* never blocks this (`.dtx`-style
        // self-inclusion is legal); the embedder's resolver enforces its own
        // policy via check_include_chain, and the violation surfaces as an
        // ordinary unresolvable-reference diagnostic at the inner `\input`.
        let mut map = MapResolver::new();
        map.insert("a.tex", r"x\input{a.tex}y");
        let language = Language::new(
            LatexlikeDriver::new(Recovery::Tolerant)
                .with_source_resolver(PolicyResolver { map: map.with_reference_as_origin() }),
            ParsingState::lang_initial_with_packages([input_package()]).expect("seed state"),
        );

        let result = language.parse(r"\input{a.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), UnresolvableSourceReference::IDENTIFIER);
        let condition = diagnostic
            .data()
            .downcast_ref::<UnresolvableSourceReference>()
            .unwrap();
        assert!(condition.error.message().contains("include cycle"));

        // The outer inclusion succeeded — one attached level, the inner `\input`
        // staged without a slot.
        let outer = result.tree.root().child(0).unwrap();
        let outer_attached = outer.slot_content_nodes_named("attached").unwrap();
        let inner = outer_attached.get(1).unwrap();
        assert_eq!(inner.name(), Some("input"));
        // The failed inner `\input` recorded no slot at all: the by-name access is
        // the unknown-name category error, not a silent miss.
        assert!(matches!(
            inner.slot_content_nodes_named("attached"),
            Err(crate::node::NamedAccessError::UnknownSlotName { .. })
        ));
    }

    #[test]
    fn a_bare_reference_argument_is_a_missing_mandatory_argument() {
        // `\input a` — the chars-group has no single-token fallback (pylatexenc's
        // chars-group parser requires the braces as well): the argument is reported
        // missing, nothing is resolved, and `a` parses on as ordinary text.
        let language = language(Recovery::Tolerant, &[("a", "ok")]);
        let result = language.parse(r"\input a").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        let identifiers: Vec<_> = result.diagnostics.iter().map(|d| d.identifier()).collect();
        assert_eq!(identifiers, [MissingMandatoryArgument::IDENTIFIER], "{:?}", result.diagnostics);
        let input = result.tree.root().child(0).unwrap();
        assert!(input.slots().unwrap().is_empty());
        assert_eq!(root_shapes(&result), ["Macro(input)", "chars(a)"]);
    }

    #[test]
    fn parse_result_recomposes_per_source_facts() {
        // The I-18 reconstruction shape: every recomposition-relevant fact of the
        // multi-source tree is recorded — the includer's bytes reproduce from the
        // root's non-attached spans, the attached source's bytes from the body.
        let language = language(Recovery::Strict, &[("part.tex", "in{ner}")]);
        let source_text = r"pre\input{part.tex}post";
        let result = language.parse(source_text).unwrap();
        check_latexlike_tree_invariants(&result.tree);

        // Root children tile the includer's source exactly (span tiling over
        // the primary source ignores the attached region).
        let root = result.tree.root();
        let mut rebuilt = String::new();
        for child in root.children().iter() {
            assert!(Arc::ptr_eq(child.span().source(), root.span().source()));
            rebuilt.push_str(child.span_content());
        }
        assert_eq!(rebuilt, source_text);

        // And the attached source rebuilds from its own slot's children.
        let input = root.child(1).unwrap();
        let slot_nodes = input.slot_content_nodes_named("attached").unwrap();
        let mut attached = String::new();
        for child in slot_nodes.iter() {
            attached.push_str(child.span_content());
        }
        assert_eq!(attached, "in{ner}");
    }

    #[test]
    fn a_body_marked_ext_makes_the_attached_slot_findable_as_the_body() {
        // The framework-choice path: an embedder passing a body-marked ext gets
        // an `Attached` slot that `NodeRef::body()` finds — the T5 findability
        // clause ([§dd-dr:slot-roles]: `body()` selects on the ext axis alone,
        // no hidden role conjunction, so an Attached-body choice is never
        // silently unlocatable). The pairing is a framework option, never the
        // shipped default.
        let language = language_with_packages(
            Recovery::Strict,
            &[("chapter.tex", "content")],
            [input_package_with(false, BodyMarker::make_body())],
        );
        let result = language.parse(r"\input{chapter.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty());
        let input = result.tree.root().child(0).unwrap();
        let slot = input.slots().unwrap().get(0).unwrap();
        assert_eq!(slot.role, SlotRole::Attached);
        assert!(slot.ext.is_body());
        assert_eq!(input.body().unwrap().source_text(), Some("content"));
    }

    // --- persist_state (Ruling B) ----------------------------------------------------

    /// A package defining `\{name}` as a `\def`-style macro whose after-effect is
    /// `delta` — the public path ([`MacroSpec::with_after_effect`]).
    fn defining_package(name: &str, delta: ParsingStateDelta<Latexlike>) -> Package<Latexlike> {
        let mut package = Package::new(name);
        package.insert(CallableType::Macro, name, MacroSpec::new(vec![]).with_after_effect(delta));
        package
    }

    /// An after-effect delta pushing a provider that defines the zero-argument
    /// macro `\{defined}`.
    fn definition_delta(defined: &str, package_name: &str) -> ParsingStateDelta<Latexlike> {
        let mut lib: Package<Latexlike> = Package::new(package_name);
        lib.insert(CallableType::Macro, defined, MacroSpec::new(vec![]));
        ParsingStateDelta::new().push_provider(Arc::new(lib))
    }

    #[test]
    fn persist_state_true_carries_included_definitions_past_the_input() {
        // Persist test (a), the paradigm case: the included file's `\def`
        // registers `\x` via an after-effect delta; under `persist_state: true`
        // the definition is USED after the `\input` in the includer.
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("defs.tex", r"\def\x")],
            [
                input_package_with(true, BodyMarker::not_body()),
                defining_package("def", definition_delta("x", "xdefs")),
            ],
        );
        let result = language.parse(r"\input{defs.tex}\x").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "diagnostics: {:?}", result.diagnostics);
        // The included run resolved its own `\x` (state evolves within the run
        // regardless of persist_state) AND the includer's `\x` after the
        // `\input` resolved through the persisted definition.
        assert_eq!(root_shapes(&result), ["Macro(input)", "Macro(x)"]);
        let input = result.tree.root().child(0).unwrap();
        let attached = input.slot_content_nodes_named("attached").unwrap();
        assert_eq!(attached.len(), 2); // \def, \x — both resolved inside too
    }

    #[test]
    fn persist_state_false_leaves_the_includers_state_untouched() {
        // Persist test (b): the SAME input under `persist_state: false` — the
        // included run still resolves its own `\x` (transparent means the
        // after-effects end with the file, not that they never applied), but
        // the includer's `\x` after the `\input` is unresolvable.
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("defs.tex", r"\def\x")],
            [
                input_package_with(false, BodyMarker::not_body()),
                defining_package("def", definition_delta("x", "xdefs")),
            ],
        );
        let result = language.parse(r"\input{defs.tex}\x").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        // Exactly one diagnostic: the includer-side `\x`.
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), UnresolvableCommand::IDENTIFIER);
        assert_eq!(diagnostic.span().range(), 16..18);
        assert!(Arc::ptr_eq(
            diagnostic.span().source(),
            result.tree.root().span().source()
        ));
        // Inside the included file the definition applied as usual.
        let input = result.tree.root().child(0).unwrap();
        let attached = input.slot_content_nodes_named("attached").unwrap();
        assert_eq!(attached.get(1).unwrap().name(), Some("x"));
    }

    #[test]
    fn nested_inclusion_composes_persisted_effects_to_the_primary() {
        // Persist test (c): inner.tex defines `\x`; outer.tex uses it after its
        // own `\input` (inner persisted effects visible to the outer file's
        // remainder) and the primary uses it after the outer `\input` (the
        // inner-origin delta rides the outer run's merged record outward).
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("outer.tex", r"\input{inner.tex}\x"), ("inner.tex", r"\def")],
            [
                input_package_with(true, BodyMarker::not_body()),
                defining_package("def", definition_delta("x", "xdefs")),
            ],
        );
        let result = language.parse(r"\input{outer.tex}\x").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "diagnostics: {:?}", result.diagnostics);
        assert_eq!(root_shapes(&result), ["Macro(input)", "Macro(x)"]);
        // Outer file's remainder saw the inner definition.
        let outer = result.tree.root().child(0).unwrap();
        let outer_attached = outer.slot_content_nodes_named("attached").unwrap();
        assert_eq!(outer_attached.get(1).unwrap().name(), Some("x"));
    }

    #[test]
    fn merged_after_effects_apply_in_order() {
        // Persist test (d): two delta-producing constructs in the included file.
        //
        // (d1) Field override, last-writer-wins: `\con` re-enables comments,
        // `\coff` disables them — the later override governs the includer after
        // the `\input`, so `%x` stages as plain chars (an empty or first-wins
        // record would leave comments enabled and stage a comment node).
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("toggles.tex", r"\con\coff")],
            [
                input_package_with(true, BodyMarker::not_body()),
                defining_package(
                    "con",
                    ParsingStateDelta::new().rules(TokenRulesOverrides {
                        comments: CommentOverrides {
                            enabled: Some(true),
                            ..CommentOverrides::default()
                        },
                        ..TokenRulesOverrides::default()
                    }),
                ),
                defining_package(
                    "coff",
                    ParsingStateDelta::new().rules(TokenRulesOverrides {
                        comments: CommentOverrides::disable(),
                        ..TokenRulesOverrides::default()
                    }),
                ),
            ],
        );
        let result = language.parse("\\input{toggles.tex}%x").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "diagnostics: {:?}", result.diagnostics);
        assert_eq!(root_shapes(&result), ["Macro(input)", "chars(%x)"]);

        // (d2) Scope pushes concatenate in application order: both constructs
        // define `\x`, the later push is innermost and wins resolution — its
        // zero-argument shape leaves `{q}` a sibling group (the earlier,
        // one-argument shape would consume it).
        let takes_arg = {
            let mut lib: Package<Latexlike> = Package::new("xa");
            lib.insert(
                CallableType::Macro,
                "x",
                MacroSpec::new(vec![Arc::new(ArgumentSpec::new(
                    Arc::new(GroupArgumentParser::new(GroupType::Content)),
                    "arg",
                ))]),
            );
            Arc::new(lib)
        };
        let no_arg = {
            let mut lib: Package<Latexlike> = Package::new("xb");
            lib.insert(CallableType::Macro, "x", MacroSpec::new(vec![]));
            Arc::new(lib)
        };
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("defs.tex", r"\defa\defb")],
            [
                input_package_with(true, BodyMarker::not_body()),
                defining_package("defa", ParsingStateDelta::new().push_provider(takes_arg)),
                defining_package("defb", ParsingStateDelta::new().push_provider(no_arg)),
            ],
        );
        let result = language.parse(r"\input{defs.tex}\x{q}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "diagnostics: {:?}", result.diagnostics);
        let shapes = root_shapes(&result);
        assert_eq!(shapes[1], "Macro(x)");
        assert!(shapes[2].starts_with("group("), "expected a sibling group, got {:?}", shapes);
        let x = result.tree.root().child(1).unwrap();
        assert!(x.arguments().unwrap().is_empty());
    }

    #[test]
    fn cross_segment_after_effects_merge_across_a_stray_close_resume() {
        // Review should-fix: a stray `}` in the included file splits its run into
        // two segments (local recovery + resume). After-effect deltas from BOTH
        // segments must ride the door's merged record under `persist_state: true`
        // — a merge that only kept the first segment's record would leave `\b`
        // unresolvable in the includer.
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("defs.tex", r"\defa}\defb")],
            [
                input_package_with(true, BodyMarker::not_body()),
                defining_package("defa", definition_delta("a", "adefs")),
                defining_package("defb", definition_delta("b", "bdefs")),
            ],
        );
        let result = language.parse(r"\input{defs.tex}\a\b").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        // Exactly the stray close's diagnostic, in the attached source.
        assert_eq!(result.diagnostics.len(), 1);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), StrayGroupClose::IDENTIFIER);
        // Both definitions — one from each segment — govern the includer.
        assert_eq!(root_shapes(&result), ["Macro(input)", "Macro(a)", "Macro(b)"]);
    }

    // --- an argument structure of the embedder's own (`InputMacroSpec::new`) ---------

    /// `\input` under an argument list built from `(code, name)` pairs.
    fn custom_input_package(codes: &[(&str, &str)]) -> Package<Latexlike> {
        let arguments =
            argument_specs_named::<Latexlike, _, _, _>(codes.iter().copied()).unwrap();
        let mut package = Package::new("inputs");
        package.insert(
            CallableType::Macro,
            "input",
            InputMacroSpec::new(arguments, false, BodyMarker::not_body()).unwrap(),
        );
        package
    }

    #[test]
    fn the_reference_is_read_from_the_argument_named_reference_wherever_it_stands() {
        // `\input[options]{file}`: the reference is the second declared argument.
        let package = custom_input_package(&[("o", "options"), ("m", "reference")]);
        let language =
            language_with_packages(Recovery::Strict, &[("chapter.tex", "hello")], [package]);
        let result = language.parse(r"A\input[draft]{chapter.tex}B").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        assert_eq!(root_shapes(&result), ["chars(A)", "Macro(input)", "chars(B)"]);
        let input = result.tree.root().child(1).unwrap();
        assert_eq!(input.span_content(), r"\input[draft]{chapter.tex}");
        assert_eq!(
            input.argument_content_nodes_named("options").unwrap().unwrap().source_text(),
            Some("draft")
        );
        assert_eq!(
            input.argument_content_nodes_named("reference").unwrap().unwrap().source_text(),
            Some("chapter.tex")
        );
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("hello")
        );

        // The optional argument absent: the reference is still the named one, not
        // the first provided.
        let result = language.parse(r"\input{chapter.tex}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        let input = result.tree.root().child(0).unwrap();
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("hello")
        );
    }

    #[test]
    fn a_custom_reference_parser_is_still_held_to_the_plain_characters_rule() {
        // The reference parsed as an ordinary `{…}` group (code `m`): what it stages
        // must still read as plain characters. A protective group inside the braces
        // (`\input{{chap.tex}}`) carries no such text, under this parser as under the
        // standard chars-group.
        let package = custom_input_package(&[("m", "reference")]);
        let language = language_with_packages(
            Recovery::Tolerant,
            &[("chap.tex", "x"), ("my-file.tex", "x")],
            [package],
        );
        let result = language.parse(r"\input{{chap.tex}}").unwrap();
        check_latexlike_tree_invariants(&result.tree);
        assert_eq!(result.diagnostics.len(), 1, "{:?}", result.diagnostics);
        let diagnostic = result.diagnostics.iter().next().unwrap();
        assert_eq!(diagnostic.identifier(), InvalidSourceReferenceArgument::IDENTIFIER);
        let input = result.tree.root().child(0).unwrap();
        assert!(input.slots().unwrap().is_empty());
        // A name the group parser reads as characters resolves.
        let result = language.parse(r"\input{my-file.tex}").unwrap();
        assert!(result.diagnostics.is_empty(), "{:?}", result.diagnostics);
        let input = result.tree.root().child(0).unwrap();
        assert_eq!(
            input.slot_content_nodes_named("attached").unwrap().source_text(),
            Some("x")
        );
    }

    #[test]
    fn a_list_without_a_reference_argument_is_refused_when_the_spec_is_built() {
        let arguments =
            argument_specs_named::<Latexlike, _, _, _>([("o", "options"), ("m", "file")])
                .unwrap();
        let error = InputMacroSpec::new(arguments, false, BodyMarker::not_body()).unwrap_err();
        assert_eq!(
            error.declared_names,
            vec![Some("options".into()), Some("file".into())]
        );
        assert_eq!(
            error.to_string(),
            r#"the input spec's argument list declares no argument named "reference" (declared: "options", "file")"#
        );

        // An empty list, and an unnamed argument.
        let error =
            InputMacroSpec::<Latexlike>::new(vec![], false, BodyMarker::not_body()).unwrap_err();
        assert!(error.declared_names.is_empty());
        assert!(error.to_string().ends_with("(the list is empty)"), "{error}");
        let arguments = argument_specs::<Latexlike, _>(["m"]).unwrap();
        let error = InputMacroSpec::new(arguments, false, BodyMarker::not_body()).unwrap_err();
        assert_eq!(error.declared_names, vec![None]);
        assert!(error.to_string().ends_with("(declared: <unnamed>)"), "{error}");
    }

    #[test]
    fn the_standard_recipe_declares_the_named_reference_argument() {
        let spec = input_macro_spec::<Latexlike>(false, BodyMarker::not_body());
        assert!(spec.standard_arguments);
        let names: Vec<Option<&str>> =
            spec.arguments().iter().map(|argument| argument.name.as_deref()).collect();
        assert_eq!(names, vec![Some(InputMacroSpec::<Latexlike>::REFERENCE_ARGUMENT_NAME)]);
        assert_eq!(InputMacroSpec::<Latexlike>::REFERENCE_ARGUMENT_NAME, "reference");
        // The same list handed to `new` builds a spec that is not the standard one:
        // the flag records the constructor, not the list's shape.
        let custom =
            InputMacroSpec::new(spec.arguments().to_vec(), false, BodyMarker::not_body())
                .unwrap();
        assert!(!custom.standard_arguments);
    }
}