Skip to main content

flm_core/core/registry/
declarations.rs

1//! The element declarations a registry was built from, kept as declared:
2//! [`Declarations`], and the references into them that its accessors return.
3//!
4//! A feature declares what an author may write in a document with element
5//! declarations ([`ElementDef`]: the names a command is written under, its
6//! syntax, its arguments, its parsing modes and its documentation), scoped
7//! packages ([`ScopedPackageDef`]), fallbacks ([`FallbackDef`]) and overrides
8//! ([`OverrideDef`]). The registry build turns them into the FLM language
9//! that documents are parsed with
10//! ([`FlmRegistry::lang`](super::FlmRegistry::lang)), which keeps only what a
11//! parse needs. The registry also keeps the declarations themselves in a
12//! [`Declarations`] value
13//! ([`FlmRegistry::declarations`](super::FlmRegistry::declarations)), so
14//! that a program can describe what an author may write: every command with
15//! its syntax, its arguments and their roles, and its documentation.
16//!
17//! The declarations are the ones the build used: a [peer element
18//! value](super::FeatureBuilder::peer_element_value) whose element type some
19//! feature declares is kept where it was declared, and one whose element type
20//! no feature declares is not there, since the build dropped it. Each element
21//! declaration holds the element value the registry numbered, with the
22//! aspects features attached to it.
23//!
24//! Keeping the declarations costs little: a declaration shares its parsers and
25//! its element value with the language through `Arc`s, and only its strings
26//! are its own.
27
28use crate::lang::mint::packages::{feature_stack_order, is_weak};
29use crate::lang::mint::{
30    ArgDef, CallableKind, ElementDef, FallbackDef, OverrideDef, ScopedPackageDef, SyntaxDef,
31    TackOnField,
32};
33
34/// The element declarations, scoped packages, fallbacks and overrides that
35/// the features of a registry declared, as declared.
36///
37/// The element declarations are in the order in which the language stacks
38/// the features' definitions (see [`elements`](Declarations::elements)), so
39/// that, in a parsing mode, the last declaration of a command is the one in
40/// force. Everything else is in registration order.
41///
42/// Get it from
43/// [`FlmRegistry::declarations`](super::FlmRegistry::declarations). The list
44/// accessors ([`elements`](Declarations::elements),
45/// [`scoped_packages`](Declarations::scoped_packages),
46/// [`fallbacks`](Declarations::fallbacks),
47/// [`overrides`](Declarations::overrides)) return everything; the other
48/// accessors answer the usual questions of a program that describes the
49/// language: the commands of one feature
50/// ([`elements_of`](Declarations::elements_of)), the declarations of one
51/// command ([`named`](Declarations::named)), a scoped package and the places
52/// that make it available ([`scoped_package`](Declarations::scoped_package),
53/// [`scoped_package_uses`](Declarations::scoped_package_uses)), and the
54/// arguments that hold a given kind of thing
55/// ([`arguments`](Declarations::arguments),
56/// [`role_uses`](Declarations::role_uses)).
57///
58/// # Examples
59///
60/// ```
61/// use std::sync::Arc;
62/// use flm_core::core::registry::{BuildError, FeatureBuilder, FeatureInfo, FlmFeature, build_registry};
63/// use flm_core::lang::mint::{ArgDef, CallableKind, ElementDef, SyntaxDef};
64/// use flm_core::model::element::ElementSpec;
65///
66/// struct Shout;
67/// impl FlmFeature for Shout {
68///     fn info(&self) -> FeatureInfo { FeatureInfo::new("shout", "Shouting") }
69///     fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
70///         let element = Arc::new(ElementSpec::new("shout.shout"));
71///         let syntax = SyntaxDef::Macro { args: vec![ArgDef::mandatory("text")] };
72///         b.element(ElementDef::new("shout", ["shout"], syntax, element).docs("Shouted text."))
73///     }
74/// }
75///
76/// let registry = build_registry([Arc::new(Shout) as Arc<dyn FlmFeature>])?;
77/// let found = registry.declarations().named(CallableKind::Macro, "shout");
78/// assert_eq!(found.len(), 1);
79/// # #[cfg(feature = "docs")]
80/// assert_eq!(found[0].docs, "Shouted text.");
81/// assert_eq!(found[0].syntax.args()[0].name.as_deref(), Some("text"));
82/// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
83/// ```
84#[derive(Debug, Clone)]
85pub struct Declarations {
86    elements: Vec<ElementDef>,
87    scoped_packages: Vec<ScopedPackageDef>,
88    fallbacks: Vec<FallbackDef>,
89    overrides: Vec<OverrideDef>,
90}
91
92/// One argument declaration among a registry's [`Declarations`], with where
93/// it is declared: the element declaration it belongs to, the scoped package
94/// that holds that declaration, and the tack-on field whose own argument list
95/// holds it.
96///
97/// [`Declarations::arguments`] and [`Declarations::role_uses`] return it.
98#[derive(Debug, Clone, Copy)]
99pub struct ArgumentRef<'a> {
100    /// The element declaration the argument belongs to. Its
101    /// [`owner`](ElementDef::owner) is the feature that declared it.
102    pub declaration: &'a ElementDef,
103    /// The scoped package that holds the element declaration, or `None` for
104    /// a declaration a feature made directly
105    /// ([`FeatureBuilder::element`](super::FeatureBuilder::element)).
106    pub within: Option<&'a ScopedPackageDef>,
107    /// The [tack-on field](TackOnField) whose own argument list holds the
108    /// argument (the innermost one, for a field written in another field's
109    /// argument), or `None` for an argument of the element declaration
110    /// itself.
111    pub field: Option<&'a TackOnField>,
112    /// The argument's position, counting from zero, in the argument list
113    /// that holds it: the element declaration's own, or the field's.
114    pub index: usize,
115    /// The argument declaration.
116    pub arg: &'a ArgDef,
117}
118
119/// One place where an element declaration makes a scoped package available:
120/// an environment's body ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped))
121/// or an argument ([`ArgDef::scoped`]).
122///
123/// [`Declarations::scoped_package_uses`] returns it.
124#[derive(Debug, Clone, Copy)]
125pub enum ScopedPackageUse<'a> {
126    /// The body of an environment makes the package available inside it.
127    Body {
128        /// The environment's declaration. Its [`owner`](ElementDef::owner)
129        /// is the feature that declared it.
130        declaration: &'a ElementDef,
131        /// The scoped package that holds the declaration, or `None` for a
132        /// declaration a feature made directly.
133        within: Option<&'a ScopedPackageDef>,
134    },
135    /// An argument makes the package available inside it.
136    Argument(ArgumentRef<'a>),
137}
138
139impl<'a> ScopedPackageUse<'a> {
140    /// The element declaration whose body or argument makes the package
141    /// available.
142    pub fn declaration(&self) -> &'a ElementDef {
143        match self {
144            ScopedPackageUse::Body { declaration, .. } => declaration,
145            ScopedPackageUse::Argument(argument) => argument.declaration,
146        }
147    }
148
149    /// The scoped package that holds that declaration, or `None` for a
150    /// declaration a feature made directly.
151    pub fn within(&self) -> Option<&'a ScopedPackageDef> {
152        match self {
153            ScopedPackageUse::Body { within, .. } => *within,
154            ScopedPackageUse::Argument(argument) => argument.within,
155        }
156    }
157}
158
159/// Adds to `out` every argument of the element declaration `def`, held in
160/// the scoped package `within` if any, in the order written: each argument
161/// of the declaration, followed by the arguments of each of its tack-on
162/// fields, and so on for a field's own tack-on arguments.
163pub(crate) fn arguments_of<'a>(
164    def: &'a ElementDef,
165    within: Option<&'a ScopedPackageDef>,
166    out: &mut Vec<ArgumentRef<'a>>,
167) {
168    arguments_in(def, within, None, def.syntax.args(), out);
169}
170
171/// Adds to `out` the arguments `args` of the declaration `def`, held in the
172/// list of the tack-on field `field` (or the declaration's own list), each
173/// followed by the arguments of its tack-on fields.
174fn arguments_in<'a>(
175    def: &'a ElementDef,
176    within: Option<&'a ScopedPackageDef>,
177    field: Option<&'a TackOnField>,
178    args: &'a [ArgDef],
179    out: &mut Vec<ArgumentRef<'a>>,
180) {
181    for (index, arg) in args.iter().enumerate() {
182        out.push(ArgumentRef { declaration: def, within, field, index, arg });
183        for inner in arg.kind.tack_on_fields().unwrap_or_default() {
184            arguments_in(def, within, Some(inner), &inner.args, out);
185        }
186    }
187}
188
189impl Declarations {
190    /// The declarations as the build leaves them, moved into the frozen
191    /// registry, with the weak element declarations before the ordinary ones,
192    /// each part grouped by feature in the order of [`feature_stack_order`].
193    pub(crate) fn new(
194        mut elements: Vec<ElementDef>,
195        scoped_packages: Vec<ScopedPackageDef>,
196        fallbacks: Vec<FallbackDef>,
197        overrides: Vec<OverrideDef>,
198    ) -> Declarations {
199        // The build lists a finalizer's declarations after every declaration
200        // of the first registration round, while the language stacks each
201        // feature's definitions together, at the place of its first
202        // declaration, every feature's weak declarations under every
203        // feature's ordinary ones. The sort is stable, so each feature's
204        // declarations of one weakness keep the order it made them in.
205        let order = feature_stack_order(&elements);
206        elements.sort_by_key(|def| {
207            (!is_weak(def), order.iter().position(|owner| *owner == def.owner))
208        });
209        Declarations { elements, scoped_packages, fallbacks, overrides }
210    }
211
212    /// Every element declaration a feature made directly
213    /// ([`FeatureBuilder::element`](super::FeatureBuilder::element)),
214    /// grouped by feature. The declarations held by scoped packages are not
215    /// among them: see [`scoped_packages`](Declarations::scoped_packages).
216    ///
217    /// The declarations come in the order in which the language stacks the
218    /// features' definitions, so that, in a parsing mode, the last
219    /// declaration of a command is the one in force. The weak declarations
220    /// ([`ElementDef::weak`]) of every feature come first, then the ordinary
221    /// ones. In each of these two parts, the features come in the order of
222    /// each feature's first element declaration, a later feature's definition
223    /// of a command replacing an earlier one's: the final order of the
224    /// features ([`FlmRegistry::features`](super::FlmRegistry::features))
225    /// among those that declare elements when they register. A feature whose
226    /// only element declarations come from a [`Finalizer`](super::Finalizer)
227    /// comes after them. Each feature's declarations of one part are in the
228    /// order it made them, its finalizers' last.
229    pub fn elements(&self) -> &[ElementDef] {
230        &self.elements
231    }
232
233    /// Every scoped package, with the element declarations it holds, in
234    /// registration order.
235    pub fn scoped_packages(&self) -> &[ScopedPackageDef] {
236        &self.scoped_packages
237    }
238
239    /// Every fallback, in registration order.
240    pub fn fallbacks(&self) -> &[FallbackDef] {
241        &self.fallbacks
242    }
243
244    /// Every override, in registration order.
245    pub fn overrides(&self) -> &[OverrideDef] {
246        &self.overrides
247    }
248
249    /// The element declarations that the feature called `feature` made
250    /// directly, in the order of [`elements`](Declarations::elements): its
251    /// weak declarations first, then its ordinary ones, each in the order it
252    /// made them. The declarations of its scoped
253    /// packages are not among them: see
254    /// [`scoped_packages_of`](Declarations::scoped_packages_of).
255    pub fn elements_of<'a>(&'a self, feature: &'a str) -> impl Iterator<Item = &'a ElementDef> + 'a {
256        self.elements.iter().filter(move |def| def.owner == feature)
257    }
258
259    /// The scoped packages that the feature called `feature` declared, in the
260    /// order it declared them.
261    pub fn scoped_packages_of<'a>(
262        &'a self,
263        feature: &'a str,
264    ) -> impl Iterator<Item = &'a ScopedPackageDef> + 'a {
265        self.scoped_packages.iter().filter(move |package| package.owner == feature)
266    }
267
268    /// The element declarations, across features, that define the command
269    /// `name` of the callable kind `kind`, in the order of
270    /// [`elements`](Declarations::elements). `name` is
271    /// written without the escape character (`section`, `itemize`); for a
272    /// special character sequence it is the trigger (`~`). A file-inclusion
273    /// macro is a macro.
274    ///
275    /// Several declarations define one command when their parsing modes
276    /// differ ([`ElementDef::modes`]), or when one feature's definition
277    /// replaces another's. In a given parsing mode, the definition in force
278    /// is the last one in this list that is available in that mode (a
279    /// feature declares a command at most once per parsing mode, so this is
280    /// the ordinary definition of the feature whose definitions the language
281    /// stacks last, or the weak one of that feature when no feature defines
282    /// the command ordinarily in that mode). Only the declarations
283    /// that features made directly are searched; a scoped package's command
284    /// is found through [`scoped_package`](Declarations::scoped_package).
285    pub fn named(&self, kind: CallableKind, name: &str) -> Vec<&ElementDef> {
286        self.elements.iter().filter(|def| defines(def, kind, name)).collect()
287    }
288
289    /// The scoped package called `name`, or `None` when no feature declares
290    /// one. A registry holds at most one scoped package of a name.
291    pub fn scoped_package(&self, name: &str) -> Option<&ScopedPackageDef> {
292        self.scoped_packages.iter().find(|package| package.name == *name)
293    }
294
295    /// Every place where an element declaration makes the scoped package
296    /// called `name` available: each environment body and each argument
297    /// whose declaration lists the package ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
298    /// [`ArgDef::scoped`]). The declarations that features made directly come
299    /// first, in the order of [`elements`](Declarations::elements), then
300    /// those held by scoped packages, in registration order.
301    /// A use by a feature that declared the package as a peer is listed
302    /// whether or not some feature declares the package.
303    pub fn scoped_package_uses(&self, name: &str) -> Vec<ScopedPackageUse<'_>> {
304        let mut uses = Vec::new();
305        for (def, within) in self.all_elements() {
306            if let SyntaxDef::Environment { body, .. } = &def.syntax {
307                if body.scoped.iter().any(|package| package == name) {
308                    uses.push(ScopedPackageUse::Body { declaration: def, within });
309                }
310            }
311            let mut arguments = Vec::new();
312            arguments_of(def, within, &mut arguments);
313            uses.extend(
314                arguments
315                    .into_iter()
316                    .filter(|argument| argument.arg.scoped.iter().any(|package| package == name))
317                    .map(ScopedPackageUse::Argument),
318            );
319        }
320        uses
321    }
322
323    /// Every argument of every element declaration, including the arguments
324    /// of the tack-on fields: the declarations that features made directly
325    /// first, in the order of [`elements`](Declarations::elements), then
326    /// those held by scoped packages, in registration order; each
327    /// declaration's arguments come in the order written.
328    pub fn arguments(&self) -> Vec<ArgumentRef<'_>> {
329        let mut out = Vec::new();
330        for (def, within) in self.all_elements() {
331            arguments_of(def, within, &mut out);
332        }
333        out
334    }
335
336    /// Every argument whose [role](ArgDef::role) is `role`, in the order of
337    /// [`arguments`](Declarations::arguments).
338    pub fn role_uses(&self, role: &str) -> Vec<ArgumentRef<'_>> {
339        self.arguments()
340            .into_iter()
341            .filter(|argument| argument.arg.role.as_ref().is_some_and(|name| name == role))
342            .collect()
343    }
344
345    /// Every element declaration with the scoped package that holds it: the
346    /// declarations that features made directly first, then those of each
347    /// scoped package.
348    fn all_elements(&self) -> impl Iterator<Item = (&ElementDef, Option<&ScopedPackageDef>)> {
349        self.elements.iter().map(|def| (def, None)).chain(
350            self.scoped_packages
351                .iter()
352                .flat_map(|package| package.elements.iter().map(move |def| (def, Some(package)))),
353        )
354    }
355}
356
357/// Whether the declaration `def` defines the command `name` of the callable
358/// kind `kind`: one of its names, or its trigger for a special character
359/// sequence.
360fn defines(def: &ElementDef, kind: CallableKind, name: &str) -> bool {
361    if def.syntax.kind() != Some(kind) {
362        return false;
363    }
364    match &def.syntax {
365        SyntaxDef::Specials { trigger, .. } => trigger == name,
366        _ => def.names.iter().any(|written| written == name),
367    }
368}
369
370#[cfg(test)]
371mod tests {
372    use std::sync::Arc;
373
374    use techy::latexlike::Mode;
375
376    use crate::core::registry::{
377        build_registry, BuildError, FeatureBuilder, FeatureInfo, Finalizer, FlmFeature,
378        FlmRegistry, RegistryBuildError, UnresolvedPeer,
379    };
380    use crate::lang::mint::{
381        ArgDef, ArgStdKind, BodyDef, CallableKind, ElementDef, FallbackDef, FallbackKind,
382        ScopedPackageDef, Symbol, SyntaxDef, TackOnField,
383    };
384    use crate::model::element::ElementSpec;
385    use crate::model::names::Name;
386
387    type Register = dyn Fn(&mut FeatureBuilder<'_>) -> Result<(), BuildError> + Send + Sync;
388
389    /// A feature called `name` whose registration is the closure it holds.
390    struct Test {
391        name: &'static str,
392        register: Box<Register>,
393    }
394
395    impl FlmFeature for Test {
396        fn info(&self) -> FeatureInfo {
397            FeatureInfo::new(self.name, self.name)
398        }
399
400        fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
401            (self.register)(b)
402        }
403    }
404
405    fn feature(
406        name: &'static str,
407        register: impl Fn(&mut FeatureBuilder<'_>) -> Result<(), BuildError> + Send + Sync + 'static,
408    ) -> Arc<dyn FlmFeature> {
409        Arc::new(Test { name, register: Box::new(register) })
410    }
411
412    fn built(features: Vec<Arc<dyn FlmFeature>>) -> Arc<FlmRegistry> {
413        build_registry(features).unwrap_or_else(|error| panic!("{}", error.render()))
414    }
415
416    fn refused(features: Vec<Arc<dyn FlmFeature>>) -> RegistryBuildError {
417        match build_registry(features) {
418            Ok(_) => panic!("the registry build was expected to fail"),
419            Err(error) => error,
420        }
421    }
422
423    fn element(name: &str) -> Arc<ElementSpec> {
424        Arc::new(ElementSpec::new(name))
425    }
426
427    /// A macro `\name` of `owner` taking `args`, whose element is `owner.name`.
428    fn macro_with(owner: &str, name: &str, args: Vec<ArgDef>) -> ElementDef {
429        ElementDef::new(owner, [name], SyntaxDef::Macro { args }, element(&format!("{owner}.{name}")))
430    }
431
432    fn arg_names(def: &ElementDef) -> Vec<Option<&str>> {
433        def.syntax.args().iter().map(|arg| arg.name.as_deref()).collect()
434    }
435
436    fn notes(registry: &FlmRegistry) -> Vec<String> {
437        registry.build_diagnostics().iter().map(|diagnostic| diagnostic.identifier().to_string()).collect()
438    }
439
440    // --- the retained declarations ---------------------------------------------------------
441
442    #[test]
443    fn a_registry_retains_every_declaration_in_registration_order() {
444        let registry = built(vec![
445            feature("t", |b| {
446                b.element(macro_with("t", "a", vec![ArgDef::mandatory("x")]).docs("The a."))?;
447                b.element(macro_with("t", "b", Vec::new()))?;
448                b.element(ElementDef::new(
449                    "t",
450                    ["list"],
451                    SyntaxDef::Environment { args: Vec::new(), body: BodyDef::new().scoped("t.items") },
452                    element("t.list"),
453                ))?;
454                b.scoped_package(ScopedPackageDef {
455                    owner: "t".into(),
456                    name: Name::from("t.items"),
457                    elements: vec![macro_with("t", "item", Vec::new())],
458                    docs: String::from("The items."),
459                })?;
460                b.fallback(FallbackDef {
461                    owner: "t".into(),
462                    modes: vec![Mode::Math],
463                    kind: FallbackKind::Macro,
464                    element: element("t.any"),
465                })
466            }),
467            feature("u", |b| {
468                b.element(macro_with("u", "a", Vec::new()).modes([Mode::Math]))?;
469                b.override_callable(CallableKind::Macro, "b")
470            }),
471        ]);
472        let declarations = registry.declarations();
473        let written: Vec<(&str, &str)> =
474            declarations.elements().iter().map(|def| (def.owner.as_str(), def.names[0].as_str())).collect();
475        assert_eq!(written, [("t", "a"), ("t", "b"), ("t", "list"), ("u", "a")]);
476        assert_eq!(declarations.scoped_packages().len(), 1);
477        assert_eq!(declarations.fallbacks().len(), 1);
478        assert_eq!(declarations.overrides().len(), 1);
479        assert_eq!(declarations.elements_of("t").count(), 3);
480        assert_eq!(declarations.elements_of("u").count(), 1);
481        assert_eq!(declarations.scoped_packages_of("t").count(), 1);
482
483        let a = declarations.named(CallableKind::Macro, "a");
484        let owners: Vec<&str> = a.iter().map(|def| def.owner.as_str()).collect();
485        assert_eq!(owners, ["t", "u"]);
486        #[cfg(feature = "docs")]
487        assert_eq!(a[0].docs, "The a.");
488        assert_eq!(arg_names(a[0]), [Some("x")]);
489        assert!(declarations.named(CallableKind::Environment, "a").is_empty());
490        assert!(declarations.named(CallableKind::Macro, "item").is_empty());
491
492        let items = declarations.scoped_package("t.items").expect("declared");
493        assert_eq!(items.elements[0].names[0], "item");
494        let uses = declarations.scoped_package_uses("t.items");
495        assert_eq!(uses.len(), 1);
496        assert!(matches!(uses[0], super::ScopedPackageUse::Body { within: None, .. }));
497        assert_eq!(uses[0].declaration().names[0], "list");
498    }
499
500    /// A finalizer that declares the macro `\x` for its feature.
501    struct LateX;
502
503    impl Finalizer for LateX {
504        fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
505            b.element(macro_with("a", "x", Vec::new()))
506        }
507    }
508
509    #[test]
510    fn a_finalizer_s_declarations_join_its_feature_s_and_the_last_one_named_is_in_force() {
511        // `a` declares `\x` from its finalizer, after `b` declared `\x` (with an
512        // override) in the first round; the language stacks `b`'s definitions
513        // above all of `a`'s, so `b`'s `\x` is in force.
514        let registry = built(vec![
515            feature("a", |b| {
516                b.element(macro_with("a", "y", Vec::new()))?;
517                b.finalizer(Arc::new(LateX))
518            }),
519            feature("b", |b| {
520                b.element(macro_with("b", "x", Vec::new()))?;
521                b.override_callable(CallableKind::Macro, "x")
522            }),
523        ]);
524        let declarations = registry.declarations();
525        let written: Vec<(&str, &str)> =
526            declarations.elements().iter().map(|def| (def.owner.as_str(), def.names[0].as_str())).collect();
527        assert_eq!(written, [("a", "y"), ("a", "x"), ("b", "x")]);
528        let x = declarations.named(CallableKind::Macro, "x");
529        let owners: Vec<&str> = x.iter().map(|def| def.owner.as_str()).collect();
530        assert_eq!(owners, ["a", "b"]);
531        let symbol = Symbol { kind: CallableKind::Macro, name: String::from("x") };
532        let in_force = registry.lang().symbols().get(&symbol).expect("`\\x` is defined");
533        assert_eq!(x.last().map(|def| &def.owner), Some(in_force));
534    }
535
536    #[test]
537    fn in_a_mode_the_last_declaration_named_is_in_force_whatever_the_weakness() {
538        // `b`, registered after `a`, declares `\x` weakly in both modes; `a`
539        // declares it ordinarily in math mode. In text mode `b`'s is in force,
540        // in math mode `a`'s.
541        let registry = built(vec![
542            feature("a", |b| b.element(macro_with("a", "x", Vec::new()).modes([Mode::Math]))),
543            feature("b", |b| {
544                b.element(macro_with("b", "x", Vec::new()).modes([Mode::Text, Mode::Math]).weak())
545            }),
546        ]);
547        let declarations = registry.declarations();
548        let x = declarations.named(CallableKind::Macro, "x");
549        let in_force = |mode: Mode| {
550            x.iter().rev().find(|def| def.modes.contains(&mode)).map(|def| def.owner.as_str())
551        };
552        assert_eq!(in_force(Mode::Text), Some("b"));
553        assert_eq!(in_force(Mode::Math), Some("a"));
554    }
555
556    #[test]
557    fn the_mark_enters_the_digest() {
558        let with = |weak: bool| {
559            built(vec![feature("a", move |b| {
560                let def = macro_with("a", "x", Vec::new());
561                b.element(if weak { def.weak() } else { def })
562            })])
563            .digest()
564        };
565        assert_eq!(with(true), with(true));
566        assert_ne!(with(true), with(false));
567    }
568
569    #[test]
570    fn a_resolved_peer_element_value_is_kept_and_an_unresolved_one_is_not() {
571        let registry = built(vec![
572            feature("t", |b| b.element(macro_with("t", "own", Vec::new()))),
573            feature("u", |b| {
574                b.peer_element_value(ElementDef::new("u", ["also"], SyntaxDef::Macro { args: Vec::new() }, element("t.own")))?;
575                b.peer_element_value(ElementDef::new("u", ["none"], SyntaxDef::Macro { args: Vec::new() }, element("v.none")))
576            }),
577        ]);
578        let names: Vec<&str> =
579            registry.declarations().elements().iter().map(|def| def.names[0].as_str()).collect();
580        assert_eq!(names, ["own", "also"]);
581    }
582
583    // --- argument roles ---------------------------------------------------------------------
584
585    #[test]
586    fn a_declared_role_is_listed_and_found_on_its_arguments() {
587        let registry = built(vec![feature("t", |b| {
588            b.argument_role("t.key", "A key.")?;
589            b.element(macro_with("t", "k", vec![ArgDef::mandatory("key").role("t.key")]))
590        })]);
591        let role = registry.argument_role_named("t.key").expect("declared");
592        assert_eq!(role.owner, "t");
593        #[cfg(feature = "docs")]
594        assert_eq!(role.docs, "A key.");
595        assert_eq!(registry.argument_roles().len(), 1);
596        let uses = registry.declarations().role_uses("t.key");
597        assert_eq!(uses.len(), 1);
598        assert_eq!(uses[0].arg.name.as_deref(), Some("key"));
599        assert_eq!(uses[0].declaration.names[0], "k");
600        assert!(registry.argument_role_named("t.other").is_none());
601    }
602
603    #[test]
604    fn a_role_no_feature_declares_is_an_error_naming_the_feature_command_argument_and_role() {
605        let error = refused(vec![feature("t", |b| {
606            b.argument_role("t.key", "A key.")?;
607            let field = TackOnField::new("tag", vec![ArgDef::mandatory("name").role("t.tag")]);
608            b.element(macro_with(
609                "t",
610                "k",
611                vec![ArgDef::new(ArgStdKind::Mandatory).role("t.kye"), ArgDef::new(ArgStdKind::TackOn { fields: vec![field] })],
612            ))
613        })]);
614        let roles: Vec<(&str, Option<&str>, Option<&str>)> = error
615            .errors
616            .iter()
617            .filter_map(|error| match error {
618                BuildError::UndeclaredArgumentRole { role, place, .. } => {
619                    Some((role.as_str(), place.argument.as_deref(), place.field.as_deref()))
620                }
621                _ => None,
622            })
623            .collect();
624        assert_eq!(roles, [("t.kye", None, None), ("t.tag", Some("name"), Some("tag"))]);
625        match &error.errors[0] {
626            BuildError::UndeclaredArgumentRole { feature, place, role, roster } => {
627                assert_eq!((feature.as_str(), place.command.as_str(), role.as_str()), ("t", "\\k", "t.kye"));
628                assert_eq!(roster, &[Name::from("t.key")]);
629                assert_eq!((place.argument.as_deref(), place.index, place.field.as_deref()), (None, 0, None));
630            }
631            other => panic!("unexpected error: {other:?}"),
632        }
633    }
634
635    #[test]
636    fn another_feature_s_role_needs_no_peer_declaration_when_that_feature_is_present() {
637        let registry = built(vec![
638            feature("t", |b| b.argument_role("t.key", "A key.")),
639            feature("u", |b| b.element(macro_with("u", "k", vec![ArgDef::mandatory("key").role("t.key")]))),
640        ]);
641        assert_eq!(registry.declarations().role_uses("t.key").len(), 1);
642        assert!(registry.peer_argument_roles().is_empty());
643    }
644
645    #[test]
646    fn a_peer_declared_role_resolves_and_an_unresolved_one_is_a_note() {
647        let user = || {
648            feature("u", |b| {
649                b.peer_argument_role("t.key")?;
650                b.peer_argument_role("t.key")?;
651                b.element(macro_with("u", "k", vec![ArgDef::mandatory("key").role("t.key")]))
652            })
653        };
654        let resolved = built(vec![feature("t", |b| b.argument_role("t.key", "A key.")), user()]);
655        assert_eq!(resolved.peer_argument_roles().len(), 1);
656        assert!(resolved.peer_argument_roles()[0].resolved);
657        assert!(notes(&resolved).is_empty(), "{:?}", notes(&resolved));
658
659        let alone = built(vec![user()]);
660        assert_eq!(alone.peer_argument_roles().len(), 1);
661        assert!(!alone.peer_argument_roles()[0].resolved);
662        assert_eq!(notes(&alone), ["flm.registry.unresolved-peer"]);
663        let note = alone.build_diagnostics().iter().next().expect("one note");
664        let data = note.data().downcast_ref::<UnresolvedPeer>().expect("an unresolved peer");
665        assert_eq!(data.kind, "argument role");
666        assert_eq!((data.feature.as_str(), data.name.as_str()), ("u", "t.key"));
667        assert_eq!(alone.declarations().role_uses("t.key").len(), 1);
668    }
669
670    #[test]
671    fn two_declarations_of_one_role_are_an_error_naming_both_features() {
672        let error = refused(vec![
673            feature("t", |b| b.argument_role("x.key", "A key.")),
674            feature("u", |b| b.argument_role("x.key", "Another key.")),
675        ]);
676        assert!(
677            matches!(
678                &error.errors[..],
679                [BuildError::Duplicate { kind: "argument role", name, first, second }]
680                    if name.as_str() == "x.key" && first.as_str() == "t" && second.as_str() == "u"
681            ),
682            "{error:?}"
683        );
684    }
685
686    #[test]
687    fn a_role_is_not_an_input_of_the_digest() {
688        let with = |role: bool| {
689            built(vec![feature("t", move |b| {
690                b.argument_role("t.key", "A key.")?;
691                let mut arg = ArgDef::mandatory("key");
692                if role {
693                    arg = arg.role("t.key");
694                }
695                b.element(macro_with("t", "k", vec![arg]))
696            })])
697            .digest()
698        };
699        assert_eq!(with(false), with(true));
700        let without_declaration =
701            built(vec![feature("t", |b| b.element(macro_with("t", "k", vec![ArgDef::mandatory("key")])))]).digest();
702        assert_eq!(with(false), without_declaration);
703    }
704}