1use std::{borrow::Cow, fmt, fmt::Display, rc::Rc};
2
3use crate::{
4 Digested,
5 common::{
6 arena::{self, SymStr},
7 dimension::Dimension,
8 error::*,
9 float::Float,
10 glue::Glue,
11 mudimension::MuDimension,
12 muglue::MuGlue,
13 number::Number,
14 numeric_ops::NumericOps,
15 store::Stored,
16 },
17 definition::{Definition, register::Register},
18 state,
19 tokens::Tokens,
20};
21
22static CONTROLNAME: &[&str] = &[
23 "NUL", "SOH", "STX", "ETX", "EOT", "ENQ", "ACK", "BEL", "BS", "HT", "LF", "VT", "FF", "CR", "SO",
24 "SI", "DLE", "DC1", "DC2", "DC3", "DC4", "NAK", "SYN", "ETB", "CAN", "EM", "SUB", "ESC", "FS",
25 "GS", "RS", "US",
26];
27
28#[derive(PartialEq, Eq, Clone, Copy, Hash, Debug)]
34#[repr(u16)]
35pub enum Catcode {
36 ESCAPE,
37 BEGIN,
38 END,
39 MATH,
40 ALIGN,
41 EOL,
42 PARAM,
43 SUPER,
44 SUB,
45 IGNORE,
46 SPACE,
47 LETTER,
48 OTHER,
49 ACTIVE,
50 COMMENT,
51 INVALID,
52 CS,
53 MARKER,
54 ARG,
55}
56
57impl From<u8> for Catcode {
58 fn from(num: u8) -> Catcode {
59 use crate::token::Catcode::*;
60 match num {
61 0 => ESCAPE,
62 1 => BEGIN,
63 2 => END,
64 3 => MATH,
65 4 => ALIGN,
66 5 => EOL,
67 6 => PARAM,
68 7 => SUPER,
69 8 => SUB,
70 9 => IGNORE,
71 10 => SPACE,
72 11 => LETTER,
73 12 => OTHER,
74 13 => ACTIVE,
75 14 => COMMENT,
76 15 => INVALID,
77 16 => CS,
78 17 => MARKER,
79 18 => ARG,
80 _ => {
81 IGNORE
84 },
85 }
86 }
87}
88
89impl From<Catcode> for u8 {
90 fn from(cc: Catcode) -> u8 {
91 use crate::token::Catcode::*;
92 match cc {
93 ESCAPE => 0,
94 BEGIN => 1,
95 END => 2,
96 MATH => 3,
97 ALIGN => 4,
98 EOL => 5,
99 PARAM => 6,
100 SUPER => 7,
101 SUB => 8,
102 IGNORE => 9,
103 SPACE => 10,
104 LETTER => 11,
105 OTHER => 12,
106 ACTIVE => 13,
107 COMMENT => 14,
108 INVALID => 15,
109 CS => 16,
110 MARKER => 17,
111 ARG => 18,
112 }
113 }
114}
115
116impl Catcode {
117 pub fn name(self) -> &'static str {
119 use crate::token::Catcode::*;
120 match self {
121 ESCAPE => "Escape",
123 BEGIN => "Begin",
124 END => "End",
125 MATH => "Math",
126 ALIGN => "Align",
127 EOL => "EOL",
128 PARAM => "Parameter",
129 SUPER => "Superscript",
130 SUB => "Subscript",
131 SPACE => "Space",
132 IGNORE => "Ignore",
134 LETTER => "Letter",
135 OTHER => "Other",
136 ACTIVE => "Active",
137 COMMENT => "Comment",
138 INVALID => "Invalid",
139 CS => "ControlSequence",
140 MARKER => "Marker",
141 ARG => "Arg",
142 }
143 }
144
145 pub fn name_sym(self) -> SymStr {
150 use crate::token::Catcode::*;
151 match self {
152 ESCAPE => crate::pin!("Escape"),
153 BEGIN => crate::pin!("Begin"),
154 END => crate::pin!("End"),
155 MATH => crate::pin!("Math"),
156 ALIGN => crate::pin!("Align"),
157 EOL => crate::pin!("EOL"),
158 PARAM => crate::pin!("Parameter"),
159 SUPER => crate::pin!("Superscript"),
160 SUB => crate::pin!("Subscript"),
161 SPACE => crate::pin!("Space"),
162 IGNORE => crate::pin!("Ignore"),
163 LETTER => crate::pin!("Letter"),
164 OTHER => crate::pin!("Other"),
165 ACTIVE => crate::pin!("Active"),
166 COMMENT => crate::pin!("Comment"),
167 INVALID => crate::pin!("Invalid"),
168 CS => crate::pin!("ControlSequence"),
169 MARKER => crate::pin!("Marker"),
170 ARG => crate::pin!("Arg"),
171 }
172 }
173 pub fn meaning(self) -> &'static str {
175 use crate::token::Catcode::*;
176 match self {
177 ESCAPE => "the escape character",
178 BEGIN => "begin-group character",
179 END => "end-group character",
180 MATH => "math shift character",
181 ALIGN => "alignment tab character",
182 EOL => "end-of-line character",
183 PARAM => "macro parameter character",
184 SUPER => "superscript character",
185 SUB => "subscript character",
186 IGNORE => "ignored character",
187 SPACE => "blank space",
188 LETTER => "the letter",
189 OTHER => "the character",
190 ACTIVE => "active character",
191 COMMENT => "comment character",
192 INVALID => "invalid character",
193 _ => "",
194 }
195 }
196 pub fn short_name(self) -> &'static str {
198 use crate::token::Catcode::*;
199 match self {
200 ESCAPE => "T_ESCAPE",
201 BEGIN => "T_BEGIN",
202 END => "T_END",
203 MATH => "T_MATH",
204 ALIGN => "T_ALIGN",
205 EOL => "T_EOL",
206 PARAM => "T_PARAM",
207 SUPER => "T_SUPER",
208 SUB => "T_SUB",
209 IGNORE => "T_IGNORE",
210 SPACE => "T_SPACE",
211 LETTER => "T_LETTER",
212 OTHER => "T_OTHER",
213 ACTIVE => "T_ACTIVE",
214 COMMENT => "T_COMMENT",
215 INVALID => "T_INVALID",
216 CS => "T_CS",
217 MARKER => "T_MARKER",
218 ARG => "T_ARG",
219 }
220 }
221
222 pub fn is_primitive(self) -> bool {
228 use crate::token::Catcode::*;
229 match self {
230 ESCAPE | BEGIN | END | MATH | ALIGN | EOL | PARAM | SUPER | SUB | SPACE => true,
232 IGNORE | LETTER | OTHER | ACTIVE | COMMENT | INVALID | CS | MARKER | ARG => false,
234 }
235 }
236 pub fn is_executable(self) -> bool {
238 use crate::token::Catcode::*;
239 match self {
240 BEGIN | END | MATH | ALIGN | SUPER | SUB | ACTIVE | CS => true,
242 EOL | ESCAPE | PARAM | SPACE | IGNORE | LETTER | OTHER | COMMENT | INVALID | MARKER | ARG => {
244 false
245 },
246 }
247 }
248 pub fn is_neutralizable(self) -> bool {
250 use crate::token::Catcode::*;
251 match self {
252 MATH | ALIGN | PARAM | SUPER | SUB | ACTIVE => true,
254 ESCAPE | BEGIN | END | EOL | IGNORE | SPACE | LETTER | OTHER | COMMENT | INVALID | CS
256 | MARKER | ARG => false,
257 }
258 }
259 pub fn is_active_or_cs(self) -> bool {
261 use crate::token::Catcode::*;
262 matches!(self, ACTIVE | CS)
263 }
264 pub fn is_absorbable(self) -> bool {
266 use crate::token::Catcode::*;
267 matches!(self, SPACE | LETTER | OTHER | COMMENT)
269 }
270 pub fn is_gullet_holdable(self) -> bool {
272 use crate::token::Catcode::*;
273 matches!(self, COMMENT | MARKER)
274 }
275 pub fn is_balanced_interesting(self) -> bool {
277 use crate::token::Catcode::*;
278 matches!(self, BEGIN | END | MARKER)
280 }
281}
282
283#[derive(Copy, Clone)]
298#[repr(C)]
299pub struct Token {
300 pub text: SymStr,
302 pub code: Catcode,
304 pub prov: u16,
310 #[cfg(feature = "token-locators")]
318 pub loc: u32,
319}
320
321impl fmt::Debug for Token {
322 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
323 if self.code == Catcode::ARG {
324 self.with_str(|text| write!(f, "\"#{}\"", text))
325 } else {
326 self.with_str(|text| write!(f, "{:?}", text))
327 }
328 }
329}
330
331impl Display for Token {
332 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
333 if self.code == Catcode::ARG {
334 write!(f, "#")?;
335 }
336 self.with_str(|text| write!(f, "{}", text))
337 }
338}
339
340impl PartialEq for Token {
345 fn eq(&self, other: &Token) -> bool {
346 self.code == other.code && (self.code == Catcode::SPACE || (self.text == other.text))
347 }
348}
349
350impl Eq for Token {}
352
353impl std::hash::Hash for Token {
356 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
357 self.code.hash(state);
358 if self.code != Catcode::SPACE {
359 self.text.hash(state);
360 }
361 }
362}
363
364thread_local! {
378 static NOEXPAND_FAMILY_MEMO: std::mem::ManuallyDrop<std::cell::RefCell<Vec<u8>>> =
379 const { std::mem::ManuallyDrop::new(std::cell::RefCell::new(Vec::new())) };
380}
381const NOEXPAND_MEMO_SPAN: usize = 1 << 26;
383
384pub fn reset_noexpand_family_memo() {
390 NOEXPAND_FAMILY_MEMO.with(|memo| *memo.borrow_mut() = Vec::new());
391}
392
393pub const NOEXPAND_PREFIX: &str = "\\special_relax";
396pub const NOEXPAND_SEP: u8 = 1;
401
402pub fn noexpand_family(shadowed: &Token) -> Token {
408 let text = shadowed.with_str(|s| format!("{NOEXPAND_PREFIX}{}{s}", NOEXPAND_SEP as char));
409 Token {
410 text: arena::pin(text),
411 code: Catcode::CS,
412 prov: 0,
413 #[cfg(feature = "token-locators")]
414 loc: 0,
415 }
416}
417
418thread_static! {
424 pub static TOKEN_BEGIN: Token = Token {
426 text: arena::pin_static("{"),
427 code: Catcode::BEGIN,
428 prov: 0,
429 #[cfg(feature = "token-locators")]
430 loc: 0,
431 };
432}
433thread_static! {
434 pub static TOKEN_END: Token = Token {
436 text: arena::pin_static("}"),
437 code: Catcode::END,
438 prov: 0,
439 #[cfg(feature = "token-locators")]
440 loc: 0,
441 };
442}
443thread_static! {
444 pub static TOKEN_MATH: Token = Token {
446 text: arena::pin_static("$"),
447 code: Catcode::MATH,
448 prov: 0,
449 #[cfg(feature = "token-locators")]
450 loc: 0,
451 };
452}
453thread_static! {
454 pub static TOKEN_ALIGN: Token = Token {
456 text: arena::pin_static("&"),
457 code: Catcode::ALIGN,
458 prov: 0,
459 #[cfg(feature = "token-locators")]
460 loc: 0,
461 };
462}
463thread_static! {
464 pub static TOKEN_PARAM: Token = Token {
466 text: arena::pin_static("#"),
467 code: Catcode::PARAM,
468 prov: 0,
469 #[cfg(feature = "token-locators")]
470 loc: 0,
471 };
472}
473thread_static! {
474 pub static TOKEN_SUPER: Token = Token {
476 text: arena::pin_static("^"),
477 code: Catcode::SUPER,
478 prov: 0,
479 #[cfg(feature = "token-locators")]
480 loc: 0,
481 };
482}
483thread_static! {
484 pub static TOKEN_SUB: Token = Token {
486 text: arena::pin_static("_"),
487 code: Catcode::SUB,
488 prov: 0,
489 #[cfg(feature = "token-locators")]
490 loc: 0,
491 };
492}
493thread_static! {
494 pub static TOKEN_SPACE: Token = Token {
496 text: arena::pin_static(" "),
497 code: Catcode::SPACE,
498 prov: 0,
499 #[cfg(feature = "token-locators")]
500 loc: 0,
501 };
502}
503thread_static! {
504 pub static TOKEN_CR: Token = Token {
506 text: arena::pin_static("\n"),
507 code: Catcode::SPACE,
508 prov: 0,
509 #[cfg(feature = "token-locators")]
510 loc: 0,
511 };
512}
513thread_static! {
514 pub static TOKEN_RELAX: Token = Token {
516 text: arena::pin_static("\\relax"),
517 code: Catcode::CS,
518 prov: 0,
519 #[cfg(feature = "token-locators")]
520 loc: 0,
521 };
522}
523thread_static! {
524 pub static TOKEN_EXPANDAFTER: Token = Token {
526 text: arena::pin_static("\\expandafter"),
527 code: Catcode::CS,
528 prov: 0,
529 #[cfg(feature = "token-locators")]
530 loc: 0,
531 };
532}
533thread_static! {
534 pub static TOKEN_ENDCSNAME: Token = Token {
536 text: arena::pin_static("\\endcsname"),
537 code: Catcode::CS,
538 prov: 0,
539 #[cfg(feature = "token-locators")]
540 loc: 0,
541 };
542}
543
544pub(crate) fn force_init() {
553 for token in constants() {
554 let _ = &**token;
555 }
556}
557
558fn constants() -> [&'static crate::aux_macros::ThreadRoot<Token>; 12] {
560 [
561 &TOKEN_BEGIN,
562 &TOKEN_END,
563 &TOKEN_MATH,
564 &TOKEN_ALIGN,
565 &TOKEN_PARAM,
566 &TOKEN_SUPER,
567 &TOKEN_SUB,
568 &TOKEN_SPACE,
569 &TOKEN_CR,
570 &TOKEN_RELAX,
571 &TOKEN_EXPANDAFTER,
572 &TOKEN_ENDCSNAME,
573 ]
574}
575
576pub(crate) fn repin_constants() -> bool {
580 const TEXTS: [&str; 12] = [
581 "{",
582 "}",
583 "$",
584 "&",
585 "#",
586 "^",
587 "_",
588 " ",
589 "\n",
590 "\\relax",
591 "\\expandafter",
592 "\\endcsname",
593 ];
594 let mut same = true;
595 for (token, text) in constants().into_iter().zip(TEXTS) {
596 same &= arena::pin_static(text) == token.text;
597 }
598 same
599}
600
601#[macro_export]
602macro_rules! T_BEGIN(() => { *$crate::token::TOKEN_BEGIN });
604#[macro_export]
605macro_rules! T_END(() => { *$crate::token::TOKEN_END });
607#[macro_export]
609macro_rules! T_MATH(() => { *$crate::token::TOKEN_MATH });
610#[macro_export]
612macro_rules! T_ALIGN(() => { *$crate::token::TOKEN_ALIGN });
613#[macro_export]
615macro_rules! T_PARAM(() => { *$crate::token::TOKEN_PARAM });
616#[macro_export]
618macro_rules! T_SUPER(() => { *$crate::token::TOKEN_SUPER });
619#[macro_export]
621macro_rules! T_SUB(() => { *$crate::token::TOKEN_SUB });
622#[macro_export]
624macro_rules! T_SPACE(() => { *$crate::token::TOKEN_SPACE };
625($text:literal) => {
626 Token { text: $crate::pin!($text), code: Catcode::SPACE,
627 prov: 0, #[cfg(feature = "token-locators")] loc: 0
628 }
629});
630#[macro_export]
632macro_rules! T_CR(() => { *$crate::token::TOKEN_CR });
633#[macro_export]
635macro_rules! T_LETTER {
636 ($text:literal) => {
637 Token {
638 text: $crate::pin!($text),
639 code: Catcode::LETTER,
640 prov: 0,
641 #[cfg(feature = "token-locators")]
642 loc: 0,
643 }
644 };
645 ($text:expr_2021) => {
646 Token {
647 text: $crate::common::arena::pin($text),
648 code: Catcode::LETTER,
649 prov: 0,
650 #[cfg(feature = "token-locators")]
651 loc: 0,
652 }
653 };
654}
655#[macro_export]
657macro_rules! T_OTHER {
658 ($text:literal) => {
659 Token {
660 text: $crate::pin!($text),
661 code: Catcode::OTHER,
662 prov: 0,
663 #[cfg(feature = "token-locators")]
664 loc: 0,
665 }
666 };
667 ($text:expr_2021) => {
668 Token {
669 text: $crate::common::arena::pin($text),
670 code: Catcode::OTHER,
671 prov: 0,
672 #[cfg(feature = "token-locators")]
673 loc: 0,
674 }
675 };
676}
677#[macro_export]
679macro_rules! T_OTHER_CHAR {
680 ($text:literal) => {
681 Token {
682 text: $crate::common::arena::pin_char($text),
683 code: Catcode::OTHER,
684 prov: 0,
685 #[cfg(feature = "token-locators")]
686 loc: 0,
687 }
688 };
689}
690#[macro_export]
692macro_rules! T_ACTIVE {
693 ($c:expr_2021) => {{
694 let mut tmp = [0u8; 4];
695 let s = $c.encode_utf8(&mut tmp);
696 Token {
697 text: $crate::common::arena::pin(s),
698 code: Catcode::ACTIVE,
699 prov: 0,
700 #[cfg(feature = "token-locators")]
701 loc: 0,
702 }
703 }};
704}
705#[macro_export]
707macro_rules! T_COMMENT {
708 ($text:expr_2021) => {
709 Token {
710 text: $crate::common::arena::pin($text),
711 code: Catcode::COMMENT,
712 prov: 0,
713 #[cfg(feature = "token-locators")]
714 loc: 0,
715 }
716 };
717}
718#[macro_export]
720macro_rules! T_CS {
721 ($text:literal) => {
722 $crate::token::Token {
723 text: $crate::pin!($text),
724 code: $crate::token::Catcode::CS,
725 prov: 0,
726 #[cfg(feature = "token-locators")]
727 loc: 0,
728 }
729 };
730 ($text:expr_2021) => {
731 $crate::token::Token {
732 text: $crate::common::arena::pin($text),
733 code: $crate::token::Catcode::CS,
734 prov: 0,
735 #[cfg(feature = "token-locators")]
736 loc: 0,
737 }
738 };
739}
740
741#[macro_export]
743macro_rules! T_RELAX(() => { $crate::token::TOKEN_RELAX.clone() });
744
745#[macro_export]
747macro_rules! T_MARKER {
748 ($text:expr_2021) => {
749 Token {
750 text: $crate::common::arena::pin($text),
751 code: Catcode::MARKER,
752 prov: 0,
753 #[cfg(feature = "token-locators")]
754 loc: 0,
755 }
756 };
757}
758
759#[macro_export]
761macro_rules! T_ARG {
762 ($text:expr_2021) => {
763 Token {
764 text: $crate::common::arena::pin($text.to_string()),
765 code: Catcode::ARG,
766 prov: 0,
767 #[cfg(feature = "token-locators")]
768 loc: 0,
769 }
770 };
771}
772
773#[macro_export]
776macro_rules! Token {
777 (sym $sym:expr_2021, $cc:expr_2021) => {
778 Token {
779 text: $sym,
780 code: $cc,
781 prov: 0,
782 #[cfg(feature = "token-locators")]
783 loc: 0,
784 }
785 };
786 ($text:expr_2021) => {
787 Token!($text, Catcode::OTHER)
788 };
789 ($text:literal, $cc:expr_2021) => {
790 Token {
791 text: $crate::pin!($text),
792 code: $cc,
793 prov: 0,
794 #[cfg(feature = "token-locators")]
795 loc: 0,
796 }
797 };
798 ($text:expr_2021, $cc:expr_2021) => {
799 Token {
800 text: $crate::common::arena::pin($text),
801 code: $cc,
802 prov: 0,
803 #[cfg(feature = "token-locators")]
804 loc: 0,
805 }
806 };
807}
808
809#[macro_export]
811macro_rules! CharToken {
812 ($c:expr_2021) => {
813 CharToken!($c, $crate::token::Catcode::OTHER)
814 };
815 ($c:expr_2021, $cc:expr_2021) => {
816 $crate::token::Token {
817 text: $crate::common::arena::pin_char($c),
818 code: $cc,
819 prov: 0,
820 #[cfg(feature = "token-locators")]
821 loc: 0,
822 }
823 };
824}
825
826#[macro_export]
831macro_rules! Explode(($text:expr_2021) => (
832 $text.to_string().chars().map(|c|
833 if c==' ' { T_SPACE!() }
834 else {
835 CharToken!(c)
836 }
837 ).collect::<Vec<Token>>()
838));
839
840#[macro_export]
841macro_rules! ExplodeChars(($text:expr_2021) => (
842 $text.as_str().chars().map(|c|
843 if c==' ' { T_SPACE!() }
844 else {
845 CharToken!(c)
846 }
847 ).collect::<Vec<Token>>()
848));
849
850#[macro_export]
855macro_rules! ExplodeText(
856 ($text:expr_2021) => ({
857 use $crate::token::{Catcode,Token};
858 $text.to_string().chars().map(|c|
859 if c==' ' { T_SPACE!() }
860 else {
861 let mut tmp = [0u8; 4];
862 let s = c.encode_utf8(&mut tmp);
863 if c.is_ascii_alphabetic() {
864 T_LETTER!(s) }
865 else { T_OTHER!(s) }}
866 ).collect::<Vec<Token>>()
867}));
868
869#[macro_export]
870macro_rules! SymExplodeText(
871 ($sym:expr_2021) => ({
872 use $crate::token::{Catcode,Token};
873 let chars : Vec<char> = arena::with($sym, |text| text.chars().collect());
874 chars.into_iter().map(|c|
875 if c==' ' { T_SPACE!() }
876 else {
877 let mut tmp = [0u8; 4];
878 let s = c.encode_utf8(&mut tmp);
879 if c.is_ascii_alphabetic() {
880 T_LETTER!(s) }
881 else { T_OTHER!(s) }}
882 ).collect::<Vec<Token>>()
883}));
884
885impl Default for Token {
888 fn default() -> Self {
889 Token {
890 text: arena::pin_static("EXPECTED_TOKEN"),
891 code: Catcode::OTHER,
892 prov: 0,
893 #[cfg(feature = "token-locators")]
894 loc: 0,
895 }
896 }
897}
898
899pub const FIELD_PROV_POS_BITS: u16 = 14;
903pub const FIELD_PROV_POS_MASK: u16 = (1 << FIELD_PROV_POS_BITS) - 1;
905pub const AUTHOR_PROV_POS_MASK: u16 = (1 << (FIELD_PROV_POS_BITS + 1)) - 1;
909const AUTHOR_PROV: u16 = 1 << (FIELD_PROV_POS_BITS + 1);
910pub fn field_prov(field: u16, pos: usize) -> u16 {
912 if field == 2 {
913 AUTHOR_PROV | (pos.min(AUTHOR_PROV_POS_MASK as usize) as u16)
914 } else {
915 (field << FIELD_PROV_POS_BITS) | (pos.min(FIELD_PROV_POS_MASK as usize) as u16)
916 }
917}
918#[inline]
920pub fn field_prov_field(prov: u16) -> u16 {
921 if prov & AUTHOR_PROV != 0 {
922 2
923 } else {
924 prov >> FIELD_PROV_POS_BITS
925 }
926}
927#[inline]
929pub fn field_prov_pos(prov: u16) -> u16 {
930 if prov & AUTHOR_PROV != 0 {
931 prov & AUTHOR_PROV_POS_MASK
932 } else {
933 prov & FIELD_PROV_POS_MASK
934 }
935}
936
937#[inline]
941pub fn inherit_field_prov(prov: u16, expansion: &mut Tokens) {
942 if prov != 0 {
943 for t in expansion.unlist_mut() {
944 if t.prov == 0 {
945 t.prov = prov;
946 }
947 }
948 }
949}
950
951#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
954pub struct FieldCover {
955 pub field: u16,
957 pub start: u16,
959 pub end: u16,
961}
962
963thread_local! {
964 static FIELD_COVER_PENDING: std::cell::Cell<FieldCover> =
968 const { std::cell::Cell::new(FieldCover { field: 0, start: 0, end: 0 }) };
969}
970
971pub fn field_cover_pending_merge(cover: FieldCover) -> FieldCover {
975 let pending = FIELD_COVER_PENDING.replace(FieldCover::default());
976 if pending.field == cover.field && pending.start <= cover.start && cover.start <= pending.end {
977 FieldCover {
978 field: cover.field,
979 start: pending.start,
980 end: pending.end.max(cover.end),
981 }
982 } else {
983 cover
984 }
985}
986
987pub fn field_cover_set_pending(cover: FieldCover) {
990 let merged = field_cover_pending_merge(cover);
991 FIELD_COVER_PENDING.set(merged);
992}
993
994#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
997pub struct FieldLedgerEntry {
998 pub cover: FieldCover,
1000 pub taken: bool,
1004}
1005
1006thread_local! {
1007 static FIELD_LEDGER: std::cell::RefCell<Vec<FieldLedgerEntry>> =
1012 const { std::cell::RefCell::new(Vec::new()) };
1013}
1014thread_local! {
1015 static FIELD_LEDGER_SETTLED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
1018}
1019const FIELD_LEDGER_CAP: usize = 1 << 16;
1021
1022#[inline]
1024pub fn field_ledger_live() -> bool { !FIELD_LEDGER_SETTLED.get() }
1025
1026pub fn field_ledger_settle() { FIELD_LEDGER_SETTLED.set(true); }
1028
1029pub fn field_ledger_push(cover: FieldCover) -> Option<u32> {
1031 if FIELD_LEDGER_SETTLED.get() {
1032 return None;
1033 }
1034 FIELD_LEDGER.with(|ledger| {
1035 let mut ledger = ledger.borrow_mut();
1036 if ledger.len() >= FIELD_LEDGER_CAP {
1037 return None;
1038 }
1039 ledger.push(FieldLedgerEntry { cover, taken: false });
1040 u32::try_from(ledger.len() - 1).ok()
1041 })
1042}
1043
1044pub fn field_ledger_take(serial: u32) {
1047 FIELD_LEDGER.with(|ledger| {
1048 if let Some(entry) = ledger.borrow_mut().get_mut(serial as usize) {
1049 entry.taken = true;
1050 }
1051 });
1052}
1053
1054pub fn field_ledger_cover(field: u16, serials: &[(u32, u32)]) -> Vec<(u16, u16)> {
1057 let mut cover: Vec<(u16, u16)> = FIELD_LEDGER.with(|ledger| {
1058 let ledger = ledger.borrow();
1059 let mut cover = Vec::new();
1060 for &(first, last) in serials {
1061 let (first, last) = (first as usize, last as usize);
1062 if first > last || first >= ledger.len() {
1063 continue;
1064 }
1065 cover.extend(
1066 ledger[first..=last.min(ledger.len() - 1)]
1067 .iter()
1068 .filter(|e| e.cover.field == field)
1069 .map(|e| (e.cover.start, e.cover.end.max(e.cover.start + 1))),
1070 );
1071 }
1072 cover
1073 });
1074 cover.sort_unstable();
1075 let mut merged: Vec<(u16, u16)> = Vec::with_capacity(cover.len());
1076 for (start, end) in cover {
1077 match merged.last_mut() {
1078 Some((_, e)) if start <= *e => *e = (*e).max(end),
1079 _ => merged.push((start, end)),
1080 }
1081 }
1082 merged
1083}
1084
1085pub fn field_ledger_entry(serial: u32) -> Option<FieldLedgerEntry> {
1087 FIELD_LEDGER.with(|ledger| ledger.borrow().get(serial as usize).copied())
1088}
1089
1090pub struct FieldLedgerScope {
1104 len: usize,
1105 pending: FieldCover,
1106 settled: bool,
1107 stamped: bool,
1108 outer: Option<Vec<Digested>>,
1110}
1111
1112pub type FieldNotesHook = fn(&Token, FieldCover, FieldInvocation<'_>);
1117
1118#[derive(Clone, Copy)]
1120pub enum FieldInvocation<'a> {
1121 Digested(&'a [Digested]),
1123 Expanded(&'a Tokens),
1125}
1126thread_local! {
1127 static FIELD_NOTES_HOOK: std::cell::Cell<Option<FieldNotesHook>> =
1128 const { std::cell::Cell::new(None) };
1129}
1130
1131pub fn set_field_notes_hook(hook: Option<FieldNotesHook>) { FIELD_NOTES_HOOK.set(hook); }
1133
1134#[inline]
1136pub fn field_notes_hook() -> Option<FieldNotesHook> { FIELD_NOTES_HOOK.get() }
1137
1138pub fn field_cover_pending() -> FieldCover { FIELD_COVER_PENDING.get() }
1140
1141thread_local! {
1142 static FIELD_STAMPED_BOXES: std::cell::RefCell<Option<Vec<Digested>>> =
1144 const { std::cell::RefCell::new(None) };
1145}
1146
1147pub(crate) fn field_stamp_noted(digested: &Digested) {
1150 FIELD_STAMPED_BOXES.with(|boxes| {
1151 if let Some(boxes) = boxes.borrow_mut().as_mut() {
1152 boxes.push(digested.clone());
1153 }
1154 });
1155}
1156
1157impl FieldLedgerScope {
1158 pub fn begin() -> Self {
1160 let len = FIELD_LEDGER.with(|ledger| ledger.borrow().len());
1161 FieldLedgerScope {
1162 len,
1163 pending: FIELD_COVER_PENDING.replace(FieldCover::default()),
1164 settled: FIELD_LEDGER_SETTLED.replace(false),
1165 stamped: crate::document::field_prov_stamped(),
1166 outer: FIELD_STAMPED_BOXES.with(|boxes| boxes.replace(Some(Vec::new()))),
1167 }
1168 }
1169}
1170
1171impl Drop for FieldLedgerScope {
1172 fn drop(&mut self) {
1173 FIELD_LEDGER.with(|ledger| ledger.borrow_mut().truncate(self.len));
1174 FIELD_COVER_PENDING.set(self.pending);
1175 FIELD_LEDGER_SETTLED.set(self.settled);
1176 crate::document::restore_field_prov_stamped(self.stamped);
1177 let stamped = FIELD_STAMPED_BOXES.with(|boxes| boxes.replace(self.outer.take()));
1178 for digested in stamped.into_iter().flatten() {
1179 digested.try_remove_property(crate::document::FIELD_PROV_PROPERTY);
1180 digested.try_remove_property(crate::document::FIELD_SERIAL_PROPERTY);
1181 }
1182 }
1183}
1184
1185pub fn reset_field_cover_pending() {
1187 FIELD_COVER_PENDING.set(FieldCover::default());
1188 FIELD_LEDGER.with(|ledger| ledger.borrow_mut().clear());
1189 FIELD_LEDGER_SETTLED.set(false);
1190}
1191
1192impl Token {
1193 pub fn new<T: AsRef<str>>(text: T, code: Catcode) -> Self {
1195 Self::from_sym(arena::pin(text), code)
1196 }
1197
1198 #[inline]
1201 pub fn from_sym(text: SymStr, code: Catcode) -> Self {
1202 Token {
1203 text,
1204 code,
1205 prov: 0,
1206 #[cfg(feature = "token-locators")]
1207 loc: 0,
1208 }
1209 }
1210
1211 #[inline]
1214 pub fn try_cs<T: AsRef<str>>(text: T) -> Option<Self> {
1215 arena::get(text).map(|text| Token { text, ..T_CS!("\\relax") })
1216 }
1217
1218 #[inline]
1223 pub fn cycle_fingerprint(&self) -> u64 {
1224 use std::hash::{Hash, Hasher};
1225 let mut h = rustc_hash::FxHasher::default();
1226 self.code.hash(&mut h);
1227 if self.code != Catcode::SPACE {
1228 self.text.hash(&mut h);
1229 }
1230 h.finish()
1231 }
1232
1233 pub fn get_cs_name(&self) -> SymStr {
1236 if self.code.is_primitive() {
1237 self.code.name_sym()
1238 } else {
1239 self.get_sym()
1240 }
1241 }
1242
1243 pub fn with_cs_name<R, FnR>(&self, caller: FnR) -> R
1247 where FnR: FnOnce(&str) -> R {
1248 if self.code.is_primitive() {
1249 caller(self.code.name())
1250 } else {
1251 self.with_str(caller)
1252 }
1253 }
1254
1255 pub fn pin_cs_name(&self) -> SymStr {
1257 if self.code.is_primitive() {
1258 self.code.name_sym()
1259 } else {
1260 self.get_sym()
1261 }
1262 }
1263
1264 pub fn get_primitive_name(&self) -> Option<&'static str> {
1266 if self.code.is_primitive() {
1267 Some(self.code.name())
1268 } else {
1269 None
1270 }
1271 }
1272
1273 pub fn get_executable_name(&self) -> String {
1275 let cc = self.code;
1276 if cc.is_executable() {
1277 self
1278 .get_primitive_name()
1279 .map(ToString::to_string)
1280 .unwrap_or_else(|| self.with_str(|text| text.to_string()))
1281 } else {
1282 String::new()
1283 }
1284 }
1285
1286 pub fn get_executable_primitive_name(&self) -> Option<&'static str> {
1288 let cc = self.code;
1289 if cc.is_executable() && cc.is_primitive() {
1290 Some(self.code.name())
1291 } else {
1292 None
1293 }
1294 }
1295
1296 pub fn get_sym(&self) -> SymStr { self.text }
1298 pub fn with_str<R, FnR>(&self, caller: FnR) -> R
1301 where FnR: FnOnce(&str) -> R {
1302 arena::with(self.text, caller)
1303 }
1304
1305 #[inline]
1315 pub fn is_noexpand_family(&self) -> bool {
1316 self.code == Catcode::CS && self.names_noexpand_family()
1317 }
1318
1319 fn names_noexpand_family(&self) -> bool {
1321 use string_interner::Symbol;
1329 let idx = self.text.to_usize();
1330 if idx < NOEXPAND_MEMO_SPAN {
1331 let cached = NOEXPAND_FAMILY_MEMO.with(|memo| memo.borrow().get(idx).copied().unwrap_or(0));
1332 if cached != 0 {
1333 return cached == 2;
1334 }
1335 }
1336 self.read_noexpand_family(idx)
1337 }
1338
1339 #[cold]
1342 #[inline(never)]
1343 fn read_noexpand_family(&self, idx: usize) -> bool {
1344 let is_family = self.with_str(|s| {
1345 s.starts_with(NOEXPAND_PREFIX)
1346 && (s.len() == NOEXPAND_PREFIX.len() || s.as_bytes()[NOEXPAND_PREFIX.len()] == NOEXPAND_SEP)
1347 });
1348 if idx < NOEXPAND_MEMO_SPAN {
1349 NOEXPAND_FAMILY_MEMO.with(|memo| {
1350 let mut memo = memo.borrow_mut();
1351 if memo.len() <= idx {
1352 memo.resize(idx + 1, 0);
1353 }
1354 memo[idx] = if is_family { 2 } else { 1 };
1355 });
1356 }
1357 is_family
1358 }
1359
1360 #[inline]
1364 pub fn noexpand_shadowed(&self) -> Option<Token> {
1365 if self.is_noexpand_family() {
1366 self.shadowed_by_noexpand()
1367 } else {
1368 None
1369 }
1370 }
1371
1372 #[cold]
1374 #[inline(never)]
1375 fn shadowed_by_noexpand(&self) -> Option<Token> {
1376 let (name, code) = self.with_str(|s| {
1380 let rest = s.strip_prefix(NOEXPAND_PREFIX)?;
1381 let rest = rest.strip_prefix(NOEXPAND_SEP as char)?;
1382 let code = if rest.starts_with('\\') {
1383 Catcode::CS
1384 } else {
1385 Catcode::ACTIVE
1386 };
1387 Some((rest.to_string(), code))
1388 })?;
1389 Some(Token {
1390 text: arena::pin(name),
1391 code,
1392 prov: 0,
1393 #[cfg(feature = "token-locators")]
1394 loc: 0,
1395 })
1396 }
1397
1398 pub fn get_charcode(&self) -> u32 {
1410 if self.code == Catcode::CS {
1411 256
1412 } else if self.code == Catcode::SPACE {
1413 32
1414 } else {
1415 self.with_str(|text| {
1416 if let Some(c) = text.chars().next() {
1417 c as u32
1418 } else {
1419 0
1420 }
1421 })
1422 }
1423 }
1424
1425 pub fn group_step(&self) -> i32 {
1428 match self.get_catcode() {
1429 Catcode::BEGIN => 1,
1430 Catcode::END => -1,
1431 _ => 0,
1432 }
1433 }
1434
1435 pub fn get_catcode(&self) -> Catcode { self.code }
1437 pub fn is_executable(&self) -> bool { self.code.is_executable() }
1439 pub fn is_active_or_cs(&self) -> bool { self.code.is_active_or_cs() }
1441
1442 pub fn neutralize(self, extraspecials: &[char]) -> Token {
1449 let first_c: Option<char> = self.with_str(|text| text.chars().next());
1450 let ch = match first_c {
1451 Some(ch) => ch,
1452 None => return self,
1453 };
1454 let cc = self.code;
1455 if cc.is_neutralizable() {
1456 for extra in extraspecials {
1457 if extra == &ch {
1458 let mut tmp = [0u8; 4];
1459 let s = ch.encode_utf8(&mut tmp);
1460 return T_OTHER!(s);
1461 }
1462 }
1463 let maybe_return = state::with_value("SPECIALS", |specials_opt| {
1464 if let Some(Stored::Chars(specials_list)) = specials_opt {
1465 for special in specials_list.iter() {
1466 if *special == ch {
1467 let mut tmp = [0u8; 4];
1468 let s = ch.encode_utf8(&mut tmp);
1469 return Some(T_OTHER!(s));
1470 }
1471 }
1472 }
1473 None
1474 });
1475 if let Some(token) = maybe_return {
1476 return token;
1477 }
1478 }
1479 self
1480 }
1481
1482 pub fn as_other(&self) -> Token {
1483 Token {
1484 text: self.text,
1485 code: Catcode::OTHER,
1486 prov: 0,
1487 #[cfg(feature = "token-locators")]
1488 loc: 0,
1489 }
1490 }
1491 pub fn as_cs(&self) -> Token {
1492 Token {
1493 text: self.text,
1494 code: Catcode::CS,
1495 prov: 0,
1496 #[cfg(feature = "token-locators")]
1497 loc: 0,
1498 }
1499 }
1500
1501 pub fn substitute_parameters(self, args: &[&Token]) -> Self {
1502 if self.code == Catcode::ARG {
1503 self.with_str(|text| {
1504 let arg_idx = text
1505 .parse::<usize>()
1506 .expect("ARG catcode tokens should always contain numeric literals as text");
1507 *args[arg_idx - 1]
1508 })
1509 } else {
1510 self
1511 }
1512 }
1513
1514 pub fn revert(self) -> Token { self }
1516
1517 pub fn stringify(&self) -> String {
1519 self.with_str(|text| {
1520 let display_text = if text.len() == 1 {
1522 let c = text.chars().next().unwrap() as u16;
1523 if c < 0x020 {
1524 Cow::Owned(s!("U+{:04x}/{}", c, CONTROLNAME[c as usize]))
1525 } else {
1526 Cow::Borrowed(text)
1527 }
1528 } else {
1529 Cow::Borrowed(text)
1530 };
1531 s!("{}[{}]", self.code.short_name(), display_text)
1532 })
1533 }
1534
1535 pub fn to_register(&self) -> Option<Rc<Register>> { state::lookup_register_definition(self) }
1536
1537 pub fn to_number(&self) -> Number {
1538 Number::new(self.with_str(|text| text.parse::<i64>()).unwrap_or(0))
1539 }
1540
1541 pub fn to_dimension(&self) -> Dimension {
1542 Dimension::new_f64(self.with_str(|text| text.parse::<f64>().unwrap_or(0.0)))
1543 }
1544
1545 pub fn to_mu_dimension(&self) -> MuDimension {
1546 MuDimension::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1547 }
1548
1549 pub fn to_glue(&self) -> Glue {
1550 Glue::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1551 }
1552
1553 pub fn to_mu_glue(&self) -> MuGlue {
1554 MuGlue::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1555 }
1556
1557 pub fn to_float(&self) -> Float {
1558 Float::new_f64(self.with_str(|s| s.parse::<f64>()).unwrap_or(0.0))
1559 }
1560
1561 pub fn be_digested(self) -> Result<Digested> { crate::stomach::digest(Tokens::new(vec![self])) }
1562
1563 pub fn defined_as(&self, other: &Token) -> bool {
1568 self.spelled_as(other)
1569 || self
1570 .meaning_name()
1571 .is_some_and(|letto| letto.spelled_as(other))
1572 }
1573
1574 #[inline]
1577 pub fn spelled_as(&self, other: &Token) -> bool {
1578 self.code == other.code && (other.code == Catcode::SPACE || self.text == other.text)
1579 }
1580
1581 #[inline]
1584 pub fn meaning_name(&self) -> Option<Token> { self.with_meaning_name(|named, _| named) }
1585
1586 pub fn with_meaning_name<R>(&self, f: impl FnOnce(Option<Token>, Option<&Stored>) -> R) -> R {
1590 if !matches!(self.code, Catcode::CS | Catcode::ACTIVE) {
1591 return f(None, None);
1592 }
1593 state::with_meaning(self, |defn_opt| {
1599 let named = defn_opt.and_then(|defn| match defn {
1600 Stored::Token(t) => Some(*t),
1601 Stored::Expandable(inner) => Some(*inner.get_cs()),
1602 Stored::Primitive(inner) => Some(*inner.get_cs()),
1603 Stored::MathPrimitive(inner) => Some(*inner.get_cs()),
1604 Stored::Register(inner) => Some(*inner.get_cs()),
1605 Stored::Conditional(inner) => Some(*inner.get_cs()),
1606 Stored::Constructor(inner) => Some(*inner.get_cs()),
1607 _ => None,
1608 });
1609 f(named, defn_opt)
1610 })
1611 }
1612}
1613
1614impl From<&str> for Token {
1617 fn from(text: &str) -> Token {
1618 match text.chars().next() {
1619 Some('{') => T_BEGIN!(),
1620 Some('}') => T_END!(),
1621 Some('$') => T_MATH!(),
1622 Some('#') => T_PARAM!(),
1623 Some('&') => T_ALIGN!(),
1624 Some('^') => T_SUPER!(),
1625 Some('_') => T_SUB!(),
1626 Some('\\') => T_CS!(text),
1627 Some('%') => T_COMMENT!(text),
1628 _ => {
1629 if text.chars().all(|c| c.is_ascii_whitespace()) {
1637 T_SPACE!()
1638 } else {
1639 T_OTHER!(text)
1640 }
1641 },
1642 }
1643 }
1644}
1645
1646#[cfg(feature = "token-locators")]
1653#[derive(Clone, Copy, Debug)]
1654pub struct TokenStart {
1655 pub source: SymStr,
1656 pub line: u32,
1657 pub col: u32,
1658 pub inherited: bool,
1667}
1668
1669#[cfg(feature = "token-locators")]
1670thread_local! {
1671 static TOKEN_ORIGINS: std::cell::RefCell<Vec<TokenStart>> =
1672 const { std::cell::RefCell::new(Vec::new()) };
1673}
1674
1675#[cfg(feature = "token-locators")]
1678pub fn push_token_origin(source: SymStr, line: u32, col: u32) -> u32 {
1679 TOKEN_ORIGINS.with(|o| {
1680 let mut v = o.borrow_mut();
1681 v.push(TokenStart {
1682 source,
1683 line,
1684 col,
1685 inherited: false,
1686 });
1687 v.len() as u32 })
1689}
1690
1691#[cfg(feature = "token-locators")]
1697pub fn push_inherited_origin(handle: u32) -> u32 {
1698 if handle == 0 {
1699 return 0;
1700 }
1701 TOKEN_ORIGINS.with(|o| {
1702 let mut v = o.borrow_mut();
1703 let Some(mut start) = v.get((handle - 1) as usize).copied() else {
1704 return 0;
1705 };
1706 start.inherited = true;
1707 v.push(start);
1708 v.len() as u32
1709 })
1710}
1711
1712#[cfg(feature = "token-locators")]
1715pub fn get_token_origin(handle: u32) -> Option<TokenStart> {
1716 if handle == 0 {
1717 return None;
1718 }
1719 TOKEN_ORIGINS.with(|o| o.borrow().get((handle - 1) as usize).copied())
1720}
1721
1722#[cfg(feature = "token-locators")]
1724pub fn clear_token_origins() { TOKEN_ORIGINS.with(|o| o.borrow_mut().clear()); }
1725
1726#[cfg(test)]
1727mod tests {
1728 use super::*;
1729
1730 #[test]
1737 fn noexpand_memo_stays_within_its_span() {
1738 std::thread::spawn(|| {
1739 let early = T_CS!(NOEXPAND_PREFIX);
1740 assert!(early.is_noexpand_family());
1741 let _bulk = arena::pin("x".repeat(NOEXPAND_MEMO_SPAN + (1 << 20)));
1742 let late_family = T_CS!(format!("{NOEXPAND_PREFIX}{}\\foo", NOEXPAND_SEP as char));
1743 let late_other = T_CS!("\\noexpandmemoprobe");
1744 assert!(early.is_noexpand_family());
1745 assert!(late_family.is_noexpand_family());
1746 assert!(!late_other.is_noexpand_family());
1747 let len = NOEXPAND_FAMILY_MEMO.with(|memo| memo.borrow().len());
1748 assert!(len <= NOEXPAND_MEMO_SPAN, "memo grew to {len} bytes");
1749 reset_noexpand_family_memo();
1750 arena::reset();
1751 })
1752 .join()
1753 .unwrap();
1754 }
1755
1756 #[test]
1761 fn token_size_invariant() {
1762 #[cfg(not(feature = "token-locators"))]
1763 assert_eq!(
1764 size_of::<Token>(),
1765 8,
1766 "default Token must stay 8 bytes (SymStr + Catcode + prov)"
1767 );
1768 #[cfg(feature = "token-locators")]
1769 assert_eq!(
1770 std::mem::size_of::<Token>(),
1771 12,
1772 "token-locators Token is 8 + a u32 origin handle"
1773 );
1774 }
1775
1776 #[test]
1780 fn field_ledger_take_cover_and_settle() {
1781 reset_field_cover_pending();
1782 let cover = |start, end| FieldCover { field: 1, start, end };
1783 let a = field_ledger_push(cover(0, 5)).unwrap();
1784 let unused = field_ledger_push(cover(5, 9)).unwrap();
1785 let marker = field_ledger_push(cover(9, 10)).unwrap();
1786 field_ledger_take(marker);
1787 assert!(field_ledger_entry(marker).is_some_and(|e| e.taken));
1788 assert!(field_ledger_entry(unused).is_some_and(|e| !e.taken));
1789 assert_eq!(field_ledger_cover(1, &[(a, a)]), vec![(0, 5)]);
1790 assert_eq!(field_ledger_cover(1, &[(a, a), (marker, marker)]), vec![
1791 (0, 5),
1792 (9, 10)
1793 ]);
1794 assert!(field_ledger_live());
1795 field_ledger_settle();
1796 assert!(!field_ledger_live());
1797 assert_eq!(field_ledger_push(cover(10, 11)), None);
1798 reset_field_cover_pending();
1799 assert!(field_ledger_live());
1800 assert_eq!(field_ledger_entry(a), None);
1801 }
1802
1803 #[test]
1809 fn token_layout_code_at_byte_4() {
1810 assert_eq!(std::mem::offset_of!(Token, text), 0);
1811 assert_eq!(
1812 std::mem::offset_of!(Token, code),
1813 4,
1814 "Token.code must sit at byte 4 (read-path codegen)"
1815 );
1816 assert_eq!(
1817 size_of::<Catcode>(),
1818 2,
1819 "Catcode fills bytes 4-5: no pad byte before prov"
1820 );
1821 assert_eq!(std::mem::offset_of!(Token, prov), 6);
1822 #[cfg(feature = "token-locators")]
1823 assert_eq!(std::mem::offset_of!(Token, loc), 8);
1824 assert_eq!(
1825 size_of::<Option<Token>>(),
1826 size_of::<Token>(),
1827 "Option<Token> keeps its niche"
1828 );
1829 }
1830
1831 #[cfg(feature = "token-locators")]
1837 #[test]
1838 fn token_origin_capture() {
1839 super::clear_token_origins();
1840 let toks = crate::mouth::tokenize("Hello");
1842 let got: Vec<(u32, u32)> = toks
1843 .unlist_ref()
1844 .iter()
1845 .map(|t| {
1846 let o = super::get_token_origin(t.loc).expect("token carries an origin handle");
1847 (o.line, o.col)
1848 })
1849 .collect();
1850 assert_eq!(
1851 got,
1852 vec![(1, 1), (1, 2), (1, 3), (1, 4), (1, 5)],
1853 "each letter's captured (line, col) must be exact"
1854 );
1855 }
1856
1857 #[test]
1858 fn catcode_name_covers_all_variants() {
1859 use Catcode::*;
1861 for cc in [
1862 ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1863 ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1864 ] {
1865 assert!(!cc.name().is_empty(), "{cc:?}.name() is empty");
1866 }
1867 }
1868
1869 #[test]
1870 fn catcode_name_specific_values() {
1871 assert_eq!(Catcode::ESCAPE.name(), "Escape");
1872 assert_eq!(Catcode::BEGIN.name(), "Begin");
1873 assert_eq!(Catcode::CS.name(), "ControlSequence");
1874 assert_eq!(Catcode::LETTER.name(), "Letter");
1875 }
1876
1877 #[test]
1878 fn catcode_short_name_starts_with_t_prefix() {
1879 use Catcode::*;
1880 for cc in [
1881 ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1882 ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1883 ] {
1884 assert!(
1885 cc.short_name().starts_with("T_"),
1886 "{cc:?}.short_name() = {} lacks T_ prefix",
1887 cc.short_name()
1888 );
1889 }
1890 }
1891
1892 #[test]
1893 fn catcode_meaning_mostly_nonempty() {
1894 assert!(!Catcode::ESCAPE.meaning().is_empty());
1896 assert!(!Catcode::LETTER.meaning().is_empty());
1897 assert!(!Catcode::OTHER.meaning().is_empty());
1898 assert_eq!(Catcode::CS.meaning(), "");
1900 }
1901
1902 #[test]
1903 fn is_primitive_checks() {
1904 use Catcode::*;
1905 for cc in [
1907 ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE,
1908 ] {
1909 assert!(cc.is_primitive(), "{cc:?} should be primitive");
1910 }
1911 for cc in [
1913 IGNORE, LETTER, OTHER, ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1914 ] {
1915 assert!(!cc.is_primitive(), "{cc:?} should not be primitive");
1916 }
1917 }
1918
1919 #[test]
1920 fn is_executable_checks() {
1921 use Catcode::*;
1922 for cc in [BEGIN, END, MATH, ALIGN, SUPER, SUB, ACTIVE, CS] {
1923 assert!(cc.is_executable(), "{cc:?} should be executable");
1924 }
1925 for cc in [
1926 EOL, ESCAPE, PARAM, SPACE, IGNORE, LETTER, OTHER, COMMENT, INVALID, MARKER, ARG,
1927 ] {
1928 assert!(!cc.is_executable(), "{cc:?} should not be executable");
1929 }
1930 }
1931
1932 #[test]
1933 fn is_neutralizable_set() {
1934 use Catcode::*;
1935 for cc in [MATH, ALIGN, PARAM, SUPER, SUB, ACTIVE] {
1936 assert!(cc.is_neutralizable(), "{cc:?}");
1937 }
1938 assert!(!CS.is_neutralizable());
1939 assert!(!LETTER.is_neutralizable());
1940 }
1941
1942 #[test]
1943 fn is_active_or_cs_narrow_set() {
1944 assert!(Catcode::ACTIVE.is_active_or_cs());
1945 assert!(Catcode::CS.is_active_or_cs());
1946 assert!(!Catcode::LETTER.is_active_or_cs());
1947 assert!(!Catcode::ESCAPE.is_active_or_cs());
1948 }
1949
1950 #[test]
1951 fn is_absorbable_space_letter_other_comment() {
1952 use Catcode::*;
1953 assert!(SPACE.is_absorbable());
1954 assert!(LETTER.is_absorbable());
1955 assert!(OTHER.is_absorbable());
1956 assert!(COMMENT.is_absorbable());
1957 assert!(!CS.is_absorbable());
1959 assert!(!BEGIN.is_absorbable());
1960 }
1961
1962 #[test]
1963 fn is_gullet_holdable_comment_marker_only() {
1964 assert!(Catcode::COMMENT.is_gullet_holdable());
1965 assert!(Catcode::MARKER.is_gullet_holdable());
1966 assert!(!Catcode::SPACE.is_gullet_holdable());
1967 assert!(!Catcode::LETTER.is_gullet_holdable());
1968 }
1969
1970 #[test]
1971 fn is_balanced_interesting_begin_end_marker() {
1972 assert!(Catcode::BEGIN.is_balanced_interesting());
1973 assert!(Catcode::END.is_balanced_interesting());
1974 assert!(Catcode::MARKER.is_balanced_interesting());
1975 assert!(!Catcode::LETTER.is_balanced_interesting());
1976 assert!(!Catcode::MATH.is_balanced_interesting());
1977 }
1978
1979 #[test]
1980 fn catcode_u8_roundtrip() {
1981 use Catcode::*;
1984 for cc in [
1985 ESCAPE, BEGIN, END, MATH, ALIGN, EOL, PARAM, SUPER, SUB, SPACE, IGNORE, LETTER, OTHER,
1986 ACTIVE, COMMENT, INVALID, CS, MARKER, ARG,
1987 ] {
1988 let b: u8 = cc.into();
1989 let cc2: Catcode = b.into();
1990 assert_eq!(cc, cc2, "roundtrip broke for {cc:?} (u8={b})");
1991 }
1992 }
1993
1994 #[test]
1995 fn token_new_and_display() {
1996 let t = Token::new("foo", Catcode::LETTER);
1997 assert_eq!(format!("{t}"), "foo");
1998 assert_eq!(t.code, Catcode::LETTER);
1999 }
2000
2001 #[test]
2002 fn token_arg_display_prepends_hash() {
2003 let t = Token::new("1", Catcode::ARG);
2005 assert_eq!(format!("{t}"), "#1");
2006 }
2007}
2008
2009#[cfg(test)]
2010mod charcode_tests {
2011 use super::{Catcode, Token};
2012
2013 #[test]
2016 fn end_of_line_space_has_character_code_32() {
2017 assert_eq!(Token::new("\n", Catcode::SPACE).get_charcode(), 32);
2018 assert_eq!(Token::new(" ", Catcode::SPACE).get_charcode(), 32);
2019 assert_eq!(Token::new("A", Catcode::LETTER).get_charcode(), 65);
2020 }
2021}