Skip to main content

flm_core/stdlib/features/userdefs/
config.rs

1//! The configuration of the [`userdefs`](super) feature, [`UserdefsConfig`]:
2//! the user definitions and the expansion depth limit, and the forms in which
3//! settings written as data give them.
4//!
5//! [`Userdefs::new`](super::Userdefs::new) takes a [`UserdefsConfig`]: the user
6//! definitions ([`Definition`], one per macro, environment or special
7//! character sequence) and the limit on how many expansions one chain of use
8//! sites may nest before a use site is replaced by its literal source text and
9//! reported with `flm.userdefs.recursion-limit`. The configuration is fixed
10//! when the registry is built ([settings, options and
11//! configuration](crate::guide::concepts_overview#settings-options-and-configuration)).
12//!
13//! Settings written as data ([`crate::core::settings`]) give the configuration
14//! as a [`UserdefsData`]: one map per kind of definition (`macros`,
15//! `environments`, `specials`) from a name to a [`DefinitionData`], and the
16//! depth limit. The library converts it to a [`UserdefsConfig`].
17//!
18//! # The canonical bytes of the configuration
19//!
20//! [`UserdefsConfig::digest_bytes`] writes the configuration as bytes, field
21//! by field. The feature gives these bytes as an input of the [registry
22//! digest](crate::model::digest), because a template text changes the trees a
23//! run freezes, so two registries that differ in one must not share cached
24//! trees. The same bytes are what the type's `Hash` implementation hashes: the
25//! feature's settings declaration declares the configuration as an option type
26//! bound to the registry ([`Bind::Registry`](crate::model::options::Bind)), and
27//! every option type implements `Hash`. The bytes are written field by field
28//! rather than taken from the type's `Debug` output, which could hold a memory
29//! address and would change with a field rename.
30
31// The depth limit is configuration of the feature rather than a per-document
32// or per-render option, because the trees a run freezes depend on it and the
33// registry digest must see it.
34
35use std::collections::BTreeMap;
36use std::hash::{Hash, Hasher};
37
38use serde::Deserialize;
39use serde_json::Value;
40
41use crate::core::settings::named::{self, NamedEntry};
42use crate::model::aspects::{BlockRole, Placement};
43use crate::model::names::Name;
44use crate::lang::mint::{deserialize_arg_list, ArgDef, ArgLayout, ArgListData};
45use crate::lang::rewrites::userdefs::{
46    DEFAULT_RECURSION_LIMIT, Definition, DefinitionKind, ExpandPolicy,
47};
48
49/// The configuration of the [`userdefs`](super) feature: the user definitions
50/// and the expansion depth limit. It is fixed when the registry is built; see
51/// the module documentation.
52///
53/// Build a value with [`UserdefsConfig::new`] and the builder methods
54/// [`definition`](UserdefsConfig::definition),
55/// [`definitions`](UserdefsConfig::definitions) and
56/// [`recursion_limit`](UserdefsConfig::recursion_limit), or read it from data
57/// as a [`UserdefsData`] and convert it with `From`.
58///
59/// # Examples
60///
61/// ```
62/// use flm_core::stdlib::features::userdefs::{Definition, UserdefsConfig};
63///
64/// let config = UserdefsConfig::new()
65///     .definition(Definition::macro_("hi", Vec::new()).content("Hello"))
66///     .recursion_limit(4);
67///
68/// assert_eq!(config.definitions.len(), 1);
69/// assert_eq!(config.recursion_limit, 4);
70/// ```
71///
72#[derive(Debug, Clone)]
73pub struct UserdefsConfig {
74    /// The user definitions, in the order they were declared. In data, they are
75    /// written in one map per kind ([`UserdefsData`]).
76    pub definitions: Vec<Definition>,
77    /// The expansion depth limit: how many expansions one chain of use sites
78    /// may nest before a use site is reported with
79    /// `flm.userdefs.recursion-limit`. The default is
80    /// [`DEFAULT_RECURSION_LIMIT`] (32).
81    pub recursion_limit: usize,
82}
83
84impl UserdefsConfig {
85    /// Returns the default configuration: no definitions, and the default
86    /// expansion depth limit ([`DEFAULT_RECURSION_LIMIT`]).
87    pub fn new() -> UserdefsConfig {
88        UserdefsConfig::default()
89    }
90
91    /// Adds one definition after the ones already declared, and returns the
92    /// configuration.
93    pub fn definition(mut self, definition: Definition) -> UserdefsConfig {
94        self.definitions.push(definition);
95        self
96    }
97
98    /// Adds several definitions, in the order given, after the ones already
99    /// declared, and returns the configuration.
100    pub fn definitions(
101        mut self,
102        definitions: impl IntoIterator<Item = Definition>,
103    ) -> UserdefsConfig {
104        self.definitions.extend(definitions);
105        self
106    }
107
108    /// Sets the expansion depth limit, and returns the configuration.
109    pub fn recursion_limit(mut self, limit: usize) -> UserdefsConfig {
110        self.recursion_limit = limit;
111        self
112    }
113
114    /// Returns the canonical bytes of the configuration: the input the
115    /// `userdefs` feature gives to the registry digest, and what `Hash` hashes.
116    ///
117    /// Two configurations give the same bytes exactly when they declare the
118    /// same definitions in the same order under the same expansion depth
119    /// limit. A definition is written as its name, its kind, its arguments
120    /// (each one's name, the identity of its parser, its parsing mode, its
121    /// layout, whether it is declared with an opaque wrapper, its scoped
122    /// packages and its state events), its template text, the parsing modes it applies in, its
123    /// default values, its argument number offset, its block role, its
124    /// expansion policy, whether it overrides another feature's command, and
125    /// its extra placeholders (each one's name and whether it accepts a
126    /// substitution argument; [`Definition::extra_placeholder`]).
127    /// Documentation strings change nothing in a parse and are left out.
128    pub fn digest_bytes(&self) -> Vec<u8> {
129        let mut out = Vec::new();
130        put_count(&mut out, self.recursion_limit);
131        put_count(&mut out, self.definitions.len());
132        for definition in &self.definitions {
133            put_definition(&mut out, definition);
134        }
135        out
136    }
137}
138
139impl Default for UserdefsConfig {
140    fn default() -> UserdefsConfig {
141        UserdefsConfig { definitions: Vec::new(), recursion_limit: DEFAULT_RECURSION_LIMIT }
142    }
143}
144
145impl Hash for UserdefsConfig {
146    fn hash<H: Hasher>(&self, state: &mut H) {
147        state.write(&self.digest_bytes());
148    }
149}
150
151/// Writes `text` to `out`, its length first.
152fn put(out: &mut Vec<u8>, text: &str) {
153    put_count(out, text.len());
154    out.extend_from_slice(text.as_bytes());
155}
156
157/// Writes an absent text as `-`, and a present one as `+` followed by the
158/// text.
159fn put_opt(out: &mut Vec<u8>, text: Option<&str>) {
160    match text {
161        None => put(out, "-"),
162        Some(text) => {
163            put(out, "+");
164            put(out, text);
165        }
166    }
167}
168
169/// Writes a count or a flag as eight bytes, least significant first.
170fn put_count(out: &mut Vec<u8>, count: usize) {
171    out.extend_from_slice(&(count as u64).to_le_bytes());
172}
173
174/// Writes one definition, field by field, in the order
175/// [`UserdefsConfig::digest_bytes`] lists.
176fn put_definition(out: &mut Vec<u8>, definition: &Definition) {
177    put(out, definition.name.as_str());
178    put(
179        out,
180        match definition.kind {
181            DefinitionKind::Macro => "macro",
182            DefinitionKind::Environment => "environment",
183            DefinitionKind::Specials => "specials",
184        },
185    );
186    put_count(out, definition.args.len());
187    for arg in &definition.args {
188        put_arg(out, arg);
189    }
190    put_opt(out, definition.content.as_deref());
191    put(out, definition.modes.token());
192    put_count(out, definition.defaults.len());
193    for (key, text) in &definition.defaults {
194        put(out, key);
195        put(out, text);
196    }
197    put_count(out, definition.argument_number_offset);
198    put_role(out, definition.block_role);
199    put(
200        out,
201        match definition.expand {
202            ExpandPolicy::Always => "always",
203            ExpandPolicy::PerPlan => "per-plan",
204        },
205    );
206    put_count(out, usize::from(definition.overrides));
207    put_count(out, definition.extra_placeholders.len());
208    for extra in &definition.extra_placeholders {
209        put(out, &extra.name);
210        put_count(out, usize::from(extra.substitution));
211    }
212}
213
214/// Writes a block role: its kind, then the two whitespace-absorption flags of
215/// an inline role, or the placement of a block decorator.
216fn put_role(out: &mut Vec<u8>, role: BlockRole) {
217    match role {
218        BlockRole::Block => put(out, "block"),
219        BlockRole::Inline(spacing) => {
220            put(out, "inline");
221            put_count(out, usize::from(spacing.absorb_before));
222            put_count(out, usize::from(spacing.absorb_after));
223        }
224        BlockRole::Displayed => put(out, "displayed"),
225        BlockRole::BlockDecorator(placement) => {
226            put(out, "decorator");
227            put(
228                out,
229                match placement {
230                    Placement::Leads => "leads",
231                    Placement::Trails => "trails",
232                    Placement::Free => "free",
233                },
234            );
235        }
236    }
237}
238
239/// Writes one argument: its name; the identity of its parser
240/// ([`FlmArgumentParser::identity`](crate::lang::mint::FlmArgumentParser::identity)),
241/// its length first; its parsing mode; its layout; whether it is declared with
242/// an opaque wrapper; its scoped packages, their count first; and its state
243/// events, their count first.
244///
245/// The identity of a standard parser gives its kind with every parameter it
246/// holds, whether the argument was read from a code or from a structured
247/// syntax, so two arguments that differ in one parameter are written apart;
248/// for a tack-on argument, it gives each field's name, arguments and whether
249/// it repeats. The parsing mode is written as
250/// the `Debug` output of techy's parse mode (`Some(Math)`), and each state
251/// event as the `Debug` output of [`FlmEvent`](crate::lang::FlmEvent); neither
252/// holds a memory address, and the registry digest writes both the same way.
253fn put_arg(out: &mut Vec<u8>, arg: &ArgDef) {
254    put_opt(out, arg.name.as_deref());
255    let identity = arg.kind.identity();
256    put_count(out, identity.len());
257    out.extend_from_slice(&identity);
258    put(out, &format!("{:?}", arg.mode));
259    put(
260        out,
261        match arg.layout {
262            ArgLayout::Inline => "inline",
263            ArgLayout::Blocks => "blocks",
264            ArgLayout::InlineOrBlocks => "inline-or-blocks",
265        },
266    );
267    put_count(out, usize::from(arg.opaque_wrapper));
268    put_count(out, arg.scoped.len());
269    for package in &arg.scoped {
270        put(out, package.as_str());
271    }
272    put_count(out, arg.events.len());
273    for event in &arg.events {
274        put(out, &format!("{event:?}"));
275    }
276}
277
278/// The settings of the [`userdefs`](super) feature as data gives them: the user
279/// definitions in one map per kind, and the expansion depth limit.
280///
281/// The library reads the settings into this type and converts it to a
282/// [`UserdefsConfig`] with `From`: the macros in the order written, then the
283/// environments, then the special character sequences, each entry giving the
284/// definitions that [`DefinitionData::definitions`] returns for it (one, or one
285/// per parsing mode). The field documentation below is the description of each
286/// settings key in the settings' JSON Schema.
287///
288/// # Examples
289///
290/// ```
291/// use flm_core::stdlib::features::userdefs::{Definition, UserdefsConfig, UserdefsData};
292///
293/// let data = serde_json::json!({
294///     "macros": { "hi": { "content": "Hello" } },
295///     "environments": { "hi": { "content": "#{body}" } },
296/// });
297/// let config = UserdefsConfig::from(serde_json::from_value::<UserdefsData>(data)?);
298/// assert_eq!(config.definitions.len(), 2);
299/// assert_eq!(config.definitions[1].display_name(), "\\begin{hi}");
300/// # Ok::<(), serde_json::Error>(())
301/// ```
302#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
303#[serde(default, deny_unknown_fields)]
304pub struct UserdefsData {
305    /// The macros: a map from a macro's name, without the backslash, to its
306    /// definition. The order written is kept.
307    #[serde(deserialize_with = "named::deserialize")]
308    #[schemars(
309        transform = named::map_schema,
310        with = "BTreeMap<String, DefinitionData>"
311    )]
312    pub macros: Vec<NamedDefinition>,
313    /// The environments: a map from an environment's name to its definition.
314    /// The order written is kept.
315    #[serde(deserialize_with = "named::deserialize")]
316    #[schemars(
317        transform = named::map_schema,
318        with = "BTreeMap<String, DefinitionData>"
319    )]
320    pub environments: Vec<NamedDefinition>,
321    /// The special character sequences: a map from the characters of a
322    /// sequence to its definition. The order written is kept.
323    #[serde(deserialize_with = "named::deserialize")]
324    #[schemars(
325        transform = named::map_schema,
326        with = "BTreeMap<String, DefinitionData>"
327    )]
328    pub specials: Vec<NamedDefinition>,
329    /// The expansion depth limit: how many expansions one chain of use sites
330    /// may nest before a use site is reported with
331    /// `flm.userdefs.recursion-limit`. The default is 32
332    /// ([`UserdefsConfig::recursion_limit`]).
333    pub recursion_limit: usize,
334}
335
336impl Default for UserdefsData {
337    fn default() -> UserdefsData {
338        UserdefsData {
339            macros: Vec::new(),
340            environments: Vec::new(),
341            specials: Vec::new(),
342            recursion_limit: UserdefsConfig::default().recursion_limit,
343        }
344    }
345}
346
347impl From<UserdefsData> for UserdefsConfig {
348    fn from(data: UserdefsData) -> UserdefsConfig {
349        let kinds = [
350            (DefinitionKind::Macro, data.macros),
351            (DefinitionKind::Environment, data.environments),
352            (DefinitionKind::Specials, data.specials),
353        ];
354        let definitions = kinds.into_iter().flat_map(|(kind, entries)| {
355            entries.into_iter().flat_map(move |entry| entry.definition.definitions(kind, entry.name))
356        });
357        UserdefsConfig::new().definitions(definitions).recursion_limit(data.recursion_limit)
358    }
359}
360
361/// One entry of a map of [`UserdefsData`]: the name the entry is written under,
362/// and the definition written there.
363#[derive(Debug, Clone)]
364pub struct NamedDefinition {
365    /// The name the entry is written under: a macro's or an environment's
366    /// name, or the characters of a special character sequence.
367    pub name: Name,
368    /// The definition written under that name.
369    pub definition: DefinitionData,
370}
371
372impl NamedEntry for NamedDefinition {
373    fn read_entry(name: &str, data: Value) -> Result<NamedDefinition, String> {
374        let definition = named::read_unnamed(name, data)?;
375        Ok(NamedDefinition { name: Name::from(name), definition })
376    }
377}
378
379/// A user definition as data gives it, under its name in the map of its kind
380/// ([`UserdefsData`]): the fields of a [`Definition`] except its name, its
381/// kind and its parsing modes, which the entry's name, the map and the content
382/// give, and except its extra placeholders
383/// ([`Definition::extra_placeholder`]), which only a definition declared in
384/// Rust can have. A field not written keeps the value that
385/// [`Definition::new`] gives it.
386///
387/// [`definitions`](DefinitionData::definitions) returns the definitions the
388/// entry declares, given its kind and its name. The field documentation below
389/// is the description of each settings key in the settings' JSON Schema.
390#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
391#[serde(default, deny_unknown_fields)]
392pub struct DefinitionData {
393    /// The arguments, in the order they are written at a use site. Each
394    /// argument gives its syntax as a structured syntax: a map whose key
395    /// `syntax` holds the name of a standard kind of argument and whose other
396    /// keys hold the kind's parameters, beside the argument's own keys
397    /// (`name`, `mode`, `layout`, `opaque_wrapper`, `scoped`, `events`, `docs`,
398    /// `role`),
399    /// as in `{syntax: delimited-group, delimiters: ["(", ")"], name: size}`
400    /// for a group in parentheses named `size`. An argument code is a
401    /// shorthand for a structured syntax: in a map, the key `code` holds it in
402    /// place of `syntax`, so `{code: "r()", name: size}` declares the same
403    /// argument; a code alone (`"{"`) declares an argument with no other key.
404    /// The list is written in one of three shapes: one text in which each
405    /// character is one code (`"[{"`); a list of codes (`["[", "r()"]`); or a
406    /// list whose entries are each a code or a map. The kinds and their
407    /// parameters are listed in [the documentation of the standard
408    /// kinds](crate::lang::mint::ArgStdKind#the-kind-as-data), and the codes
409    /// in [the table of argument codes](crate::lang::mint::codes#the-codes).
410    #[serde(deserialize_with = "deserialize_arg_list")]
411    #[schemars(with = "ArgListData")]
412    pub args: Vec<ArgDef>,
413    /// The template: FLM text with placeholders, which replaces every use site.
414    /// One text is the template in text mode and in mathematics mode, and the
415    /// definition applies in each mode where the text parses. A map with the
416    /// keys `text` and `math`, one or both written, gives one template per
417    /// mode, and the definition applies in the modes written.
418    pub content: Option<DefinitionContent>,
419    /// The default values of the arguments: template text, keyed by the
420    /// argument's declared name or by the number a placeholder refers to it
421    /// by. A default value replaces the placeholders of an argument that a use
422    /// site leaves out.
423    pub defaults: BTreeMap<String, String>,
424    /// The argument number offset: how many of the first declared arguments
425    /// the numbered placeholders skip, so that `#1` refers to the argument at
426    /// this index (counting from zero).
427    pub argument_number_offset: usize,
428    /// The block role of the definition's element: a block of its own, inline
429    /// content, a displayed item, or a block decorator.
430    pub block_role: BlockRole,
431    /// When the use sites are expanded: `always`, in every plan, or `per-plan`
432    /// (the default), as each plan decides.
433    pub expand: ExpandPolicy,
434    /// Whether this definition replaces another feature's definition of the
435    /// same command. Without it, two features that define one command make the
436    /// registry build fail, unless the feature order places the feature
437    /// registered last explicitly after the other.
438    pub overrides: bool,
439    /// The definition's documentation, shown wherever the registry describes
440    /// its element.
441    pub docs: String,
442}
443
444impl Default for DefinitionData {
445    fn default() -> DefinitionData {
446        // A field not written keeps what the Rust constructor gives it; the
447        // kind and the name chosen here reach no field below.
448        let base = Definition::new(DefinitionKind::Macro, "", Vec::new());
449        DefinitionData {
450            args: base.args,
451            content: None,
452            defaults: base.defaults,
453            argument_number_offset: base.argument_number_offset,
454            block_role: base.block_role,
455            expand: base.expand,
456            overrides: base.overrides,
457            docs: base.docs,
458        }
459    }
460}
461
462impl DefinitionData {
463    /// Returns the definitions the entry declares as a definition of kind
464    /// `kind` with the name `name`: one definition that applies in both modes
465    /// when the content is one text or is not written; for a content given per
466    /// mode, one definition per mode written, the one for text mode first, each
467    /// applying in its mode alone (as [`Definition::text`] and
468    /// [`Definition::math`] declare).
469    pub fn definitions(self, kind: DefinitionKind, name: impl Into<Name>) -> Vec<Definition> {
470        let base = Definition {
471            defaults: self.defaults,
472            argument_number_offset: self.argument_number_offset,
473            block_role: self.block_role,
474            expand: self.expand,
475            overrides: self.overrides,
476            ..Definition::new(kind, name, self.args)
477        }
478        .docs(self.docs);
479        match self.content {
480            None => vec![base],
481            Some(content) => content.definitions(base),
482        }
483    }
484}
485
486impl DefinitionContent {
487    /// Returns the definitions this content declares from `base`, a
488    /// definition complete except for its template: for one text, one
489    /// definition that applies in both modes (in each mode where the text
490    /// parses); for a content given per mode, one definition per mode written,
491    /// the one for text mode first, each applying in its mode alone (as
492    /// [`Definition::text`] and [`Definition::math`] declare).
493    ///
494    /// Every feature that reads a definition's `content` key from data calls
495    /// this function, so that the key has the same meaning wherever it is
496    /// written.
497    ///
498    /// # Examples
499    ///
500    /// ```
501    /// use flm_core::lang::rewrites::userdefs::DefinitionModes;
502    /// use flm_core::stdlib::features::userdefs::{Definition, DefinitionContent};
503    ///
504    /// let base = Definition::macro_("ket", Vec::new());
505    /// let one = DefinitionContent::Both(String::from("x")).definitions(base.clone());
506    /// assert_eq!(one.len(), 1);
507    /// assert_eq!(one[0].modes, DefinitionModes::Both);
508    ///
509    /// let by_mode: DefinitionContent = serde_json::from_str(r#"{"text": "t", "math": "m"}"#).unwrap();
510    /// let two = by_mode.definitions(base);
511    /// let modes: Vec<DefinitionModes> = two.iter().map(|definition| definition.modes).collect();
512    /// assert_eq!(modes, [DefinitionModes::Text, DefinitionModes::Math]);
513    /// ```
514    pub fn definitions(self, base: Definition) -> Vec<Definition> {
515        match self {
516            DefinitionContent::Both(template) => vec![base.content(template)],
517            DefinitionContent::ByMode(templates) => {
518                let mut definitions = Vec::new();
519                if let Some(template) = templates.text {
520                    definitions.push(base.clone().text(template));
521                }
522                if let Some(template) = templates.math {
523                    definitions.push(base.math(template));
524                }
525                definitions
526            }
527        }
528    }
529}
530
531/// The `content` key of a [`DefinitionData`]: one template for both parsing
532/// modes, or one template per mode.
533///
534/// In data, it is a text or a map with the keys `text` and `math`. A map that
535/// gives neither key, and a value of any other form, are refused when the
536/// settings are read.
537#[derive(Debug, Clone, PartialEq, Eq, schemars::JsonSchema)]
538#[schemars(untagged)]
539pub enum DefinitionContent {
540    /// One template for text mode and mathematics mode; the definition applies
541    /// in each mode where it parses.
542    Both(String),
543    /// One template per mode, at least one of the two given.
544    ByMode(ModeTemplates),
545}
546
547impl<'de> Deserialize<'de> for DefinitionContent {
548    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
549        use serde::de::Error;
550        match Value::deserialize(deserializer)? {
551            Value::String(template) => Ok(DefinitionContent::Both(template)),
552            value @ Value::Object(_) => {
553                let templates: ModeTemplates = serde_json::from_value(value).map_err(D::Error::custom)?;
554                if templates.text.is_none() && templates.math.is_none() {
555                    return Err(D::Error::custom(
556                        "a `content` map must give `text`, `math` or both",
557                    ));
558                }
559                Ok(DefinitionContent::ByMode(templates))
560            }
561            other => Err(D::Error::custom(format!(
562                "`content` must be a text or a map with the keys `text` and `math`, not `{other}`"
563            ))),
564        }
565    }
566}
567
568/// The templates of a content given per mode ([`DefinitionContent::ByMode`]);
569/// at least one is given.
570#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
571#[serde(default, deny_unknown_fields)]
572#[schemars(extend("minProperties" = 1))]
573pub struct ModeTemplates {
574    /// The template for text mode.
575    #[schemars(with = "String")]
576    pub text: Option<String>,
577    /// The template for mathematics mode.
578    #[schemars(with = "String")]
579    pub math: Option<String>,
580}
581
582#[cfg(test)]
583mod tests {
584    use super::*;
585    use crate::model::digest::digest_of;
586
587    fn config(template: &str) -> UserdefsConfig {
588        UserdefsConfig::new()
589            .definition(Definition::macro_("foo", vec![ArgDef::mandatory("x")]).text(template))
590    }
591
592    #[test]
593    fn the_default_limit_is_the_passes() {
594        assert_eq!(UserdefsConfig::new().recursion_limit, DEFAULT_RECURSION_LIMIT);
595        assert!(UserdefsConfig::new().definitions.is_empty());
596    }
597
598    #[test]
599    fn the_rendering_sees_the_template_text() {
600        assert_ne!(config("#1").digest_bytes(), config("#1!").digest_bytes());
601        assert_eq!(config("#1").digest_bytes(), config("#1").digest_bytes());
602    }
603
604    #[test]
605    fn the_rendering_sees_the_parsing_modes() {
606        let in_math = UserdefsConfig::new()
607            .definition(Definition::macro_("foo", vec![ArgDef::mandatory("x")]).math("#1"));
608        let in_both = UserdefsConfig::new().definition(
609            Definition::macro_("foo", vec![ArgDef::mandatory("x")]).content("#1"),
610        );
611        // `config` declares the same template text in text mode alone.
612        assert_ne!(config("#1").digest_bytes(), in_math.digest_bytes());
613        assert_ne!(config("#1").digest_bytes(), in_both.digest_bytes());
614        assert_ne!(in_math.digest_bytes(), in_both.digest_bytes());
615    }
616
617    #[test]
618    fn the_rendering_sees_the_argument_number_offset() {
619        let shifted = UserdefsConfig::new().definition(
620            Definition::macro_("foo", vec![ArgDef::mandatory("x")])
621                .text("#1")
622                .argument_number_offset(1),
623        );
624        assert_ne!(config("#1").digest_bytes(), shifted.digest_bytes());
625    }
626
627    #[test]
628    fn the_rendering_sees_the_depth_limit() {
629        assert_ne!(
630            config("#1").digest_bytes(),
631            config("#1").recursion_limit(3).digest_bytes()
632        );
633    }
634
635    #[test]
636    fn the_rendering_sees_an_arguments_mode_layout_scoped_packages_and_events() {
637        let with = |arg: ArgDef| {
638            UserdefsConfig::new().definition(Definition::macro_("foo", vec![arg]).text("#1"))
639        };
640        let plain = with(ArgDef::mandatory("x")).digest_bytes();
641        let in_math = with(ArgDef::mandatory("x").mode(techy::latexlike::Mode::Math));
642        let as_blocks = with(ArgDef::mandatory("x").layout(ArgLayout::Blocks));
643        let scoped = with(ArgDef::mandatory("x").scoped(crate::model::names::Name::new("some.package")));
644        assert_ne!(plain, in_math.digest_bytes());
645        assert_ne!(plain, as_blocks.digest_bytes());
646        assert_ne!(plain, scoped.digest_bytes());
647        let with_event = with(ArgDef::mandatory("x").event(crate::lang::FlmEvent::StandardState));
648        assert_ne!(plain, with_event.digest_bytes());
649        assert_eq!(plain, with(ArgDef::mandatory("x")).digest_bytes());
650    }
651
652    #[test]
653    fn documentation_is_not_semantic() {
654        let documented = UserdefsConfig::new().definition(
655            Definition::macro_("foo", vec![ArgDef::mandatory("x")]).text("#1").docs("a foo"),
656        );
657        assert_eq!(config("#1").digest_bytes(), documented.digest_bytes());
658    }
659
660    #[test]
661    fn the_hash_is_the_rendering() {
662        assert_eq!(digest_of(&config("#1")), digest_of(&config("#1")));
663        assert_ne!(digest_of(&config("#1")), digest_of(&config("#1 ")));
664    }
665}