Skip to main content

latexml_core/
aux_macros.rs

1//! Helper macros for quicker and more idiomatic construction and access to data structures.
2
3/// A flexary macro for constructing `HashMap<&'static str, &'static str>` maps
4#[macro_export]
5macro_rules! static_map {
6  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
7    let mut map : HashMap<&'static str, &'static str> = HashMap::default();
8    $( map.insert($key, $val); )*
9    map
10  }}
11}
12
13/// A flexary macro for constructing `HashMap<String, T>` maps, where `T` is generic.
14#[macro_export]
15macro_rules! map {
16  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
17    let mut map = HashMap::default();
18    $( map.insert($key.to_string(), $val); )*
19    map
20  }}
21}
22
23/// A flexary macro for constructing `SymHashMap<Stored>` maps
24#[macro_export]
25macro_rules! stored_map {
26  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
27    let mut map : $crate::common::arena::SymHashMap<$crate::common::store::Stored> =
28      $crate::common::arena::SymHashMap::default();
29    $( map.insert($key, $val.into()); )*
30    map
31  }}
32}
33
34/// A flexary macro for constructing `SymHashMap<T>` maps
35#[macro_export]
36macro_rules! sym_map {
37  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
38    let mut map = $crate::common::arena::SymHashMap::default();
39    $( map.insert($key, $val); )*
40    map
41  }}
42}
43
44/// A flexary macro for constructing `HashMap<String, T>` maps
45#[macro_export]
46macro_rules! string_keys_map {
47  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
48    let mut map = HashMap::default();
49    $( map.insert($key.to_string(), $val.into()); )*
50    map
51  }}
52}
53
54/// A flexary macro for constructing `HashMap<String, String>` maps
55#[macro_export]
56macro_rules! string_map {
57  ($( $key:expr_2021 => $val:expr_2021 ),*) => {{
58    let mut map = HashMap::default();
59    $( map.insert($key.to_string(), $val.to_string()); )*
60    map
61  }}
62}
63
64/// A flexary macro for constructing `HashMap<K, V>` maps, where `K` and `V` are both generic
65/// (inferred at time of use)
66#[macro_export]
67macro_rules! raw_map {
68  ($( $key:expr_2021 => $val:expr_2021 ),* $(,)?) => {{
69    #[allow(unused_mut)]
70    let mut map = HashMap::default();
71    $( map.insert($key, $val); )*
72    map
73  }}
74}
75
76/// A flexary macro for constructing `HashMap<char, T>` maps, where `T` is generic
77#[macro_export]
78macro_rules! raw_char_map {
79  ($( $key:literal => $val:expr_2021 ),*) => {{
80    let mut map : HashMap<char,_> = HashMap::default();
81    $( map.insert($key, $val); )*
82    map
83  }}
84}
85
86/// The `s!` macro is a briefer alias for `format!`
87#[macro_export]
88macro_rules! s {
89  ($($arg : tt )*) => {format!($($arg)*)};
90}
91
92/// The `some!` macro transforms data in type `S` to `Option<Into<T>>` (always wrapping with `Some`)
93#[macro_export]
94macro_rules! some {
95  ($arg:expr_2021) => {
96    Some($arg.into())
97  };
98}
99
100/// A variant on `vec!` where each argument receives an additional `.into()` call
101/// best used with an outer context that explicitly provides the expected type, such as
102/// ```
103/// # use std::rc::Rc;
104/// # use latexml_core::common::store::Stored;
105/// # use latexml_core::mixvec;
106/// let stored_vec : Vec<Stored> = mixvec!(1, true, "string");
107/// ```
108#[macro_export]
109macro_rules! mixvec {
110  ($( $val:expr_2021 ),*) => {{
111    vec![ $($val.into()),*]
112  }}
113}
114
115/// A variant on `mixvec!` where each argument receives an additional `.into()` call
116/// best used with an outer context that explicitly provides the expected type, such as
117/// ```
118/// # use std::rc::Rc;
119/// # use latexml_core::common::store::Stored;
120/// # use latexml_core::mixrc;
121/// let stored_vec : Rc<[Stored]> = mixrc!(1, true, "string");
122/// ```
123#[macro_export]
124macro_rules! mixrc {
125  ($( $val:expr_2021 ),*) => {{
126    Rc::new([ $($val.into()),*])
127  }}
128}
129
130/// Instantiates a `Font`, using the `Font` fields as keys, and calling `.into()` for each value.
131/// The specification can be partial - missing fields are taken via the `Default` trait.
132#[macro_export]
133macro_rules! fontmap {
134  ($($key:ident => $value:expr_2021),*) => (
135    Font { $($key: Some($value.into()),)* .. Font::default() })
136}
137
138/// Simple generic helper for `HashSet<K,V>` creation
139/// Source: <https://riptutorial.com/rust/example/4149/create-a-hashset-macro>
140#[macro_export]
141macro_rules! set {
142    ( $( $x:expr_2021 ),* ) => {  // Match zero or more comma delimited items
143        {
144            // use rustc_hash::FxHashSet as HashSet;
145            use rustc_hash::FxHashSet as HashSet;
146            let mut temp_set = HashSet::default();  // Create a mutable HashSet
147            $(
148                temp_set.insert($x); // Insert each item matched into the HashSet
149            )*
150            temp_set // Return the populated HashSet
151        }
152    };
153}
154
155/// A thread's engine root (`arena_root()`, `state_root()`, …): a `&'static` to the value, built on first use and
156/// leaked, kept in a stable `thread_local!` slot. Like the `#[thread_local]` static it replaces, it runs no destructor
157/// at thread exit (`reset_thread_engine` frees the contents); the slot is `const`-initialized and needs no `Drop`, so
158/// an access is one TLS load and a null test, and the `Ref` guards stay `'static` (issue #143).
159macro_rules! thread_root {
160  ($(#[$meta:meta])* $vis:vis fn $name:ident() -> $ty:ty = $init:expr_2021;) => {
161    $(#[$meta])*
162    #[inline(always)]
163    $vis fn $name() -> &'static $ty {
164      ::std::thread_local! {
165        static SLOT: ::std::cell::Cell<Option<&'static $ty>> =
166          const { ::std::cell::Cell::new(None) };
167      }
168      #[cold]
169      #[inline(never)]
170      fn init() -> &'static $ty {
171        let root: &'static $ty = Box::leak(Box::new($init));
172        // An initializer that reaches its own root would build a second value here and lose one.
173        debug_assert!(SLOT.get().is_none(), "a thread root's initializer re-entered its own root");
174        SLOT.set(Some(root));
175        root
176      }
177      match SLOT.get() {
178        Some(root) => root,
179        None => init(),
180      }
181    }
182  };
183}
184
185/// The handle of a `thread_static!` value: it derefs to this thread's value, so the call sites of a former
186/// `#[thread_local]` static (`REPORT.borrow_mut()`, `*TOKEN_RELAX`) read as before (issue #143).
187pub struct ThreadRoot<T: 'static>(pub fn() -> &'static T);
188
189impl<T: 'static> std::ops::Deref for ThreadRoot<T> {
190  type Target = T;
191  #[inline(always)]
192  fn deref(&self) -> &T { (self.0)() }
193}
194
195/// A per-thread static on stable Rust: built on first use and leaked, so, like the `#[thread_local]` attribute it
196/// replaces, it runs no destructor at thread exit; the `thread_local!` slot is `const`-initialized and needs no `Drop`.
197macro_rules! thread_static {
198  ($(#[$meta:meta])* $vis:vis static $name:ident: $ty:ty = $init:expr_2021;) => {
199    $(#[$meta])*
200    $vis static $name: $crate::aux_macros::ThreadRoot<$ty> = $crate::aux_macros::ThreadRoot({
201      #[inline(always)]
202      fn root() -> &'static $ty {
203        ::std::thread_local! {
204          static SLOT: ::std::cell::Cell<Option<&'static $ty>> =
205            const { ::std::cell::Cell::new(None) };
206        }
207        #[cold]
208        #[inline(never)]
209        fn init() -> &'static $ty {
210          let root: &'static $ty = Box::leak(Box::new($init));
211          // An initializer that reaches its own root would build a second value here and lose one.
212          debug_assert!(SLOT.get().is_none(), "a thread root's initializer re-entered its own root");
213          SLOT.set(Some(root));
214          root
215        }
216        match SLOT.get() {
217          Some(root) => root,
218          None => init(),
219        }
220      }
221      root
222    });
223  };
224}