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 and its scoped
122 /// packages), 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; and its scoped packages, their count first.
243///
244/// The identity of a standard parser gives its kind with every parameter it
245/// holds, whether the argument was read from a code or from a structured
246/// syntax, so two arguments that differ in one parameter are written apart;
247/// for a tack-on argument, it gives each field's name, arguments and whether
248/// it repeats. The parsing mode is written as
249/// the `Debug` output of techy's parse mode (`Some(Math)`), which holds no
250/// memory address; the registry digest writes it the same way.
251fn put_arg(out: &mut Vec<u8>, arg: &ArgDef) {
252 put_opt(out, arg.name.as_deref());
253 let identity = arg.kind.identity();
254 put_count(out, identity.len());
255 out.extend_from_slice(&identity);
256 put(out, &format!("{:?}", arg.mode));
257 put(
258 out,
259 match arg.layout {
260 ArgLayout::Inline => "inline",
261 ArgLayout::Blocks => "blocks",
262 ArgLayout::InlineOrBlocks => "inline-or-blocks",
263 },
264 );
265 put_count(out, usize::from(arg.opaque_wrapper));
266 put_count(out, arg.scoped.len());
267 for package in &arg.scoped {
268 put(out, package.as_str());
269 }
270}
271
272/// The settings of the [`userdefs`](super) feature as data gives them: the user
273/// definitions in one map per kind, and the expansion depth limit.
274///
275/// The library reads the settings into this type and converts it to a
276/// [`UserdefsConfig`] with `From`: the macros in the order written, then the
277/// environments, then the special character sequences, each entry giving the
278/// definitions that [`DefinitionData::definitions`] returns for it (one, or one
279/// per parsing mode). The field documentation below is the description of each
280/// settings key in the settings' JSON Schema.
281///
282/// # Examples
283///
284/// ```
285/// use flm_core::stdlib::features::userdefs::{Definition, UserdefsConfig, UserdefsData};
286///
287/// let data = serde_json::json!({
288/// "macros": { "hi": { "content": "Hello" } },
289/// "environments": { "hi": { "content": "#{body}" } },
290/// });
291/// let config = UserdefsConfig::from(serde_json::from_value::<UserdefsData>(data)?);
292/// assert_eq!(config.definitions.len(), 2);
293/// assert_eq!(config.definitions[1].display_name(), "\\begin{hi}");
294/// # Ok::<(), serde_json::Error>(())
295/// ```
296#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
297#[serde(default, deny_unknown_fields)]
298pub struct UserdefsData {
299 /// The macros: a map from a macro's name, without the backslash, to its
300 /// definition. The order written is kept.
301 #[serde(deserialize_with = "named::deserialize")]
302 #[schemars(
303 transform = named::map_schema,
304 with = "BTreeMap<String, DefinitionData>"
305 )]
306 pub macros: Vec<NamedDefinition>,
307 /// The environments: a map from an environment's name to its definition.
308 /// The order written is kept.
309 #[serde(deserialize_with = "named::deserialize")]
310 #[schemars(
311 transform = named::map_schema,
312 with = "BTreeMap<String, DefinitionData>"
313 )]
314 pub environments: Vec<NamedDefinition>,
315 /// The special character sequences: a map from the characters of a
316 /// sequence to its definition. The order written is kept.
317 #[serde(deserialize_with = "named::deserialize")]
318 #[schemars(
319 transform = named::map_schema,
320 with = "BTreeMap<String, DefinitionData>"
321 )]
322 pub specials: Vec<NamedDefinition>,
323 /// The expansion depth limit: how many expansions one chain of use sites
324 /// may nest before a use site is reported with
325 /// `flm.userdefs.recursion-limit`. The default is 32
326 /// ([`UserdefsConfig::recursion_limit`]).
327 pub recursion_limit: usize,
328}
329
330impl Default for UserdefsData {
331 fn default() -> UserdefsData {
332 UserdefsData {
333 macros: Vec::new(),
334 environments: Vec::new(),
335 specials: Vec::new(),
336 recursion_limit: UserdefsConfig::default().recursion_limit,
337 }
338 }
339}
340
341impl From<UserdefsData> for UserdefsConfig {
342 fn from(data: UserdefsData) -> UserdefsConfig {
343 let kinds = [
344 (DefinitionKind::Macro, data.macros),
345 (DefinitionKind::Environment, data.environments),
346 (DefinitionKind::Specials, data.specials),
347 ];
348 let definitions = kinds.into_iter().flat_map(|(kind, entries)| {
349 entries.into_iter().flat_map(move |entry| entry.definition.definitions(kind, entry.name))
350 });
351 UserdefsConfig::new().definitions(definitions).recursion_limit(data.recursion_limit)
352 }
353}
354
355/// One entry of a map of [`UserdefsData`]: the name the entry is written under,
356/// and the definition written there.
357#[derive(Debug, Clone)]
358pub struct NamedDefinition {
359 /// The name the entry is written under: a macro's or an environment's
360 /// name, or the characters of a special character sequence.
361 pub name: Name,
362 /// The definition written under that name.
363 pub definition: DefinitionData,
364}
365
366impl NamedEntry for NamedDefinition {
367 fn read_entry(name: &str, data: Value) -> Result<NamedDefinition, String> {
368 let definition = named::read_unnamed(name, data)?;
369 Ok(NamedDefinition { name: Name::from(name), definition })
370 }
371}
372
373/// A user definition as data gives it, under its name in the map of its kind
374/// ([`UserdefsData`]): the fields of a [`Definition`] except its name, its
375/// kind and its parsing modes, which the entry's name, the map and the content
376/// give, and except its extra placeholders
377/// ([`Definition::extra_placeholder`]), which only a definition declared in
378/// Rust can have. A field not written keeps the value that
379/// [`Definition::new`] gives it.
380///
381/// [`definitions`](DefinitionData::definitions) returns the definitions the
382/// entry declares, given its kind and its name. The field documentation below
383/// is the description of each settings key in the settings' JSON Schema.
384#[derive(Debug, Clone, serde::Deserialize, schemars::JsonSchema)]
385#[serde(default, deny_unknown_fields)]
386pub struct DefinitionData {
387 /// The arguments, in the order they are written at a use site. Each
388 /// argument gives its syntax as a structured syntax: a map whose key
389 /// `syntax` holds the name of a standard kind of argument and whose other
390 /// keys hold the kind's parameters, beside the argument's own keys
391 /// (`name`, `mode`, `layout`, `opaque_wrapper`, `scoped`, `docs`, `role`),
392 /// as in `{syntax: delimited-group, delimiters: ["(", ")"], name: size}`
393 /// for a group in parentheses named `size`. An argument code is a
394 /// shorthand for a structured syntax: in a map, the key `code` holds it in
395 /// place of `syntax`, so `{code: "r()", name: size}` declares the same
396 /// argument; a code alone (`"{"`) declares an argument with no other key.
397 /// The list is written in one of three shapes: one text in which each
398 /// character is one code (`"[{"`); a list of codes (`["[", "r()"]`); or a
399 /// list whose entries are each a code or a map. The kinds and their
400 /// parameters are listed in [the documentation of the standard
401 /// kinds](crate::lang::mint::ArgStdKind#the-kind-as-data), and the codes
402 /// in [the table of argument codes](crate::lang::mint::codes#the-codes).
403 #[serde(deserialize_with = "deserialize_arg_list")]
404 #[schemars(with = "ArgListData")]
405 pub args: Vec<ArgDef>,
406 /// The template: FLM text with placeholders, which replaces every use site.
407 /// One text is the template in text mode and in mathematics mode, and the
408 /// definition applies in each mode where the text parses. A map with the
409 /// keys `text` and `math`, one or both written, gives one template per
410 /// mode, and the definition applies in the modes written.
411 pub content: Option<DefinitionContent>,
412 /// The default values of the arguments: template text, keyed by the
413 /// argument's declared name or by the number a placeholder refers to it
414 /// by. A default value replaces the placeholders of an argument that a use
415 /// site leaves out.
416 pub defaults: BTreeMap<String, String>,
417 /// The argument number offset: how many of the first declared arguments
418 /// the numbered placeholders skip, so that `#1` refers to the argument at
419 /// this index (counting from zero).
420 pub argument_number_offset: usize,
421 /// The block role of the definition's element: a block of its own, inline
422 /// content, a displayed item, or a block decorator.
423 pub block_role: BlockRole,
424 /// When the use sites are expanded: `always`, in every plan, or `per-plan`
425 /// (the default), as each plan decides.
426 pub expand: ExpandPolicy,
427 /// Whether this definition replaces another feature's definition of the
428 /// same command. Without it, two features that define one command make the
429 /// registry build fail, unless the feature order places the feature
430 /// registered last explicitly after the other.
431 pub overrides: bool,
432 /// The definition's documentation, shown wherever the registry describes
433 /// its element.
434 pub docs: String,
435}
436
437impl Default for DefinitionData {
438 fn default() -> DefinitionData {
439 // A field not written keeps what the Rust constructor gives it; the
440 // kind and the name chosen here reach no field below.
441 let base = Definition::new(DefinitionKind::Macro, "", Vec::new());
442 DefinitionData {
443 args: base.args,
444 content: None,
445 defaults: base.defaults,
446 argument_number_offset: base.argument_number_offset,
447 block_role: base.block_role,
448 expand: base.expand,
449 overrides: base.overrides,
450 docs: base.docs,
451 }
452 }
453}
454
455impl DefinitionData {
456 /// Returns the definitions the entry declares as a definition of kind
457 /// `kind` with the name `name`: one definition that applies in both modes
458 /// when the content is one text or is not written; for a content given per
459 /// mode, one definition per mode written, the one for text mode first, each
460 /// applying in its mode alone (as [`Definition::text`] and
461 /// [`Definition::math`] declare).
462 pub fn definitions(self, kind: DefinitionKind, name: impl Into<Name>) -> Vec<Definition> {
463 let base = Definition {
464 defaults: self.defaults,
465 argument_number_offset: self.argument_number_offset,
466 block_role: self.block_role,
467 expand: self.expand,
468 overrides: self.overrides,
469 ..Definition::new(kind, name, self.args)
470 }
471 .docs(self.docs);
472 match self.content {
473 None => vec![base],
474 Some(content) => content.definitions(base),
475 }
476 }
477}
478
479impl DefinitionContent {
480 /// Returns the definitions this content declares from `base`, a
481 /// definition complete except for its template: for one text, one
482 /// definition that applies in both modes (in each mode where the text
483 /// parses); for a content given per mode, one definition per mode written,
484 /// the one for text mode first, each applying in its mode alone (as
485 /// [`Definition::text`] and [`Definition::math`] declare).
486 ///
487 /// Every feature that reads a definition's `content` key from data calls
488 /// this function, so that the key has the same meaning wherever it is
489 /// written.
490 ///
491 /// # Examples
492 ///
493 /// ```
494 /// use flm_core::lang::rewrites::userdefs::DefinitionModes;
495 /// use flm_core::stdlib::features::userdefs::{Definition, DefinitionContent};
496 ///
497 /// let base = Definition::macro_("ket", Vec::new());
498 /// let one = DefinitionContent::Both(String::from("x")).definitions(base.clone());
499 /// assert_eq!(one.len(), 1);
500 /// assert_eq!(one[0].modes, DefinitionModes::Both);
501 ///
502 /// let by_mode: DefinitionContent = serde_json::from_str(r#"{"text": "t", "math": "m"}"#).unwrap();
503 /// let two = by_mode.definitions(base);
504 /// let modes: Vec<DefinitionModes> = two.iter().map(|definition| definition.modes).collect();
505 /// assert_eq!(modes, [DefinitionModes::Text, DefinitionModes::Math]);
506 /// ```
507 pub fn definitions(self, base: Definition) -> Vec<Definition> {
508 match self {
509 DefinitionContent::Both(template) => vec![base.content(template)],
510 DefinitionContent::ByMode(templates) => {
511 let mut definitions = Vec::new();
512 if let Some(template) = templates.text {
513 definitions.push(base.clone().text(template));
514 }
515 if let Some(template) = templates.math {
516 definitions.push(base.math(template));
517 }
518 definitions
519 }
520 }
521 }
522}
523
524/// The `content` key of a [`DefinitionData`]: one template for both parsing
525/// modes, or one template per mode.
526///
527/// In data, it is a text or a map with the keys `text` and `math`. A map that
528/// gives neither key, and a value of any other form, are refused when the
529/// settings are read.
530#[derive(Debug, Clone, PartialEq, Eq, schemars::JsonSchema)]
531#[schemars(untagged)]
532pub enum DefinitionContent {
533 /// One template for text mode and mathematics mode; the definition applies
534 /// in each mode where it parses.
535 Both(String),
536 /// One template per mode, at least one of the two given.
537 ByMode(ModeTemplates),
538}
539
540impl<'de> Deserialize<'de> for DefinitionContent {
541 fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
542 use serde::de::Error;
543 match Value::deserialize(deserializer)? {
544 Value::String(template) => Ok(DefinitionContent::Both(template)),
545 value @ Value::Object(_) => {
546 let templates: ModeTemplates = serde_json::from_value(value).map_err(D::Error::custom)?;
547 if templates.text.is_none() && templates.math.is_none() {
548 return Err(D::Error::custom(
549 "a `content` map must give `text`, `math` or both",
550 ));
551 }
552 Ok(DefinitionContent::ByMode(templates))
553 }
554 other => Err(D::Error::custom(format!(
555 "`content` must be a text or a map with the keys `text` and `math`, not `{other}`"
556 ))),
557 }
558 }
559}
560
561/// The templates of a content given per mode ([`DefinitionContent::ByMode`]);
562/// at least one is given.
563#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Deserialize, schemars::JsonSchema)]
564#[serde(default, deny_unknown_fields)]
565#[schemars(extend("minProperties" = 1))]
566pub struct ModeTemplates {
567 /// The template for text mode.
568 #[schemars(with = "String")]
569 pub text: Option<String>,
570 /// The template for mathematics mode.
571 #[schemars(with = "String")]
572 pub math: Option<String>,
573}
574
575#[cfg(test)]
576mod tests {
577 use super::*;
578 use crate::model::digest::digest_of;
579
580 fn config(template: &str) -> UserdefsConfig {
581 UserdefsConfig::new()
582 .definition(Definition::macro_("foo", vec![ArgDef::mandatory("x")]).text(template))
583 }
584
585 #[test]
586 fn the_default_limit_is_the_passes() {
587 assert_eq!(UserdefsConfig::new().recursion_limit, DEFAULT_RECURSION_LIMIT);
588 assert!(UserdefsConfig::new().definitions.is_empty());
589 }
590
591 #[test]
592 fn the_rendering_sees_the_template_text() {
593 assert_ne!(config("#1").digest_bytes(), config("#1!").digest_bytes());
594 assert_eq!(config("#1").digest_bytes(), config("#1").digest_bytes());
595 }
596
597 #[test]
598 fn the_rendering_sees_the_parsing_modes() {
599 let in_math = UserdefsConfig::new()
600 .definition(Definition::macro_("foo", vec![ArgDef::mandatory("x")]).math("#1"));
601 let in_both = UserdefsConfig::new().definition(
602 Definition::macro_("foo", vec![ArgDef::mandatory("x")]).content("#1"),
603 );
604 // `config` declares the same template text in text mode alone.
605 assert_ne!(config("#1").digest_bytes(), in_math.digest_bytes());
606 assert_ne!(config("#1").digest_bytes(), in_both.digest_bytes());
607 assert_ne!(in_math.digest_bytes(), in_both.digest_bytes());
608 }
609
610 #[test]
611 fn the_rendering_sees_the_argument_number_offset() {
612 let shifted = UserdefsConfig::new().definition(
613 Definition::macro_("foo", vec![ArgDef::mandatory("x")])
614 .text("#1")
615 .argument_number_offset(1),
616 );
617 assert_ne!(config("#1").digest_bytes(), shifted.digest_bytes());
618 }
619
620 #[test]
621 fn the_rendering_sees_the_depth_limit() {
622 assert_ne!(
623 config("#1").digest_bytes(),
624 config("#1").recursion_limit(3).digest_bytes()
625 );
626 }
627
628 #[test]
629 fn the_rendering_sees_an_arguments_mode_layout_and_scoped_packages() {
630 let with = |arg: ArgDef| {
631 UserdefsConfig::new().definition(Definition::macro_("foo", vec![arg]).text("#1"))
632 };
633 let plain = with(ArgDef::mandatory("x")).digest_bytes();
634 let in_math = with(ArgDef::mandatory("x").mode(techy::latexlike::Mode::Math));
635 let as_blocks = with(ArgDef::mandatory("x").layout(ArgLayout::Blocks));
636 let scoped = with(ArgDef::mandatory("x").scoped(crate::model::names::Name::new("some.package")));
637 assert_ne!(plain, in_math.digest_bytes());
638 assert_ne!(plain, as_blocks.digest_bytes());
639 assert_ne!(plain, scoped.digest_bytes());
640 assert_eq!(plain, with(ArgDef::mandatory("x")).digest_bytes());
641 }
642
643 #[test]
644 fn documentation_is_not_semantic() {
645 let documented = UserdefsConfig::new().definition(
646 Definition::macro_("foo", vec![ArgDef::mandatory("x")]).text("#1").docs("a foo"),
647 );
648 assert_eq!(config("#1").digest_bytes(), documented.digest_bytes());
649 }
650
651 #[test]
652 fn the_hash_is_the_rendering() {
653 assert_eq!(digest_of(&config("#1")), digest_of(&config("#1")));
654 assert_ne!(digest_of(&config("#1")), digest_of(&config("#1 ")));
655 }
656}