1#[macro_use]
2pub mod expandable;
3pub mod argument;
4pub mod conditional;
5pub mod constructor;
6pub mod math_primitive;
7pub mod origin;
8pub mod primitive;
9pub mod register;
10
11use std::{borrow::Cow, fmt, rc::Rc};
12
13use libxml::tree::Node;
14
15use self::{
16 argument::ArgWrap,
17 register::{RegisterType, RegisterValue},
18};
19use crate::{
20 Digested,
21 common::{
22 arena::{self, SymHashMap, SymStr},
23 dimension::Dimension,
24 error::{emit_warn, *},
25 font::Font,
26 object::Object,
27 store::Stored,
28 },
29 definition::conditional::ConditionalType,
30 document::Document,
31 gullet::Gullet,
32 mouth,
33 parameter::Parameters,
34 state::{Scope, expire_state_unlocked, local_state_unlocked},
35 token::Token,
36 tokens::{NO_TOKENS, TeXString, Tokens},
37 whatsit::Whatsit,
38};
39
40pub type ExpansionClosure = Rc<dyn Fn(Vec<ArgWrap>) -> Result<Tokens>>;
41pub type ConditionalClosure = Rc<dyn Fn(Vec<ArgWrap>) -> Result<bool>>;
42pub type PrimitiveFn = dyn Fn(Vec<ArgWrap>) -> Result<Vec<Digested>>;
43pub type PrimitiveClosure = Rc<PrimitiveFn>;
44pub type BeforeDigestClosure = Rc<dyn Fn() -> Result<Vec<Digested>>>;
45pub type PropertiesClosure = Rc<dyn Fn(&Vec<Option<Digested>>) -> Result<SymHashMap<Stored>>>;
46pub type DigestionClosure = Rc<dyn Fn(&mut Whatsit) -> Result<Vec<Digested>>>;
47pub type ReplacementClosure =
48 Rc<dyn Fn(&mut Document, &Vec<Option<Digested>>, &SymHashMap<Stored>) -> Result<()>>;
49pub type ConstructionClosure = Rc<dyn Fn(&mut Document, &Whatsit) -> Result<()>>;
50pub type DigestedReversionClosure = Rc<dyn Fn(&Whatsit, &Vec<Option<Digested>>) -> Result<Tokens>>;
51pub type SizingClosure = Rc<dyn Fn(&Whatsit) -> Result<(Dimension, Dimension, Dimension)>>;
52pub type FontClosure = Rc<dyn Fn(Option<&Whatsit>) -> Result<Font>>;
53
54#[derive(Clone)]
55pub enum ExpansionBody {
56 Closure(ExpansionClosure),
57 Tokens(Tokens),
58}
59
60impl ExpansionBody {
61 pub fn push(&mut self, t: Token) {
64 match self {
65 ExpansionBody::Tokens(tks) => tks.unlist_mut().push(t),
66 ExpansionBody::Closure(_) => {
67 },
69 }
70 }
71}
72
73pub const CLOSURE_BODY_TEXT: &str = "CODE(native)";
76
77pub fn closure_body_meaning(cs: &str) -> String {
80 let name = cs.strip_prefix('\\').unwrap_or(cs);
81 if !name.is_empty() && name.chars().all(|c| c.is_ascii_alphabetic() || c == '@') {
82 format!("CODE({name})")
83 } else {
84 CLOSURE_BODY_TEXT.to_string()
85 }
86}
87
88impl fmt::Debug for ExpansionBody {
89 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90 match self {
91 ExpansionBody::Closure(_) => f.write_str(CLOSURE_BODY_TEXT),
92 ExpansionBody::Tokens(ts) => write!(f, "{ts:?}"),
93 }
94 }
95}
96
97impl Default for ExpansionBody {
98 fn default() -> Self { ExpansionBody::Tokens(NO_TOKENS) }
99}
100
101impl PartialEq for ExpansionBody {
102 fn eq(&self, other: &ExpansionBody) -> bool {
103 match (self, other) {
115 (ExpansionBody::Closure(a), ExpansionBody::Closure(b)) => Rc::ptr_eq(a, b),
116 (ExpansionBody::Tokens(a), ExpansionBody::Tokens(b)) => a == b,
117 _ => false,
118 }
119 }
120}
121
122#[derive(Clone)]
123pub enum PrimitiveBody {
124 Closure(PrimitiveClosure),
125 String(SymStr),
126}
127impl From<char> for PrimitiveBody {
128 fn from(c: char) -> Self { PrimitiveBody::String(arena::pin_char(c)) }
129}
130
131#[derive(Clone)]
132pub enum Reversion {
133 Closure(DigestedReversionClosure),
134 Tokens(Tokens),
135}
136
137impl PartialEq for Reversion {
138 fn eq(&self, other: &Reversion) -> bool {
139 match self {
140 Reversion::Tokens(t) => match other {
141 Reversion::Tokens(t2) => t == t2,
142 _ => false,
143 },
144 _ => false,
146 }
147 }
148}
149
150impl From<&str> for Reversion {
158 fn from(t: &str) -> Reversion {
159 Reversion::Tokens(
160 mouth::tokenize_internal(TeXString::assembled(t.to_string()))
161 .pack_parameters()
162 .unwrap(),
163 )
164 }
165}
166impl From<Tokens> for Reversion {
167 fn from(ts: Tokens) -> Reversion { Reversion::Tokens(ts) }
168}
169
170impl From<Token> for ExpansionBody {
171 fn from(t: Token) -> ExpansionBody { ExpansionBody::Tokens(Tokens!(t)) }
172}
173
174impl From<Token> for Option<ExpansionBody> {
175 fn from(t: Token) -> Option<ExpansionBody> { Some(ExpansionBody::Tokens(Tokens!(t))) }
176}
177
178impl From<Tokens> for ExpansionBody {
179 fn from(t: Tokens) -> ExpansionBody { ExpansionBody::Tokens(t) }
180}
181
182impl From<Tokens> for Option<ExpansionBody> {
183 fn from(t: Tokens) -> Option<ExpansionBody> { if t.is_empty() { None } else { Some(t.into()) } }
184}
185
186impl From<&str> for ExpansionBody {
187 fn from(s: &str) -> ExpansionBody {
188 mouth::tokenize_internal(TeXString::assembled(s.to_string())).into()
189 }
190}
191
192impl From<String> for ExpansionBody {
193 fn from(s: String) -> ExpansionBody { s.as_str().into() }
194}
195
196impl From<ArgWrap> for ExpansionBody {
197 fn from(t: ArgWrap) -> ExpansionBody {
198 ExpansionBody::Tokens(t.owned_tokens().unwrap_or_default())
199 }
200}
201impl From<ArgWrap> for Option<ExpansionBody> {
202 fn from(t: ArgWrap) -> Option<ExpansionBody> {
203 match t.owned_tokens() {
204 Some(tks) if !tks.is_empty() => Some(ExpansionBody::Tokens(tks)),
205 _ => None,
206 }
207 }
208}
209
210#[derive(Clone)]
211pub enum FontDirective {
212 Closure(FontClosure),
213 Asset(Rc<Font>),
214}
215
216impl From<Font> for FontDirective {
217 fn from(f: Font) -> Self { FontDirective::Asset(Rc::new(f)) }
218}
219impl From<FontClosure> for FontDirective {
220 fn from(fc: FontClosure) -> Self { FontDirective::Closure(fc) }
221}
222impl FontDirective {
223 pub fn get_font(&self, whatsit: Option<&Whatsit>) -> Result<Rc<Font>> {
224 match self {
225 FontDirective::Closure(fc) => Ok(Rc::new((fc)(whatsit)?)),
226 FontDirective::Asset(font) => Ok(Rc::clone(font)),
227 }
228 }
229 pub fn get_asset(&self) -> Option<Rc<Font>> {
230 if let FontDirective::Asset(font) = self {
231 Some(Rc::clone(font))
232 } else {
233 None
234 }
235 }
236}
237impl fmt::Debug for FontDirective {
238 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
239 match self {
240 FontDirective::Closure(_) => write!(f, "<FontClosure>"),
241 FontDirective::Asset(font) => write!(f, "{:?}", *font),
242 }
243 }
244}
245impl PartialEq for FontDirective {
246 fn eq(&self, other: &FontDirective) -> bool {
247 match self {
248 FontDirective::Closure(_) => false, FontDirective::Asset(asset1) => match other {
250 FontDirective::Closure(_) => false,
251 FontDirective::Asset(asset2) => *asset1 == *asset2,
252 },
253 }
254 }
255}
256
257#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
276pub struct DeclaredMode {
277 pub mode: Option<SymStr>,
279 pub enter_horizontal: bool,
282 pub leave_horizontal: bool,
284 pub bounded: bool,
286 pub require_math: bool,
287 pub forbid_math: bool,
288 pub restricted_box: bool,
292}
293
294pub trait Definition: Object {
295 fn invoke(&self, once_only: bool) -> Result<Tokens>;
296 fn invoke_onto_input(&self, once_only: bool) -> Result<()> {
300 crate::gullet::unread_expansion(self.invoke(once_only)?);
301 Ok(())
302 }
303 fn native_expansion(&self) -> Result<Option<Tokens>> { Ok(None) }
306 fn invoke_primitive(&self) -> Result<Vec<Digested>>;
307
308 fn get_cs(&self) -> Cow<'_, Token>;
311 fn get_cs_name(&self) -> Cow<'_, str>;
312 fn get_cs_or_alias(&self) -> Cow<'_, Token> {
313 match self.get_alias() {
314 Some(alias) => Cow::Owned(T_CS!(alias)),
315 None => self.get_cs(),
316 }
317 }
318 fn get_sizer(&self) -> Option<SizingClosure> { None }
319 fn declared_mode(&self) -> Option<DeclaredMode> { None }
324 fn declared_font(&self) -> Option<&FontDirective> { None }
330 fn replacement_template(&self) -> Option<&'static str> { None }
335 fn get_alias(&self) -> Option<&String>;
336 fn is_protected(&self) -> bool { false }
337 fn peeks_by_futurelet(&self) -> bool { false }
345 fn is_register(&self) -> bool { false }
346 fn is_prefix(&self) -> bool { false }
347 fn is_readonly(&self) -> bool { false }
348 fn get_test(&self) -> Option<&ConditionalClosure> { None }
349 fn get_conditional_type(&self) -> Option<ConditionalType> { None }
350
351 fn read_arguments(&self) -> Result<Vec<ArgWrap>>
352 where Self: Sized {
353 match self.get_parameters() {
354 None => Ok(Vec::new()),
355 Some(params) => params.read_arguments(Some(self)),
356 }
357 }
358 fn get_parameters(&self) -> Option<&Parameters>;
359
360 fn invocation(&mut self, args: Vec<Option<Tokens>>, _gullet: &mut Gullet) -> Result<Tokens> {
363 let mut invocation_result: Vec<Token> = vec![self.get_cs().into_owned()];
364
365 match self.get_parameters() {
366 None => {},
367 Some(params) => {
368 for result_token in params.revert_arguments(args)? {
369 invocation_result.push(result_token);
370 }
371 },
372 }
373 Ok(Tokens::new(invocation_result))
374 }
375
376 fn get_num_args(&self) -> usize { 0 }
377
378 fn do_absorption(&self, _document: &mut Document, _whatsit: &Whatsit) -> Result<Vec<Node>>;
379 fn before_digest(&self) -> Option<&Vec<BeforeDigestClosure>> { None }
380 fn after_digest(&self) -> Option<&Vec<DigestionClosure>> { None }
381 fn after_digest_body(&self) -> Option<&Vec<DigestionClosure>> { None }
382 fn capture_body(&self) -> bool { false }
383
384 fn execute_before_digest(&self) -> Result<Vec<Digested>> {
385 local_state_unlocked(true);
386 if let Some(pre_list) = self.before_digest() {
397 for pre in pre_list.iter() {
398 for bx in pre()? {
399 crate::stomach::push_box_list(bx);
400 }
401 }
402 }
403 expire_state_unlocked();
404 Ok(Vec::new())
405 }
406 fn execute_after_digest(&self, whatsit: &mut Whatsit) -> Result<Vec<Digested>> {
407 local_state_unlocked(true);
408 let mut after_digested = Vec::new();
409 if let Some(post_list) = self.after_digest() {
410 for post in post_list.iter() {
411 after_digested.extend(post(whatsit)?);
412 }
413 }
414 expire_state_unlocked();
415 Ok(after_digested)
416 }
417
418 fn execute_after_digest_body(&self, whatsit: &mut Whatsit) -> Result<Vec<Digested>> {
419 local_state_unlocked(true);
420 let mut after_body_digested = Vec::new();
421 if let Some(post_list) = self.after_digest_body() {
422 for post in post_list {
425 let after_body_digest_result = post(whatsit)?;
426 after_body_digested.extend(after_body_digest_result);
427 }
428 }
429 expire_state_unlocked();
430 Ok(after_body_digested)
431 }
432
433 fn value_of(&self, _args: Vec<ArgWrap>) -> Option<RegisterValue> { None }
434 fn set_value(
436 &self,
437 _value: RegisterValue,
438 _scope: Option<Scope>,
439 _args: Vec<ArgWrap>,
440 ) -> Result<()> {
441 emit_warn(
442 "internal",
443 "register",
444 "set_value called on non-register definition",
445 );
446 Ok(())
447 }
448 fn register_type(&self) -> Option<RegisterType> { None }
449 fn get_reversion_spec(&self) -> Option<Reversion> { None }
450 fn get_expansion(&self) -> Option<&ExpansionBody> { None }
451
452 fn stringify_type(&self, deftype: &str) -> String {
453 let name = match self.get_alias() {
454 Some(alias) => alias.clone(),
455 None => self.get_cs().with_cs_name(ToString::to_string),
456 };
457 if let Some(parameters) = self.get_parameters() {
458 s!("{}[{} {}]", deftype, name, parameters.stringify())
459 } else {
460 s!("{}[{}]", deftype, name)
461 }
462 }
463}
464
465impl PartialEq for dyn Definition {
474 fn eq(&self, other: &dyn Definition) -> bool { self.stringify() == other.stringify() }
475}
476
477impl fmt::Display for dyn Definition {
478 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
479 if let Some(params) = self.get_parameters() {
480 write!(f, "{} {}", self.get_cs_name(), params)
481 } else {
482 write!(f, "{}", self.get_cs_name())
483 }
484 }
485}
486
487impl fmt::Display for ExpansionBody {
488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
489 match self {
490 ExpansionBody::Tokens(t) => write!(f, "{t}"),
491 ExpansionBody::Closure(_) => f.write_str(CLOSURE_BODY_TEXT),
492 }
493 }
494}