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
//! Tokenization rules: the data that decides how source text is cut into tokens.
//!
//! [`TokenRules`] is all of it — which character introduces a command, which strings
//! open and close a group, which string starts a comment, which characters count as
//! whitespace, which characters are rejected outright — with one block per tokenization
//! feature: [`WhitespaceRules`], [`ParagraphRules`], [`GroupRules`], [`CommandRules`],
//! [`CommentRules`], [`SpecialsRules`], and [`ForbiddenCharsRules`].
//!
//! A language whose syntax differs from LaTeX only in *which* characters play which role
//! needs nothing more than a `TokenRules` value of its own:
//! [`StdTokenReader`](super::StdTokenReader) reads whatever the rules say. A language
//! that has to decide *differently* which token comes next implements
//! [`TokenReader`](super::TokenReader) instead.
//!
//! Nothing is built in. There is no predefined `\`, `{}`, `%`, or `$`, and none of these
//! types implement `Default`; the familiar LaTeX values are the latexlike preset's
//! ([`default_token_rules`](crate::latexlike::default_token_rules)). Build a set of your
//! own from [`TokenRules::empty`] with struct-update syntax.
//!
//! The rules are stored in the parsing state ([`StateData`](crate::core::StateData)), so
//! every one of these settings can change while a parse runs: a
//! [`ParsingStateDelta`](crate::core::ParsingStateDelta) holds
//! [`TokenRulesOverrides`](crate::core::token::TokenRulesOverrides) — one `*Overrides`
//! type per block — and the derived state's rules are the previous ones with those
//! overrides applied.
//!
//! Group *classes* and group *delimiters* are separate things. The class is the
//! language's own closed classification, [`Lang::GroupTypeId`]: usually an enum, and the
//! preset uses it to tell content groups from math groups. Which delimiter pairs exist,
//! and which class each pair produces, is runtime data — the [`GroupRule`] values here.
//! A construct parser may add a rule for the duration of one construct through a state
//! delta, which is how an optional-argument parser makes `[` … `]` a group pair just
//! while it reads that argument.
//!
//! One thing is deliberately not listed here: the trigger strings of specials. The
//! language recognizes those itself, through
//! [`Lang::scan_specials`](crate::core::Lang::scan_specials), because a trigger set can
//! be large and is usually assembled from whichever definitions are loaded. Everything
//! else — whitespace, groups, commands, comments, forbidden characters — is rules data.
//!
//! The guide chapter [Language syntax](crate::guide::language_syntax) describes these
//! settings in LaTeX terms;
//! [Token rules and specials recognition](crate::guide::custom_lang#token-rules-and-specials-recognition)
//! covers configuring them for a language of your own.
use String;
use Arc;
use Vec;
use fmt;
use crate;
/// One group delimiter pair, and the class of group it opens.
///
/// The delimiters are arbitrary non-empty strings — `{` … `}`, `[` … `]`, `$` … `$`,
/// `$$` … `$$`, `\(` … `\)`. Several rules may use the same string (`$…$` alongside
/// `$$…$$`), and one rule may use the same string to open and to close; the
/// [`PrefixTable`](super::PrefixTable) settles which rule a given piece of text matches.
///
/// [`group_type`](Self::group_type) is the language's own classification of the group
/// ([`Lang::GroupTypeId`]) and is independent of the spellings: the preset marks
/// `$…$` and `\(…\)` as math groups and `{…}` as a content group.
///
/// Rules are stored behind `Arc` in [`GroupRules::rules`]. Which rule matched is
/// recorded in the [`GroupOpen`](super::TokenKind::GroupOpen) token the reader produces,
/// so a construct parser never has to work it out again.
///
/// # Two equal rules are not interchangeable
///
/// Wherever behavior depends on *which* rule is in play, rules are compared by **`Arc`
/// identity** (`Arc::ptr_eq`), never by the structural `==` this type also implements:
///
/// - [`ParsingState::derived`](crate::core::ParsingState::derived) keeps the
/// [`temporary`](GroupRules::temporary) rules only when the installed
/// [`expecting_close`](GroupRules::expecting_close) **is one of them by `Arc`
/// identity**;
/// - the derivation caches key on the shared handles the same way: a derived state
/// reuses its base's [`PrefixTable`](super::PrefixTable) only when the rule lists
/// match elementwise by `Arc` identity, and the per-parse group-interior derivations
/// are memoized per `(base, rule)` handle pair
/// ([`ParserSession::group_interior_state`](crate::core::ParserSession::group_interior_state));
/// - the standard optional-argument parsers recognize the rules they declared
/// themselves by `Arc` identity in the matched token.
///
/// So clone the `Arc`, never the value: a data-equal copy behaves differently in every
/// one of these places, and a `contains(&rule)`-style check (which uses `==`) answers a
/// different question. That other question — "same group class and same delimiter
/// spellings" — is exactly what the structural `==` answers, and it is what
/// [`TokenKind`](super::TokenKind) equality uses to compare `GroupOpen` tokens.
/// One command syntax: an escape character introducing a named invocation.
///
/// With `escape_char: '\\'` and the ASCII letters as [`name_chars`](Self::name_chars) —
/// the LaTeX setting — `\textbf` reads as one command token named `textbf`, and `\&` as
/// one command token named `&`.
///
/// Several rules may coexist, each with its own escape character; when two of them claim
/// the same character, the earlier entry of [`CommandRules::rules`] wins. An empty rule
/// list means no command is recognized and escape characters read as ordinary content.
/// A command's syntax is always an escape character followed by a name; there is no
/// other form.
///
/// "Command" is the token-level term (TeX calls it a control sequence), deliberately not
/// "macro": at this level `\begin` is a command exactly like `\foobar`, and which names
/// are macros, environments, or anything else is decided later from the [callable
/// specs](crate::core::specs) in effect.
/// One comment syntax: a start delimiter, with the comment running to the end of the line.
///
/// With `start: "%"` — the LaTeX setting — `% remark` reads as one comment token, which
/// also takes in the newline that ends it and the indentation of the next line (the
/// token's post-space).
///
/// The terminator is always `'\n'`, or the end of the input; `'\r'` is ordinary content.
/// It does not depend on [`WhitespaceRules`], so comments still work when whitespace
/// handling is disabled. A comment always runs to the end of the line: there is no
/// block-comment form.
///
/// Several rules may coexist, and the longest matching start delimiter wins. An empty
/// [`CommentRules::rules`] list means no comment is recognized and a `%` reads as an
/// ordinary character.
/// Whitespace handling — the whitespace block of [`TokenRules`]: which characters count
/// as whitespace, and whether whitespace is treated specially at all.
///
/// While it is on, the reader skips a run of these characters ahead of each token and
/// attaches the run to that token as its *pre-space*, rather than producing a token per
/// space character. The preset's set is `" \t\n\r\u{000B}\u{000C}"`.
///
/// While it is off — [`enabled`](Self::enabled) `false`, or an empty
/// [`chars`](Self::chars) set — whitespace characters are ordinary content characters,
/// every token's pre-space is empty, and paragraph breaks are never detected. That is
/// the character-by-character reading mode.
///
/// Changed during a parse through
/// [`WhitespaceOverrides`](crate::core::token::WhitespaceOverrides).
/// Paragraph-break detection — the paragraphs block of [`TokenRules`].
///
/// A paragraph break is a run of whitespace holding two or more newlines: the blank line
/// between two paragraphs of LaTeX source. Breaks are found inside whitespace runs, so
/// this block has an effect only while whitespace handling
/// ([`WhitespaceRules::enabled`]) is on.
///
/// Changed during a parse through
/// [`ParagraphOverrides`](crate::core::token::ParagraphOverrides).
/// Group delimiters — the groups block of [`TokenRules`].
///
/// [`rules`](Self::rules) is the table of delimiter pairs in effect,
/// [`temporary`](Self::temporary) holds pairs added for the duration of one construct,
/// [`enabled`](Self::enabled) turns delimiter recognition on and off, and
/// [`expecting_close`](Self::expecting_close) names the closing delimiter the current
/// position is waiting for.
///
/// Changed during a parse through
/// [`GroupOverrides`](crate::core::token::GroupOverrides).
/// Command syntaxes — the commands block of [`TokenRules`]: which escape characters
/// introduce a command, and whether commands are recognized at all.
///
/// Changed during a parse through
/// [`CommandOverrides`](crate::core::token::CommandOverrides).
/// Comment syntaxes — the comments block of [`TokenRules`]: which strings start a
/// comment, and whether comments are recognized at all.
///
/// Changed during a parse through
/// [`CommentOverrides`](crate::core::token::CommentOverrides): a callable can switch
/// comments off for its body, so that a `%` inside stays ordinary content.
/// The specials scan — the specials block of [`TokenRules`].
///
/// *Specials* are callables triggered by a plain character sequence instead of by a
/// command name: `~`, `--`, the quote ligatures. This block holds nothing but the on/off
/// gate, because the triggers themselves are not rules data — the language recognizes
/// them through [`Lang::scan_specials`](crate::core::Lang::scan_specials), which in the
/// preset asks whichever definition providers are loaded.
///
/// Changed during a parse through
/// [`SpecialsOverrides`](crate::core::token::SpecialsOverrides).
/// Characters rejected as content — the forbidden-characters block of [`TokenRules`].
///
/// The preset forbids nothing; a language might forbid, say, a raw `\t` in a context
/// where only spaces are meaningful.
///
/// This block has no `enabled` gate on purpose: an empty
/// [`chars`](Self::chars) string is already the off setting, and it is one short string
/// to put back rather than a feature to re-enable. Changed during a parse through
/// [`ForbiddenCharsOverrides`](crate::core::token::ForbiddenCharsOverrides).
/// The data that decides how source text is cut into tokens: one block per tokenization
/// feature.
///
/// A `TokenRules` value says which characters are whitespace, whether a blank line is a
/// paragraph break, which delimiter pairs open and close a group, which escape
/// characters introduce a command and which characters its name may use, which strings
/// start a comment, whether the specials scan runs, and which characters are rejected as
/// content. Setting those seven blocks is all it takes to give a LaTeX-like language its
/// own surface syntax.
///
/// The value is stored in the parsing state, so it can change while a parse runs — see
/// [`TokenRulesOverrides`](crate::core::token::TokenRulesOverrides), the matching set of
/// per-block override types a state delta holds.
///
/// [`StdTokenReader`](super::StdTokenReader) reads exactly what this data says (together
/// with the [`PrefixTable`](super::PrefixTable) derived from it and the language's
/// specials-scan hook). A language that needs genuinely different tokenization
/// *behavior*, rather than different characters, implements the
/// [`TokenReader`](super::TokenReader) trait instead.
///
/// # Where the values come from
///
/// There is no default rule set. Start from
/// [`default_token_rules`](crate::latexlike::default_token_rules) to get the familiar
/// LaTeX values (`\` with the ASCII letters as command names, `{`/`}` and the math
/// delimiters as groups, `%` comments, ASCII whitespace with paragraph breaks on,
/// nothing forbidden), or from [`empty()`](Self::empty) to build a set of your own.
///
/// Each block is a public field, so construction writes a struct literal per block;
/// reading code uses the accessor methods ([`whitespace_enabled`](Self::whitespace_enabled),
/// [`group_rules`](Self::group_rules), …), which answer sensible values even for a
/// language that does not have the feature at all.
///
/// # Detection priority
///
/// At a position, whitespace is skipped first and becomes the next token's pre-space.
/// Then the first of these that matches decides the token: a paragraph break; the
/// closing delimiter the state expects
/// ([`expecting_group_close`](Self::expecting_group_close)); the longest group delimiter
/// in the [`PrefixTable`](super::PrefixTable); a command escape character; a comment
/// start; a specials trigger; a forbidden character (reported as an error); otherwise a
/// single content character. Group delimiters are tried before commands, so a delimiter
/// written with an escape character (`\(`) wins over reading a command. Whichever step
/// belongs to a disabled or absent feature never matches.
/// [`StdTokenReader::scan_std_token_at`](super::StdTokenReader::scan_std_token_at)
/// documents the order in full.
///
/// # The three ways a feature can be off
///
/// Each block except forbidden characters has its own `enabled` gate, in the spirit
/// of pylatexenc's `enable_macros`/`enable_comments` switches — and there are three
/// distinct ways for a feature to be off, each with its own word:
///
/// - **disabled** — the gate is `false`. The feature's syntax reads as ordinary content
/// characters while its data stays in place, so one state delta can switch a feature
/// off and a later one switch it back on without anyone having to keep a copy of the
/// rules.
/// - **empty** — there is no data: an empty rule list, or an empty character set.
/// Nothing is recognized even with the gate `true`.
/// - **absent** — the language does not have the feature at all. This one is a
/// compile-time declaration, made per feature through
/// [`Lang::Features`](crate::core::Lang::Features), and no runtime data can say
/// otherwise; [`LangFeatures`](crate::core::LangFeatures) defines the full vocabulary.
///
/// Absence reaches the storage: an absent feature's field below holds a zero-sized
/// stand-in ([`FeaturePresence::Store`](crate::core::FeaturePresence::Store)) rather
/// than its rules block, so the field takes no space and rules data for that feature
/// cannot even be written. For a language that has every feature — the usual case, and
/// the preset's — the fields simply *are* the blocks and none of this shows.
///
/// # Constructing rules for a language with absent features
///
/// Write the present features' blocks as plain literals and take every other field
/// from [`empty()`](Self::empty) with struct-update syntax:
///
/// ```
/// # use techy::core::token::{CommandRule, CommandRules, TokenRules};
/// # use techy::core::TrivialLang;
/// # use std::sync::Arc;
/// # // The example language declares every feature present (`TrivialLang`), so the
/// # // recipe compiles here as-is; for a partially-absent language the same recipe
/// # // applies, and only the absent features' fields must come from `empty()`.
/// # #[derive(Debug, Clone, Copy)]
/// # struct MyLang;
/// # impl TrivialLang for MyLang {}
/// let rules: TokenRules<MyLang> = TokenRules {
/// commands: CommandRules {
/// enabled: true,
/// rules: vec![Arc::new(CommandRule { escape_char: '\\', name_chars: "".into() })],
/// },
/// ..TokenRules::empty()
/// };
/// ```
///
/// (Writing a literal for an *absent* feature's field is a type error: the field is the
/// zero-sized stand-in, not the block.)
// Manual impls: derives would demand `L: Clone`/`L: Debug`/`L: PartialEq` although only
// the `Lang::GroupTypeId` associated type (already bounded) is stored.
// The equality impls carry one where-clause per store: the `Store` GAT itself
// promises only `Clone`/`Debug`, but both markers' stores satisfy `PartialEq`/`Eq`
// whenever the stored block does (and every rules block does), so the bounds hold at
// every concrete language.