Skip to main content

latexml_core/binding/def/
macros.rs

1// Macros requiring repetitions need to be handled outside of the main setup macro, as nested
2// macros currently don't support repetition Details at:
3// https://github.com/rust-lang/rust/issues/35853
4
5/// build a Font from key=>val pairs
6#[macro_export]
7macro_rules! Font {
8  ($($key:ident => $value:expr_2021),*) => (
9    Some(Font { $($key: $value.into_font_field(),)* .. Font::default() })
10)}
11
12/// build a FontDirective from key=>val pairs
13/// (currently only FontDirective::Asset is supported in this macro)
14#[macro_export]
15macro_rules! FontDirective {
16  ($($key:ident => $value:expr_2021),*) => (
17    Some(FontDirective::Asset(Rc::new(
18      Font { $($key: $value.into_font_field(),)* .. Font::default() }
19    ))))
20}
21
22/// given a struct `$name`, create a new instance of it using the given key=>val pairs
23/// and complete the remaining entries via the Default instance
24#[macro_export]
25macro_rules! NewDefault {
26  ($name:ident, $($key:ident => $value:expr_2021),*) => ($name {
27    $($key: $value,)*
28    ..$name::default()
29  })
30}
31
32/// Just like NewDefault, but adds a mandatory `.into_option()` to all values
33#[macro_export]
34macro_rules! NewDefaultV {
35  ($name:ident, $($key:ident => $value:expr_2021),*) => ($name {
36    $($key: $value.into_option(),)*
37    ..$name::default()
38  })
39}
40
41// Useful shorthand macros, to brainstorm ergonomics ideas,
42// and to aid binding development
43
44/// Transfers a mutable pointer to a hashmap entry, or fills in with a default if missing.
45///
46/// Assumption: `$receiver` is HashMap<String,String>.
47/// If, and only if, `$has_receiver` does not have a value at slot `$val`,
48/// and `$struct_source` has a set value at `$val`,
49/// then transfers (with ownership) the `$val` field of a `$struct_source` into the `$receiver`.
50#[macro_export]
51macro_rules! transfer_opt_default {
52  ($val:ident, $struct_source:ident, $receiver:ident) => {
53    if let Some(ref tval) = $struct_source.$val {
54      $receiver
55        .entry(stringify!($val).to_owned())
56        .or_insert(tval.to_string());
57    }
58  };
59}
60
61// Discussion: Ideally we wouldn't need any of these closure macros, just the way latexml proper
62// doesn't. In latexml, you could say:
63
64#[macro_export]
65macro_rules! before_digest {
66  ($(sub)? $body:block) => {
67    vec![before_digest_single!($body)]
68  };
69}
70
71#[macro_export]
72macro_rules! before_digest_single {
73  ($body:block) => {
74    Rc::new(move || $body.into_digested_result())
75  };
76}
77
78#[macro_export]
79macro_rules! before_digest_simple {
80  ($body:block) => {
81    Rc::new(move || $body.into_digested_result())
82  };
83}
84
85#[macro_export]
86macro_rules! tagsub {
87  // 2-argument form: sub[document, node] { ... }
88  ($document:ident, $node:ident, $body:block) => {
89    vec![Rc::new(
90      |$document: &mut Document, mut $node: &mut Node, _whatsit: Option<&Digested>| -> Result<()> {
91        $body
92        Ok(())
93      },
94    )]
95  };
96  // 3-argument form: sub[document, node, whatsit] { ... }
97  // Matches Perl's ($document, $node, $box) signature for Tag afterClose/afterOpen
98  ($document:ident, $node:ident, $whatsit:ident, $body:block) => {
99    vec![Rc::new(
100      |$document: &mut Document, mut $node: &mut Node, $whatsit: Option<&Digested>| -> Result<()> {
101        $body
102        Ok(())
103      },
104    )]
105  };
106}
107
108#[macro_export]
109macro_rules! sizersub {
110  ($whatsit:ident, $body:block) => {
111    Rc::new(
112      |$whatsit: &Whatsit| -> Result<(Dimension, Dimension, Dimension)> {
113        let macro_out = $body;
114        macro_out
115      },
116    )
117  };
118}
119
120#[macro_export]
121macro_rules! rewrite_replace_sub {
122  ($document:ident, $nodes:ident, $body:block) => {
123  Some(Rc::new(
124    |$document: &mut Document, mut $nodes: Vec<&mut Node>| -> Result<()> {
125      $body
126      Ok(())
127    },
128  ))
129  };
130}
131
132#[macro_export]
133macro_rules! noreplacement {
134  () => {
135    |doc, whatsit, props| Ok(())
136  };
137}
138
139#[macro_export]
140macro_rules! replacement {
141  ($doc:ident, $args:ident, $props:ident, $body:block) => (
142    move |$doc:&mut Document,$args: &Vec<Option<Digested>>,
143      $props: &SymHashMap<Stored>| -> Result<()> {
144    $body
145    Ok(())
146  })
147}
148
149#[macro_export]
150macro_rules! construct {
151  ($doc:ident, $whatsit:ident, $body:block) => {
152  vec![Rc::new(
153    move |$doc: &mut Document, $whatsit: &Whatsit| -> Result<()> {
154      $body
155      Ok(())
156    }
157  )]
158}}
159
160#[macro_export]
161macro_rules! properties {
162  (sub [$args:ident] $body:block) => {
163    properties!($args, $body)
164  };
165  ($args:ident, $body:block) => {
166    Rc::new(move |mut $args: &Vec<Option<Digested>>| -> Result<SymHashMap<Stored>> { $body })
167  };
168  ($(sub)? $body:block) => {
169    Rc::new(
170      move |_args: &Vec<Option<Digested>>| -> Result<SymHashMap<Stored>> {
171        $body.into_properties_result()
172      },
173    )
174  };
175  ($value:expr_2021) => {
176    Rc::new(
177      move |_args: &Vec<Option<Digested>>| -> Result<SymHashMap<Stored>> { Ok($value.clone()) },
178    )
179  };
180}
181
182#[macro_export]
183macro_rules! after_digest {
184  ($(sub)? $body:block) => {
185    vec![after_digest_single!(_whatsit, $body)]
186  };
187  ($whatsit:ident, $body:block) => {
188    vec![after_digest_single!($whatsit, $body)]
189  };
190}
191
192#[macro_export]
193macro_rules! after_digest_single {
194  ($whatsit:ident, $body:block) => {
195    Rc::new(move |$whatsit: &mut Whatsit| -> Result<Vec<Digested>> { $body.into_digested_result() })
196  };
197}
198#[macro_export]
199macro_rules! after_digest_simple {
200  ($whatsit:ident, $body:block) => {
201    Rc::new(move |$whatsit: &mut Whatsit| -> Result<Vec<Digested>> { $body.into_digested_result() })
202  };
203}
204
205#[macro_export]
206macro_rules! reader {
207  ($inner:ident, $extra:ident, $body:block) => {
208    Rc::new(
209      |$inner: Option<&Parameters>, $extra: &[Tokens]| -> Result<ArgWrap> {
210        $body.into_result_argwrap()
211      },
212    )
213  };
214}
215
216#[macro_export]
217macro_rules! predigest {
218  ($arg:ident, $body:block) => {
219    Some(Rc::new(
220      |$arg: ArgWrap, _: &[Tokens]| -> Result<Option<Digested>> {
221        $body.into_digested_option_result()
222      },
223    ))
224  };
225  ($arg:ident, $extra:ident, $body:block) => {
226    Some(Rc::new(
227      |$arg: ArgWrap, $extra: &[Tokens]| -> Result<Option<Digested>> {
228        $body.into_digested_option_result()
229      },
230    ))
231  };
232}
233
234/// A closure for obtaining a `RegisterValue`, usually owned by a `Register` getter.
235#[macro_export]
236macro_rules! getter {
237  ($args: ident, $body:block) => {
238    Some(Rc::new(
239      move |mut $args: Vec<ArgWrap>| -> Option<RegisterValue> {
240        $body.into_register_value_option()
241      },
242    ))
243  };
244}
245
246#[macro_export]
247macro_rules! setter {
248  ($value:ident, $args: ident, $body:block) => {
249    Some(Rc::new(
250      move |$value: RegisterValue, _scope: Option<Scope>, mut $args: Vec<ArgWrap>| {
251        $body;
252        Ok(())
253      },
254    ))
255  };
256  ($value:ident, $scope:ident, $args: ident, $body:block) => {
257    Some(Rc::new(
258      move |$value: RegisterValue, $scope: Option<Scope>, mut $args: Vec<ArgWrap>| {
259        $body;
260        Ok(())
261      },
262    ))
263  };
264}
265
266#[macro_export]
267macro_rules! reversion {
268  ($arg:ident, $inner:ident, $extra:ident, $body:block) => {
269    Some(Rc::new(
270      |mut $arg: Vec<Token>, $inner: Option<&Parameters>, $extra: &[Tokens]| -> Result<Tokens> {
271        $body
272      },
273    ))
274  };
275}
276
277#[macro_export]
278macro_rules! reversion_digested {
279  ($whatsit:ident, $args:ident, $body:block) => {
280    Some(Reversion::Closure(Rc::new(
281      move |$whatsit: &Whatsit, $args: &Vec<Option<Digested>>| -> Result<Tokens> { $body },
282    )))
283  };
284}
285
286// TODO: These .clone calls are silly... can we either
287// 1) Document::insert_element work with a &Vec<Digested>? or
288// 2) we can use mutable Whatsit properties in replacements, where we remove Vec<Digested> instances
289// for cases that will be absorbed? or something else that is lighter on memory allocations?
290
291#[macro_export]
292macro_rules! prop_digested {
293  ($props:ident, $key:expr_2021) => {
294    match $props.get($key) {
295      Some(Stored::VecDigested(vd)) => vd.iter().collect::<Vec<&Digested>>(),
296      Some(Stored::Digested(d)) => vec![&*d],
297      Some(Stored::String(s)) => panic!(
298        "prop_digested! called on a string property {:?} with value {:?}.",
299        $key, s
300      ),
301      None => Vec::new(),
302      other => {
303        $crate::common::error::emit_warn(
304          "unimplemented",
305          "prop_digested",
306          &format!("Please extend the api_macros::prop_digested macro to support: {other:?}"),
307        );
308        // Return empty vec instead of panicking
309        Vec::new()
310      },
311    }
312  };
313}
314
315// Discussion: It is unclear what the best authoring syntax is for our family of latexml binding
316// macros. One idea is to keep them very close to the Rust internals, but we suffer from a variety
317// of boilerplate, such as needing to spell out `key => Some(value.to_string())`, rather than a
318// direct `key => value`.
319//
320// For now I am making the decision to keep writing out the verbose form,
321// and will refactor at a later date, when the trade-offs become more clear. Smart use of the Cow
322// struct is another idea. I will use a helper though:
323
324#[macro_export]
325macro_rules! prop_str {
326  ($props:ident, $key:expr_2021) => {
327    match $props.get($key) {
328      Some(&Stored::String(ref id)) => *id,
329      _ => pin!(""),
330    }
331  };
332}
333
334#[macro_export]
335macro_rules! prop_string {
336  ($props:ident, $key:expr_2021) => {
337    match $props.get($key) {
338      Some(&Stored::String(id)) => arena::to_string(id),
339      _ => String::new(),
340    }
341  };
342}
343
344#[macro_export]
345macro_rules! prop_whatsit {
346  ($props:ident, $key:expr_2021) => {
347    match $props.get($key) {
348      // Cloning here is OK now, as there is an Rc<> guard over the DigestedData
349      Some(&Stored::Digested(ref rc)) => (**rc).clone(),
350      _ => Digested::Whatsit(Rc::new(RefCell::new(Whatsit::default()))),
351    }
352  };
353}
354
355#[macro_export]
356macro_rules! prop_bool {
357  ($props:ident, $key:expr_2021) => {
358    match $props.get($key) {
359      Some(&Stored::Bool(v)) => v,
360      _ => false,
361    }
362  };
363}
364
365/// Convenience macro to flexibly unpack a collection of `Vec<ArgWrap>` arguments into individual
366/// `Tokens` variables.
367#[macro_export]
368macro_rules! unref {
369  ($args:ident => $var:ident) => (count_unpack_ref!(0usize, $args => $var));
370  ($args:ident => $var:ident,$($tail:ident),*) => (
371    count_unpack_ref!(0usize,$args => $var,$($tail),*))
372}
373#[macro_export]
374macro_rules! count_unpack_ref {
375  ($index:expr_2021, $args:ident => $var:ident) => {
376    let $var = $args[$index].as_ref().unwrap();
377  };
378  ($index:expr_2021, $args:ident => $var:ident,$($tail:ident),*) => {
379    count_unpack_ref!($index,$args => $var);
380    count_unpack_ref!(1usize+$index, $args => $($tail),*)
381  };
382}
383
384/// Try to efficiently unwrap a `Vec<T>` into a `[T;n]` for `$arg1`...`$argn`
385#[macro_export]
386macro_rules! unpack_opt {
387  ($args:ident => $arg1:ident) => {
388    let [$arg1]: [_; 1] = $args.try_into().unwrap();
389  };
390  ($args:ident => $arg1:ident,$arg2:ident) => {
391    let [$arg1, $arg2]: [_; 2] = $args.try_into().unwrap();
392  };
393  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident) => {
394    let [$arg1, $arg2, $arg3]: [_; 3] = $args.try_into().unwrap();
395  };
396  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident,$arg4:ident) => {
397    let [$arg1, $arg2, $arg3, $arg4]: [_; 4] = $args.try_into().unwrap();
398  };
399  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident,$arg4:ident,$arg5:ident) => {
400    let [$arg1, $arg2, $arg3, $arg4, $arg5]: [_; 5] = $args.try_into().unwrap();
401  };
402}
403
404/// Try to efficiently unwrap a `&Vec<T>` into a `&[T;n]` for `$arg1`...`$argn`
405#[macro_export]
406macro_rules! unpack_opt_ref {
407  ($args:ident => $arg1:ident) => {
408    let [$arg1]: &[_; 1] = $args[..1].try_into().unwrap();
409  };
410  ($args:ident => $arg1:ident,$arg2:ident) => {
411    let [$arg1, $arg2]: &[_; 2] = $args[..2].try_into().unwrap();
412  };
413  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident) => {
414    let [$arg1, $arg2, $arg3]: &[_; 3] = $args[..3].try_into().unwrap();
415  };
416  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident,$arg4:ident) => {
417    let [$arg1, $arg2, $arg3, $arg4]: &[_; 4] = $args[..4].try_into().unwrap();
418  };
419  ($args:ident => $arg1:ident,$arg2:ident,$arg3:ident,$arg4:ident,$arg5:ident) => {
420    let [$arg1, $arg2, $arg3, $arg4, $arg5]: &[_; 5] = $args[..5].try_into().unwrap();
421  };
422}
423
424/// Convert the number to lower case roman numerals, returning a list of LaTeXML::Core::Token
425#[macro_export]
426macro_rules! roman {
427  ($stuff:expr_2021) => {
428    Tokens::new(ExplodeText!(roman_aux($stuff as i64)))
429  };
430}
431/// Convert the number to upper case roman numerals, returning a list of LaTeXML::Core::Token
432#[macro_export]
433macro_rules! Roman {
434  ($stuff:expr_2021) => {
435    Tokens::new(ExplodeText!(roman_aux($stuff as i64).to_ascii_uppercase()))
436  };
437}
438
439#[macro_export]
440macro_rules! requireMath {
441  ($cs_name:expr_2021) => {
442    if !$crate::state::lookup_bool_sym($crate::pin!("IN_MATH")) {
443      // Perl `requireMath` (Package.pm:1069-1073): `Warn('unexpected', $cs, …)`.
444      let message = s!("{} should only appear in math mode", $cs_name);
445      Warn!("unexpected", $cs_name, message);
446    }
447  };
448}
449#[macro_export]
450macro_rules! forbidMath {
451  ($cs_name:expr_2021) => {
452    if $crate::state::lookup_bool_sym($crate::pin!("IN_MATH")) {
453      // Perl `forbidMath` (Package.pm:1076-1080): `Warn('unexpected', $cs, …)`.
454      let message = s!("{} should not appear in math mode", $cs_name);
455      Warn!("unexpected", $cs_name, message);
456    }
457  };
458}
459
460/// Perl `AssignRegister($cs, $value, $scope, @parameters)` (Package.pm:1397-1406): `$cs` a name or a Token; a cs that is
461/// not a register Warns and assigns nothing.
462#[macro_export]
463macro_rules! AssignRegister {
464  ($cs:expr_2021, $value:expr_2021) => {
465    $crate::AssignRegister!($cs, $value, None, Vec::new())
466  };
467  ($cs:expr_2021, $value:expr_2021, $scope:expr_2021) => {
468    $crate::AssignRegister!($cs, $value, $scope, Vec::new())
469  };
470  ($cs:expr_2021, $value:expr_2021, $scope:expr_2021, $params:expr_2021) => {
471    let cs = $crate::binding::def::macros::register_cs($cs);
472    match $crate::state::lookup_register_definition(&cs) {
473      Some(defn) => $crate::definition::Definition::set_value(&*defn, $value, $scope, $params)?,
474      None => $crate::state::warn_not_register(&cs),
475    }
476  };
477}
478
479/// The token of [`AssignRegister!`]'s and `LookupRegister!`'s (latexml_engine) `$cs` (Perl `T_CS($cs) unless ref $cs`).
480pub fn register_cs(cs: impl RegisterCs) -> crate::token::Token { cs.register_cs() }
481
482/// A register's name as the binding macros take it: a cs name, or the Token itself.
483pub trait RegisterCs {
484  fn register_cs(self) -> crate::token::Token;
485}
486impl RegisterCs for &str {
487  fn register_cs(self) -> crate::token::Token { crate::T_CS!(self) }
488}
489impl RegisterCs for crate::token::Token {
490  fn register_cs(self) -> crate::token::Token { self }
491}
492impl RegisterCs for &crate::token::Token {
493  fn register_cs(self) -> crate::token::Token { *self }
494}
495
496#[macro_export]
497macro_rules! SetCounter {
498  ($ctr:expr_2021 => $value:expr_2021) => {
499    SetCounter!($ctr, $value)
500  };
501  ($ctr:expr_2021, $value:expr_2021) => {
502    $crate::binding::counter::dialect::set_counter(&$ctr.to_string(), $value.into())?;
503  };
504}