1use std::{borrow::Cow, fmt};
2
3use libxml::tree::Node;
4
5use crate::{
6 Digested,
7 common::{error::*, locator::Locator, object::Object},
8 definition::{
9 BeforeDigestClosure, Definition, DigestionClosure, ExpansionBody, argument::ArgWrap,
10 },
11 state::*,
12};
13
14pub fn protect_is_typeset() -> bool {
30 let protect = lookup_meaning(&T_CS!("\\protect"));
31 let typeset = lookup_meaning(&T_CS!("\\@typeset@protect"));
32 match (protect, typeset) {
33 (Some(p), Some(t)) => p == t,
34 _ => true,
37 }
38}
39
40pub(crate) fn protect_is_relax_or_undefined() -> bool {
41 let protect = T_CS!("\\protect");
42 match lookup_meaning(&protect) {
43 None => true,
44 Some(stored) => match lookup_meaning(&T_CS!("\\relax")) {
46 None => false,
47 Some(relax) => stored == relax,
48 },
49 }
50}
51use crate::{
52 document::Document,
53 parameter::Parameters,
54 token::*,
55 tokens::{BodyPiece, NO_TOKENS, Tokens},
56 whatsit::Whatsit,
57};
58
59#[derive(Debug, Clone, Default)]
60pub struct ExpandableOptions {
61 pub locked: bool,
62 pub protected: bool,
63 pub outer: bool,
64 pub long: bool,
65 pub scope: Option<Scope>,
66 pub alias: Option<String>,
67 pub mathactive: bool,
68 pub robust: bool,
69 pub nopack_parameters: bool,
70 pub peeks_by_futurelet: bool,
72 pub tex_declared: bool,
75 pub short: bool,
79 pub extends: bool,
83 pub drops: &'static [u8],
88}
89
90pub type NativeCall = fn() -> Result<Option<Tokens>>;
92
93thread_local! {
94 static NATIVE_CALL: std::cell::Cell<Option<NativeCall>> = const { std::cell::Cell::new(None) };
97}
98
99pub fn set_native_call(native: NativeCall) { NATIVE_CALL.with(|call| call.set(Some(native))); }
101
102#[cold]
103fn native_call() -> Result<Option<Tokens>> {
104 match NATIVE_CALL.with(std::cell::Cell::get) {
105 Some(native) => native(),
106 None => Ok(None),
107 }
108}
109
110#[derive(Clone, Copy, Default)]
112pub enum SpecialCall {
113 #[default]
114 None,
115 YieldsCalls,
119 Native,
125}
126
127#[derive(Clone)]
128pub struct Expandable {
129 pub is_protected: bool,
130 pub peeks_by_futurelet: bool,
134 pub is_long: bool,
135 pub checks_par: bool,
141 pub is_outer: bool,
142 pub has_cc_arg: bool,
143 pub alias: Option<String>,
144 pub locator: Locator,
145 pub cs: Token,
146 pub paramlist: Option<Parameters>,
147 pub expansion: Option<ExpansionBody>,
148 pub origin: crate::definition::origin::DefinitionOrigin,
149 pub special_call: SpecialCall,
151 pub plan: std::cell::OnceCell<Box<[BodyPiece]>>,
153 pub dropped_by_design: u16,
156 pub made_in_own_file: bool,
160 pub stored: std::cell::OnceCell<Box<StoredParameters>>,
162}
163
164impl fmt::Debug for Expandable {
166 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
167 f.debug_struct("Expandable")
168 .field("is_protected", &self.is_protected)
169 .field("peeks_by_futurelet", &self.peeks_by_futurelet)
170 .field("is_long", &self.is_long)
171 .field("checks_par", &self.checks_par)
172 .field("is_outer", &self.is_outer)
173 .field("has_cc_arg", &self.has_cc_arg)
174 .field("alias", &self.alias)
175 .field("locator", &self.locator)
176 .field("cs", &self.cs)
177 .field("paramlist", &self.paramlist)
178 .field("expansion", &self.expansion)
179 .field("origin", &self.origin)
180 .field("yields_calls", &self.yields_calls())
181 .field("plan", &self.plan)
182 .field("dropped_by_design", &self.dropped_by_design)
183 .field("made_in_own_file", &self.made_in_own_file)
184 .field("stored", &self.stored)
185 .finish()
186 }
187}
188
189impl Default for Expandable {
190 fn default() -> Self {
191 Expandable {
192 is_protected: false,
193 peeks_by_futurelet: false,
194 is_long: false,
195 checks_par: false,
196 is_outer: false,
197 has_cc_arg: false,
198 alias: None,
199 locator: Locator::default(),
200 cs: T_CS!("Expandable"),
201 paramlist: None,
202 expansion: None,
203 origin: crate::definition::origin::current_origin(),
204 special_call: SpecialCall::None,
205 plan: std::cell::OnceCell::new(),
206 made_in_own_file: false,
207 stored: std::cell::OnceCell::new(),
208 dropped_by_design: 0,
209 }
210 }
211}
212impl PartialEq for Expandable {
213 fn eq(&self, other: &Expandable) -> bool {
214 self.paramlist == other.paramlist && self.expansion == other.expansion
215 }
216}
217
218impl Object for Expandable {
224 fn is_definition(&self) -> bool { true }
225 fn is_expandable(&self) -> bool { true }
226 fn get_locator(&self) -> Option<Locator> { Some(self.locator) }
227 fn get_origin(&self) -> crate::definition::origin::DefinitionOrigin { self.origin }
228 fn stringify(&self) -> String { <Self as Definition>::stringify_type(self, "Expandable") }
229}
230impl Definition for Expandable {
231 fn is_protected(&self) -> bool { self.is_protected }
232 fn peeks_by_futurelet(&self) -> bool { self.peeks_by_futurelet }
233 fn get_parameters(&self) -> Option<&Parameters> { self.paramlist.as_ref() }
234 fn get_num_args(&self) -> usize {
235 match self.paramlist {
236 Some(ref params) => params.get_num_args(),
237 None => 0,
238 }
239 }
240 fn get_cs(&self) -> Cow<'_, Token> { Cow::Borrowed(&self.cs) }
241 fn get_cs_name(&self) -> Cow<'_, str> {
242 match self.alias {
243 Some(ref alias) => Cow::Borrowed(alias),
244 None => Cow::Owned(self.cs.with_cs_name(ToString::to_string)),
245 }
246 }
247 fn get_expansion(&self) -> Option<&ExpansionBody> { self.expansion.as_ref() }
255 fn get_alias(&self) -> Option<&String> { self.alias.as_ref() }
256
257 fn invoke(&self, once_only: bool) -> Result<Tokens> {
259 if self.may_be_watched()
260 && let Some(watched) = self.watched_call()
261 {
262 return self.expand_watched(once_only, watched);
263 }
264 self.expand(once_only)
265 }
266
267 fn invoke_onto_input(&self, once_only: bool) -> Result<()> {
272 if self.may_be_watched()
273 && let Some(watched) = self.watched_call()
274 {
275 crate::gullet::unread_expansion(self.expand_watched(once_only, watched)?);
276 return Ok(());
277 }
278 if let Some(call) = self.testopt_call()? {
279 crate::gullet::unread_expansion(call);
280 return Ok(());
281 }
282 match self.special_call {
283 SpecialCall::None => {},
284 SpecialCall::YieldsCalls => {
285 if let Some(owner) = self.call_owner()? {
286 crate::gullet::unread_expansion(Tokens!(owner));
287 return Ok(());
288 }
289 },
290 SpecialCall::Native => {
291 if let Some(expansion) = native_call()? {
292 crate::gullet::unread_expansion(expansion);
293 return Ok(());
294 }
295 },
296 }
297 let Some(ExpansionBody::Tokens(tokens)) = &self.expansion else {
298 crate::gullet::unread_expansion(self.invoke(once_only)?);
299 return Ok(());
300 };
301 let Some(parms) = &self.paramlist else {
302 let body = self.parameterless_body(tokens, once_only)?;
303 crate::gullet::unread_substituted(body, &[BodyPiece::Run(0, body.len() as u32)], &[]);
304 return Ok(());
305 };
306 let Some(args) = self.read_call_arguments(parms)? else {
309 return Ok(());
310 };
311 if !self.has_cc_arg {
312 crate::gullet::unread_substituted(
313 tokens.unlist_ref(),
314 &[BodyPiece::Run(0, tokens.len() as u32)],
315 &[],
316 );
317 return Ok(());
318 }
319 self.substitute_onto_input(tokens, &args)
320 }
321
322 fn native_expansion(&self) -> Result<Option<Tokens>> {
323 match self.special_call {
324 SpecialCall::Native => native_call(),
325 _ => Ok(None),
326 }
327 }
328
329 fn invoke_primitive(&self) -> Result<Vec<Digested>> { Ok(Vec::new()) }
331 fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { None }
332 fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { None }
333 fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>> {
334 fatal!(
335 Definition,
336 Unexpected,
337 "do_absorption on Expandable should never be called!"
338 );
339 }
340}
341
342#[derive(Clone, Copy)]
344struct WatchedCall {
345 recorded: bool,
347 dropping: bool,
350 stored: bool,
353}
354
355impl Expandable {
356 #[inline(always)]
359 fn may_be_watched(&self) -> bool {
360 crate::definition::origin::call_watch().is_some_and(|only_owned_with_parameters| {
361 !only_owned_with_parameters
362 || (self.paramlist.is_some() && (self.made_in_own_file || self.origin.is_latexml_owned()))
363 })
364 }
365
366 fn testopt_call(&self) -> Result<Option<Tokens>> {
374 if !self.peeks_by_futurelet {
375 return Ok(None);
376 }
377 let Some(param) = self
378 .paramlist
379 .as_ref()
380 .and_then(|params| params.get_parameters().first())
381 else {
382 return Ok(None);
383 };
384 let Some(call) = param.testopt_call.as_deref() else {
385 return Ok(None);
386 };
387 if x_equals(&call.head, &call.kernel) {
388 return Ok(None);
389 }
390 Ok(Some(Tokens!(
391 call.head,
392 self.cs,
393 call.internal,
394 T_BEGIN!(),
395 param.extra.first().unwrap_or(&NO_TOKENS).clone(),
396 T_END!()
397 )))
398 }
399
400 #[inline]
402 pub fn yields_calls(&self) -> bool { matches!(self.special_call, SpecialCall::YieldsCalls) }
403
404 #[cold]
416 #[inline(never)]
417 fn watched_call(&self) -> Option<WatchedCall> {
418 if crate::definition::origin::copy_default_watch() {
419 note_setter_call(&self.cs);
420 }
421 let recorded = crate::definition::origin::document_call_watch()
422 && self.paramlist.is_some()
423 && self.origin.is_latexml_owned()
424 && crate::gullet::reading_document_text();
425 let dropping = crate::definition::origin::dropped_argument_watch()
426 && self.paramlist.is_some()
427 && self.origin.is_binding_made()
428 && !matches!(self.expansion, Some(ExpansionBody::Closure(_)));
429 let stored = crate::definition::origin::store_call_watch()
430 && self.paramlist.is_some()
431 && self.made_in_own_file
432 && self.stored_parameters().numbers != 0
433 && !lookup_bool("lx_replaying_class_setter")
434 && !lookup_bool("lx_depositing_class_maketitle");
435 (recorded || dropping || stored).then_some(WatchedCall { recorded, dropping, stored })
436 }
437
438 fn stored_parameters(&self) -> &StoredParameters {
440 self.stored.get_or_init(|| {
441 Box::new(match self.expansion.as_ref() {
442 Some(ExpansionBody::Tokens(body)) => stored_parameters(body.unlist_ref()),
443 _ => StoredParameters::default(),
444 })
445 })
446 }
447
448 #[cold]
451 #[inline(never)]
452 fn expand_watched(&self, once_only: bool, watched: WatchedCall) -> Result<Tokens> {
453 let expansion = if watched.recorded || watched.dropping || watched.stored {
454 let mut captured = None;
455 let expansion = self.expand_capturing::<true>(once_only, &mut captured)?;
456 if let (Some(args), Some(parms)) = (captured, self.paramlist.as_ref()) {
457 let parameters = parms.get_parameters();
458 let keyed: Vec<bool> = parameters
461 .iter()
462 .filter(|parameter| !parameter.novalue)
463 .map(|parameter| parameter.optional || parameter.spec == crate::pin!("Until:]"))
464 .collect();
465 let optional = parameters
466 .iter()
467 .filter(|parameter| !parameter.novalue)
468 .map(|parameter| parameter.optional);
469 let used = |at: usize| {
475 !self.origin.is_binding_made()
476 || self.dropped_by_design & (1 << at) != 0
477 || match self.expansion.as_ref() {
478 Some(ExpansionBody::Tokens(body)) => names_parameter(body, at),
479 Some(ExpansionBody::Closure(_)) => true,
480 None => false,
481 }
482 };
483 let args: Vec<DocumentArgument> = optional
484 .zip(args.iter())
485 .enumerate()
486 .filter_map(|(at, (optional, arg))| match arg {
487 ArgWrap::Tokens(tokens) => Some(DocumentArgument {
488 number: at + 1,
489 optional,
490 used: used(at + 1),
491 tokens: tokens.clone(),
492 }),
493 _ => None,
494 })
495 .collect();
496 if watched.dropping {
497 for arg in args.iter().filter(|arg| !arg.optional && !arg.used) {
498 note_dropped_argument(self.cs, arg);
499 }
500 }
501 if watched.stored {
502 let stored = self.stored_parameters();
503 let (keys, values): (Vec<_>, Vec<_>) = args
504 .iter()
505 .filter(|arg| stored.numbers & (1 << arg.number) != 0 && !arg.tokens.is_empty())
506 .partition(|arg| keyed.get(arg.number - 1).copied().unwrap_or(false));
507 let tokens =
508 |args: Vec<&DocumentArgument>| args.into_iter().map(|arg| arg.tokens.clone()).collect();
509 note_store_call(self.cs, stored, tokens(values), tokens(keys));
510 }
511 if watched.recorded {
512 note_document_call(self.cs, args);
513 }
514 }
515 expansion
516 } else {
517 self.expand(once_only)?
518 };
519 Ok(expansion)
520 }
521
522 #[inline(always)]
524 fn expand(&self, once_only: bool) -> Result<Tokens> {
525 self.expand_capturing::<false>(once_only, &mut None)
526 }
527
528 #[inline(always)]
530 fn expand_capturing<const CAPTURE: bool>(
531 &self,
532 once_only: bool,
533 captured: &mut Option<Vec<ArgWrap>>,
534 ) -> Result<Tokens> {
535 if self.yields_calls()
543 && let Some(owner) = self.call_owner()?
544 {
545 return Ok(Tokens!(owner));
546 }
547 if let Some(call) = self.testopt_call()? {
548 return Ok(call);
549 }
550 match &self.expansion {
551 Some(ExpansionBody::Closure(closure)) => {
552 let args = if let Some(ref parms) = self.paramlist {
554 match self.read_call_arguments(parms)? {
556 Some(args) => args,
557 None => return Ok(Tokens!()),
558 }
559 } else {
560 Vec::new()
561 };
562 if CAPTURE {
563 *captured = Some(args.clone());
564 }
565 let result = closure(args)?;
567 Ok(result)
570 },
571 Some(ExpansionBody::Tokens(tokens)) => {
572 let result = if self.paramlist.is_none() {
573 Tokens::new(self.parameterless_body(tokens, once_only)?.to_vec())
578 } else {
579 let args = if let Some(ref parms) = self.paramlist {
580 match self.read_call_arguments(parms)? {
584 Some(args) => args,
585 None => return Ok(Tokens!()),
586 }
587 } else {
588 Vec::new()
589 };
590 if CAPTURE {
591 *captured = Some(args.clone());
592 }
593 if self.has_cc_arg {
594 let mut args_tks = Vec::with_capacity(args.len());
598 for arg in args.iter() {
599 args_tks.push(arg.as_tokens()?);
600 }
601 tokens.substitute_parameters(args_tks.as_slice())
602 } else {
603 tokens.clone()
604 }
605 };
606 Ok(result)
609 },
610 None => {
611 if let Some(ref parms) = self.paramlist {
613 let args = self.read_call_arguments(parms)?;
614 if CAPTURE {
615 *captured = args;
616 }
617 }
618 Ok(NO_TOKENS)
619 },
620 }
621 }
622
623 fn call_owner(&self) -> Result<Option<Token>> {
630 let Some(next) = crate::gullet::peek_token()? else {
631 return Ok(None);
632 };
633 let owner = locked_binding_token(&self.cs);
634 let opens_call = next.get_catcode() == Catcode::BEGIN
635 || next.get_catcode() == Catcode::OTHER && call_openers(&owner).contains(&next);
636 Ok(opens_call.then_some(owner))
637 }
638
639 fn parameterless_body<'a>(&self, tokens: &'a Tokens, once_only: bool) -> Result<&'a [Token]> {
643 if self.expands_into_itself(tokens, once_only) {
681 Error!(
682 "recursion",
683 &self.cs.to_string(),
684 s!("Token {} expands into itself!", self.cs)
685 );
686 Ok(&[])
687 } else {
688 Ok(tokens.unlist_ref())
689 }
690 }
691
692 #[inline(never)]
695 fn substitute_onto_input(&self, tokens: &Tokens, args: &[ArgWrap]) -> Result<()> {
696 if args.iter().all(|arg| matches!(arg, ArgWrap::Tokens(_))) {
698 let plan = self.plan.get_or_init(|| tokens.substitution_plan());
699 crate::gullet::unread_substituted_args(tokens.unlist_ref(), plan, args);
700 return Ok(());
701 }
702 let mut owned: [Option<Cow<'_, Tokens>>; 9] = Default::default();
704 if args.len() > owned.len() {
705 crate::gullet::unread_expansion(
706 tokens.substitute_parameters(
707 &args
708 .iter()
709 .map(|arg| arg.as_tokens())
710 .collect::<Result<Vec<_>>>()?,
711 ),
712 );
713 return Ok(());
714 }
715 for (slot, arg) in owned.iter_mut().zip(args.iter()) {
716 *slot = arg.as_tokens()?;
717 }
718 let mut slices: [&[Token]; 9] = [&[]; 9];
719 for (slice, arg) in slices.iter_mut().zip(owned.iter()) {
720 if let Some(arg) = arg {
721 *slice = arg.unlist_ref();
722 }
723 }
724 let plan = self.plan.get_or_init(|| tokens.substitution_plan());
725 crate::gullet::unread_substituted(tokens.unlist_ref(), plan, &slices[..args.len()]);
726 Ok(())
727 }
728
729 fn expands_into_itself(&self, tokens: &Tokens, once_only: bool) -> bool {
733 if !once_only {
734 let token_vec = tokens.unlist_ref();
735 let t0_opt = token_vec.first();
736 let t1_opt = token_vec.get(1);
737 let invoker = get_current_token().unwrap_or(self.cs);
747 if let Some(t0) = t0_opt {
748 if t0 == &self.cs && *t0 == invoker {
749 true
750 } else if let Some(t1) = t1_opt {
751 t1 == &self.cs && t0 == &T_CS!("\\protect") && protect_is_relax_or_undefined()
765 } else {
766 false
767 }
768 } else {
769 false
770 }
771 } else {
772 false
773 }
774 }
775
776 fn read_call_arguments(&self, parms: &Parameters) -> Result<Option<Vec<ArgWrap>>> {
785 let cs = get_current_token().unwrap_or(self.cs);
786 let matching = crate::gullet::set_scanner_status_checking_par(
787 crate::gullet::ScannerStatus::Matching,
788 Some(cs),
789 self.checks_par,
790 );
791 let args = parms.read_macro_arguments(Some(self))?;
792 match matching.end_taking_runaway_argument() {
793 None => Ok(args),
794 Some(runaway) => {
795 crate::gullet::abandon_runaway_call(cs, self.is_long, self.checks_par, runaway)?;
796 Ok(None)
797 },
798 }
799 }
800
801 pub fn new(
802 cs: Token,
803 paramlist: Option<Parameters>,
804 mut expansion_opt: Option<ExpansionBody>,
805 traits: Option<ExpandableOptions>,
806 ) -> Result<Self> {
807 let traits = traits.unwrap_or_default();
808 if !traits.nopack_parameters
809 && let Some(ExpansionBody::Tokens(expansion_tokens)) = expansion_opt
810 {
811 if !expansion_tokens.is_balanced() {
819 Fatal!(
820 Stomach,
821 Misdefined,
822 s!("Expansion of '{}' has unbalanced {{}}", cs)
823 );
824 } else {
825 expansion_opt = Some(ExpansionBody::Tokens(expansion_tokens.pack_parameters()?));
826 }
827 }
828 let has_cc_arg = match expansion_opt {
829 Some(ExpansionBody::Tokens(ref tks)) => tks
830 .unlist_ref()
831 .iter()
832 .any(|t| t.get_catcode() == Catcode::ARG),
833 _ => false,
834 };
835 let expansion = match expansion_opt {
837 Some(ExpansionBody::Tokens(tks)) if tks.is_empty() => None,
838 real_body => real_body,
839 };
840
841 let peeks_by_futurelet = traits.peeks_by_futurelet
844 || paramlist.as_ref().is_some_and(|params| {
845 params
846 .get_parameters()
847 .first()
848 .is_some_and(|param| param.testopt)
849 });
850 let is_long = traits.long || get_prefix_sym(crate::pin!("long"));
851 let reads_arguments = paramlist
852 .as_ref()
853 .is_some_and(|params| !params.get_parameters().is_empty());
854 Ok(Expandable {
855 cs,
856 paramlist,
857 peeks_by_futurelet,
858 expansion,
859 is_protected: traits.protected || get_prefix_sym(crate::pin!("protected")),
863 is_outer: traits.outer || get_prefix_sym(crate::pin!("outer")),
864 is_long,
865 checks_par: !is_long
866 && reads_arguments
867 && (traits.short
868 || traits.tex_declared
869 && matches!(
870 crate::definition::origin::current_origin(),
871 crate::definition::origin::DefinitionOrigin::Format
872 | crate::definition::origin::DefinitionOrigin::File
873 | crate::definition::origin::DefinitionOrigin::Document
874 )),
875 has_cc_arg,
876 alias: traits.alias,
877 dropped_by_design: traits.drops.iter().fold(0, |bits, &number| {
878 debug_assert!(number <= 9, "a dropped argument number past #9: {number}");
880 bits | 1 << number
881 }),
882 made_in_own_file: crate::definition::origin::reading_own_file(),
883 ..Expandable::default()
884 })
885 }
886}
887
888pub const KERNEL_WRITERS_OF_NAMES: &[&str] = &[
892 "\\def",
893 "\\gdef",
894 "\\edef",
895 "\\xdef",
896 "\\let",
897 "\\protected@edef",
898 "\\protected@xdef",
899 "\\g@addto@macro",
900];
901
902pub const ETOOLBOX_WRITERS_OF_NAMES: &[&str] = &[
905 "\\@namedef",
906 "\\appto",
907 "\\gappto",
908 "\\eappto",
909 "\\xappto",
910 "\\preto",
911 "\\gpreto",
912 "\\epreto",
913 "\\xpreto",
914 "\\listadd",
915 "\\listgadd",
916 "\\listeadd",
917 "\\listxadd",
918 "\\csdef",
919 "\\csgdef",
920 "\\csedef",
921 "\\csxdef",
922 "\\csappto",
923 "\\csgappto",
924 "\\cseappto",
925 "\\csxappto",
926 "\\cspreto",
927 "\\csgpreto",
928 "\\csepreto",
929 "\\csxpreto",
930 "\\listcsadd",
931 "\\listcsgadd",
932 "\\listcseadd",
933 "\\listcsxadd",
934];
935
936pub const WRITERS_OF_NAMES: [&str;
939 KERNEL_WRITERS_OF_NAMES.len() + ETOOLBOX_WRITERS_OF_NAMES.len()] = {
940 let mut all = [""; KERNEL_WRITERS_OF_NAMES.len() + ETOOLBOX_WRITERS_OF_NAMES.len()];
941 let mut at = 0;
942 while at < all.len() {
943 all[at] = if at < KERNEL_WRITERS_OF_NAMES.len() {
944 KERNEL_WRITERS_OF_NAMES[at]
945 } else {
946 ETOOLBOX_WRITERS_OF_NAMES[at - KERNEL_WRITERS_OF_NAMES.len()]
947 };
948 at += 1;
949 }
950 all
951};
952
953const APPENDERS: &[&str] = &[
955 "\\g@addto@macro",
956 "\\appto",
957 "\\gappto",
958 "\\eappto",
959 "\\xappto",
960 "\\preto",
961 "\\gpreto",
962 "\\epreto",
963 "\\xpreto",
964 "\\listadd",
965 "\\listgadd",
966 "\\listeadd",
967 "\\listxadd",
968 "\\csappto",
969 "\\csgappto",
970 "\\cseappto",
971 "\\csxappto",
972 "\\cspreto",
973 "\\csgpreto",
974 "\\csepreto",
975 "\\csxpreto",
976 "\\listcsadd",
977 "\\listcsgadd",
978 "\\listcseadd",
979 "\\listcsxadd",
980];
981
982const SCRATCH_NAMES: &[&str] = &[
986 "\\@tempa",
987 "\\@tempb",
988 "\\@tempc",
989 "\\@tempd",
990 "\\@tempe",
991 "\\@tempf",
992 "\\@gtempa",
993 "\\@temp",
994 "\\@tmp",
995 "\\@tmpa",
996 "\\@tmpb",
997 "\\@tmpc",
998 "\\temp",
999 "\\tempa",
1000 "\\tempb",
1001 "\\tempc",
1002 "\\tmp",
1003 "\\tmpa",
1004 "\\tmpb",
1005 "\\tmpc",
1006 "\\reserved@a",
1007 "\\reserved@b",
1008 "\\reserved@c",
1009 "\\reserved@d",
1010 "\\reserved@e",
1011 "\\reserved@f",
1012 "\\toks@",
1013 "\\@temptokena",
1014 "\\@toks",
1015];
1016
1017pub fn is_scratch_name(name: &str) -> bool { SCRATCH_NAMES.contains(&name) }
1019
1020#[derive(Debug, Clone, Default)]
1022pub struct StoredParameters {
1023 pub numbers: u16,
1025 pub replaces: bool,
1029 pub stores: Vec<Token>,
1031 pub written_out: bool,
1033}
1034
1035fn stored_parameters(body: &[Token]) -> StoredParameters {
1046 const WRITERS_OF_COMMANDS: &[&str] = &["\\renewcommand", "\\newcommand", "\\providecommand"];
1047 let mut stored = StoredParameters {
1048 replaces: true,
1049 ..StoredParameters::default()
1050 };
1051 let mut written: Vec<(Token, u16, Vec<Token>)> = Vec::new();
1053 let mut at = 0;
1054 while at < body.len() {
1055 let token = &body[at];
1056 at += 1;
1057 if token.get_catcode() != Catcode::CS {
1058 continue;
1059 }
1060 let is = |set: &[&str]| token.with_str(|name| set.contains(&name));
1061 let register = at >= 2 && body[at - 2].with_str(|name| name == "\\the");
1062 let is_let = token.with_str(|name| name == "\\let");
1063 let (store, value_search) = if is(WRITERS_OF_COMMANDS) || is(&WRITERS_OF_NAMES) {
1065 match written_store_name(body, at) {
1066 Some(found) => found,
1067 None => continue,
1068 }
1069 } else if token.with_str(|name| name == "\\write") {
1070 match body.get(at) {
1071 Some(stream) if stream.get_catcode() == Catcode::CS => (Some(*stream), at + 1),
1072 _ => continue,
1073 }
1074 } else if !register && is_token_register(token) {
1075 (Some(*token), at)
1076 } else {
1077 continue;
1078 };
1079 let scratch = store.is_some_and(|store| store.with_str(is_scratch_name));
1080 let range = if is_let {
1082 let mut from = value_search;
1083 while body
1084 .get(from)
1085 .is_some_and(|t| t.get_catcode() == Catcode::SPACE || t.with_str(|text| text == "="))
1086 {
1087 from += 1;
1088 }
1089 (from < body.len()).then_some((from, from + 1))
1090 } else {
1091 value_group(body, value_search, token)
1092 };
1093 let Some((from, to)) = range else {
1094 continue;
1095 };
1096 let value = &body[from..to];
1097 if value.iter().any(|inner| stored.stores.contains(inner)) {
1101 stored.replaces = false;
1102 }
1103 let mut named = 0u16;
1104 let mut holds: Vec<Token> = value.to_vec();
1105 for inner in value {
1106 if inner.get_catcode() == Catcode::ARG
1107 && let Some(number) = inner.with_str(|text| text.parse::<u16>().ok())
1108 {
1109 named |= 1 << number;
1110 } else if let Some((_, numbers, tokens)) = written.iter().find(|(name, ..)| name == inner) {
1111 named |= numbers;
1112 holds.extend_from_slice(tokens);
1113 }
1114 }
1115 if named != 0 && !scratch {
1116 stored.numbers |= named;
1117 let appends = is(APPENDERS) || token.with_str(|name| name == "\\write");
1118 match store {
1119 None => stored.replaces = false,
1121 Some(store) => {
1122 if appends || holds.contains(&store) {
1123 stored.replaces = false;
1124 }
1125 if token.with_str(|name| name == "\\write") {
1126 stored.written_out = true;
1127 } else {
1128 stored.stores.push(store);
1129 }
1130 },
1131 }
1132 }
1133 if let Some(store) = store
1134 && !(token.with_str(|name| name == "\\write"))
1135 {
1136 written.retain(|(name, ..)| *name != store);
1137 written.push((store, named, holds));
1138 }
1139 at = to;
1140 }
1141 stored
1142}
1143
1144pub fn written_store_name(body: &[Token], mut at: usize) -> Option<(Option<Token>, usize)> {
1148 while let Some(token) = body.get(at)
1149 && (token.get_catcode() == Catcode::SPACE
1150 || token.with_str(|text| text == "*" || text == "\\expandafter"))
1151 {
1152 at += 1;
1153 }
1154 let token = body.get(at)?;
1155 match token.get_catcode() {
1156 Catcode::CS if token.with_str(|name| name == "\\csname") => {
1157 let end = body[at..]
1158 .iter()
1159 .position(|t| t.with_str(|name| name == "\\endcsname"))?;
1160 Some((None, at + end + 1))
1161 },
1162 Catcode::CS | Catcode::ACTIVE => Some((Some(*token), at + 1)),
1163 Catcode::BEGIN => {
1164 let name = body.get(at + 1)?;
1165 let close = body.get(at + 2)?;
1166 if name.get_catcode() == Catcode::CS && close.get_catcode() == Catcode::END {
1167 return Some((Some(*name), at + 3));
1168 }
1169 let mut depth = 0usize;
1171 for (offset, token) in body[at..].iter().enumerate() {
1172 match token.get_catcode() {
1173 Catcode::BEGIN => depth += 1,
1174 Catcode::END => {
1175 depth -= 1;
1176 if depth == 0 {
1177 return Some((None, at + offset + 1));
1178 }
1179 },
1180 _ => {},
1181 }
1182 }
1183 None
1184 },
1185 _ => None,
1186 }
1187}
1188
1189pub fn value_group(body: &[Token], mut at: usize, writer: &Token) -> Option<(usize, usize)> {
1193 let by_group_only = !writer.with_str(|name| {
1194 WRITERS_OF_NAMES.contains(&name)
1195 || matches!(name, "\\renewcommand" | "\\newcommand" | "\\providecommand")
1196 });
1197 while let Some(token) = body.get(at) {
1198 match token.get_catcode() {
1199 Catcode::BEGIN => break,
1200 Catcode::END => return None,
1201 Catcode::SPACE => {},
1202 _ if !by_group_only => {},
1203 _ if token.with_str(|text| text == "=" || text == "\\expandafter") => {},
1204 _ => return None,
1205 }
1206 at += 1;
1207 }
1208 let from = at + 1;
1209 let mut depth = 0usize;
1210 for (offset, token) in body.get(at..)?.iter().enumerate() {
1211 match token.get_catcode() {
1212 Catcode::BEGIN => depth += 1,
1213 Catcode::END => {
1214 depth -= 1;
1215 if depth == 0 {
1216 return Some((from, at + offset));
1217 }
1218 },
1219 _ => {},
1220 }
1221 }
1222 None
1223}
1224
1225fn names_parameter(body: &Tokens, number: usize) -> bool {
1227 body.unlist_ref().iter().any(|token| {
1228 token.get_catcode() == Catcode::ARG && token.with_str(|text| text == number.to_string())
1229 })
1230}
1231
1232#[cfg(test)]
1233mod tests {
1234 use super::*;
1235
1236 #[test]
1237 fn expandable_default_flags_false() {
1238 let e = Expandable::default();
1239 assert!(!e.is_protected);
1240 assert!(!e.peeks_by_futurelet);
1241 assert!(!e.is_long);
1242 assert!(!e.is_outer);
1243 assert!(!e.has_cc_arg);
1244 assert!(e.alias.is_none());
1245 assert!(e.paramlist.is_none());
1246 assert!(e.expansion.is_none());
1247 }
1248
1249 #[test]
1250 fn expandable_default_has_default_cs() {
1251 let e = Expandable::default();
1252 assert_eq!(e.cs.code, Catcode::CS);
1255 }
1256
1257 #[test]
1258 fn expandable_is_definition_and_expandable() {
1259 let e = Expandable::default();
1260 assert!(e.is_definition());
1261 assert!(e.is_expandable());
1262 }
1263
1264 #[test]
1265 fn expandable_partial_eq_by_paramlist_and_expansion() {
1266 let mut a = Expandable::default();
1269 let mut b = Expandable::default();
1270 assert_eq!(a, b);
1272 a.is_protected = true;
1274 b.is_protected = false;
1275 assert_eq!(a, b);
1276 }
1277
1278 #[test]
1279 fn expandable_get_num_args_zero_without_paramlist() {
1280 let e = Expandable::default();
1281 assert_eq!(e.get_num_args(), 0);
1282 }
1283
1284 #[test]
1285 fn expandable_get_parameters_none_by_default() {
1286 let e = Expandable::default();
1287 assert!(e.get_parameters().is_none());
1288 }
1289
1290 #[test]
1291 fn expandable_options_default_all_false() {
1292 let o = ExpandableOptions::default();
1293 assert!(!o.locked);
1294 assert!(!o.protected);
1295 assert!(!o.outer);
1296 assert!(!o.long);
1297 assert!(o.scope.is_none());
1298 assert!(o.alias.is_none());
1299 assert!(!o.mathactive);
1300 assert!(!o.robust);
1301 assert!(!o.nopack_parameters);
1302 assert!(!o.peeks_by_futurelet);
1303 }
1304}