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;
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 grouped by feature, in the order in which
38/// the language stacks the features' definitions (see
39/// [`elements`](Declarations::elements)), so that the last declaration of a
40/// command is the one in 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 element declarations grouped by feature in the
192    /// 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. The sort is stable, so each feature's declarations
203        // keep the order it made them in.
204        let order = feature_stack_order(&elements);
205        elements.sort_by_key(|def| order.iter().position(|owner| *owner == def.owner));
206        Declarations { elements, scoped_packages, fallbacks, overrides }
207    }
208
209    /// Every element declaration a feature made directly
210    /// ([`FeatureBuilder::element`](super::FeatureBuilder::element)),
211    /// grouped by feature. The declarations held by scoped packages are not
212    /// among them: see [`scoped_packages`](Declarations::scoped_packages).
213    ///
214    /// The features come in the order in which the language stacks their
215    /// definitions, a later feature's definition of a command replacing an
216    /// earlier one's: the order of each feature's first element declaration,
217    /// which is the final order of the features
218    /// ([`FlmRegistry::features`](super::FlmRegistry::features)) among those
219    /// that declare elements when they register. A feature whose only
220    /// element declarations come from a [`Finalizer`](super::Finalizer)
221    /// comes after them. Each feature's declarations are in the order it made
222    /// them, its finalizers' last.
223    pub fn elements(&self) -> &[ElementDef] {
224        &self.elements
225    }
226
227    /// Every scoped package, with the element declarations it holds, in
228    /// registration order.
229    pub fn scoped_packages(&self) -> &[ScopedPackageDef] {
230        &self.scoped_packages
231    }
232
233    /// Every fallback, in registration order.
234    pub fn fallbacks(&self) -> &[FallbackDef] {
235        &self.fallbacks
236    }
237
238    /// Every override, in registration order.
239    pub fn overrides(&self) -> &[OverrideDef] {
240        &self.overrides
241    }
242
243    /// The element declarations that the feature called `feature` made
244    /// directly, in the order it made them. The declarations of its scoped
245    /// packages are not among them: see
246    /// [`scoped_packages_of`](Declarations::scoped_packages_of).
247    pub fn elements_of<'a>(&'a self, feature: &'a str) -> impl Iterator<Item = &'a ElementDef> + 'a {
248        self.elements.iter().filter(move |def| def.owner == feature)
249    }
250
251    /// The scoped packages that the feature called `feature` declared, in the
252    /// order it declared them.
253    pub fn scoped_packages_of<'a>(
254        &'a self,
255        feature: &'a str,
256    ) -> impl Iterator<Item = &'a ScopedPackageDef> + 'a {
257        self.scoped_packages.iter().filter(move |package| package.owner == feature)
258    }
259
260    /// The element declarations, across features, that define the command
261    /// `name` of the callable kind `kind`, in the order of
262    /// [`elements`](Declarations::elements). `name` is
263    /// written without the escape character (`section`, `itemize`); for a
264    /// special character sequence it is the trigger (`~`). A file-inclusion
265    /// macro is a macro.
266    ///
267    /// Several declarations define one command when their parsing modes
268    /// differ ([`ElementDef::modes`]), or when one feature's definition
269    /// replaces another's. In a given parsing mode, the definition in force
270    /// is the last one in this list that is available in that mode (a
271    /// feature declares a command at most once per parsing mode, so this is
272    /// the definition of the feature whose definitions the language stacks
273    /// last). Only the declarations
274    /// that features made directly are searched; a scoped package's command
275    /// is found through [`scoped_package`](Declarations::scoped_package).
276    pub fn named(&self, kind: CallableKind, name: &str) -> Vec<&ElementDef> {
277        self.elements.iter().filter(|def| defines(def, kind, name)).collect()
278    }
279
280    /// The scoped package called `name`, or `None` when no feature declares
281    /// one. A registry holds at most one scoped package of a name.
282    pub fn scoped_package(&self, name: &str) -> Option<&ScopedPackageDef> {
283        self.scoped_packages.iter().find(|package| package.name == *name)
284    }
285
286    /// Every place where an element declaration makes the scoped package
287    /// called `name` available: each environment body and each argument
288    /// whose declaration lists the package ([`BodyDef::scoped`](crate::lang::mint::BodyDef::scoped),
289    /// [`ArgDef::scoped`]). The declarations that features made directly come
290    /// first, in the order of [`elements`](Declarations::elements), then
291    /// those held by scoped packages, in registration order.
292    /// A use by a feature that declared the package as a peer is listed
293    /// whether or not some feature declares the package.
294    pub fn scoped_package_uses(&self, name: &str) -> Vec<ScopedPackageUse<'_>> {
295        let mut uses = Vec::new();
296        for (def, within) in self.all_elements() {
297            if let SyntaxDef::Environment { body, .. } = &def.syntax {
298                if body.scoped.iter().any(|package| package == name) {
299                    uses.push(ScopedPackageUse::Body { declaration: def, within });
300                }
301            }
302            let mut arguments = Vec::new();
303            arguments_of(def, within, &mut arguments);
304            uses.extend(
305                arguments
306                    .into_iter()
307                    .filter(|argument| argument.arg.scoped.iter().any(|package| package == name))
308                    .map(ScopedPackageUse::Argument),
309            );
310        }
311        uses
312    }
313
314    /// Every argument of every element declaration, including the arguments
315    /// of the tack-on fields: the declarations that features made directly
316    /// first, in the order of [`elements`](Declarations::elements), then
317    /// those held by scoped packages, in registration order; each
318    /// declaration's arguments come in the order written.
319    pub fn arguments(&self) -> Vec<ArgumentRef<'_>> {
320        let mut out = Vec::new();
321        for (def, within) in self.all_elements() {
322            arguments_of(def, within, &mut out);
323        }
324        out
325    }
326
327    /// Every argument whose [role](ArgDef::role) is `role`, in the order of
328    /// [`arguments`](Declarations::arguments).
329    pub fn role_uses(&self, role: &str) -> Vec<ArgumentRef<'_>> {
330        self.arguments()
331            .into_iter()
332            .filter(|argument| argument.arg.role.as_ref().is_some_and(|name| name == role))
333            .collect()
334    }
335
336    /// Every element declaration with the scoped package that holds it: the
337    /// declarations that features made directly first, then those of each
338    /// scoped package.
339    fn all_elements(&self) -> impl Iterator<Item = (&ElementDef, Option<&ScopedPackageDef>)> {
340        self.elements.iter().map(|def| (def, None)).chain(
341            self.scoped_packages
342                .iter()
343                .flat_map(|package| package.elements.iter().map(move |def| (def, Some(package)))),
344        )
345    }
346}
347
348/// Whether the declaration `def` defines the command `name` of the callable
349/// kind `kind`: one of its names, or its trigger for a special character
350/// sequence.
351fn defines(def: &ElementDef, kind: CallableKind, name: &str) -> bool {
352    if def.syntax.kind() != Some(kind) {
353        return false;
354    }
355    match &def.syntax {
356        SyntaxDef::Specials { trigger, .. } => trigger == name,
357        _ => def.names.iter().any(|written| written == name),
358    }
359}
360
361#[cfg(test)]
362mod tests {
363    use std::sync::Arc;
364
365    use techy::latexlike::Mode;
366
367    use crate::core::registry::{
368        build_registry, BuildError, FeatureBuilder, FeatureInfo, Finalizer, FlmFeature,
369        FlmRegistry, RegistryBuildError, UnresolvedPeer,
370    };
371    use crate::lang::mint::{
372        ArgDef, ArgStdKind, BodyDef, CallableKind, ElementDef, FallbackDef, FallbackKind,
373        ScopedPackageDef, Symbol, SyntaxDef, TackOnField,
374    };
375    use crate::model::element::ElementSpec;
376    use crate::model::names::Name;
377
378    type Register = dyn Fn(&mut FeatureBuilder<'_>) -> Result<(), BuildError> + Send + Sync;
379
380    /// A feature called `name` whose registration is the closure it holds.
381    struct Test {
382        name: &'static str,
383        register: Box<Register>,
384    }
385
386    impl FlmFeature for Test {
387        fn info(&self) -> FeatureInfo {
388            FeatureInfo::new(self.name, self.name)
389        }
390
391        fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
392            (self.register)(b)
393        }
394    }
395
396    fn feature(
397        name: &'static str,
398        register: impl Fn(&mut FeatureBuilder<'_>) -> Result<(), BuildError> + Send + Sync + 'static,
399    ) -> Arc<dyn FlmFeature> {
400        Arc::new(Test { name, register: Box::new(register) })
401    }
402
403    fn built(features: Vec<Arc<dyn FlmFeature>>) -> Arc<FlmRegistry> {
404        build_registry(features).unwrap_or_else(|error| panic!("{}", error.render()))
405    }
406
407    fn refused(features: Vec<Arc<dyn FlmFeature>>) -> RegistryBuildError {
408        match build_registry(features) {
409            Ok(_) => panic!("the registry build was expected to fail"),
410            Err(error) => error,
411        }
412    }
413
414    fn element(name: &str) -> Arc<ElementSpec> {
415        Arc::new(ElementSpec::new(name))
416    }
417
418    /// A macro `\name` of `owner` taking `args`, whose element is `owner.name`.
419    fn macro_with(owner: &str, name: &str, args: Vec<ArgDef>) -> ElementDef {
420        ElementDef::new(owner, [name], SyntaxDef::Macro { args }, element(&format!("{owner}.{name}")))
421    }
422
423    fn arg_names(def: &ElementDef) -> Vec<Option<&str>> {
424        def.syntax.args().iter().map(|arg| arg.name.as_deref()).collect()
425    }
426
427    fn notes(registry: &FlmRegistry) -> Vec<String> {
428        registry.build_diagnostics().iter().map(|diagnostic| diagnostic.identifier().to_string()).collect()
429    }
430
431    // --- the retained declarations ---------------------------------------------------------
432
433    #[test]
434    fn a_registry_retains_every_declaration_in_registration_order() {
435        let registry = built(vec![
436            feature("t", |b| {
437                b.element(macro_with("t", "a", vec![ArgDef::mandatory("x")]).docs("The a."))?;
438                b.element(macro_with("t", "b", Vec::new()))?;
439                b.element(ElementDef::new(
440                    "t",
441                    ["list"],
442                    SyntaxDef::Environment { args: Vec::new(), body: BodyDef::new().scoped("t.items") },
443                    element("t.list"),
444                ))?;
445                b.scoped_package(ScopedPackageDef {
446                    owner: "t".into(),
447                    name: Name::from("t.items"),
448                    elements: vec![macro_with("t", "item", Vec::new())],
449                    docs: String::from("The items."),
450                })?;
451                b.fallback(FallbackDef {
452                    owner: "t".into(),
453                    modes: vec![Mode::Math],
454                    kind: FallbackKind::Macro,
455                    element: element("t.any"),
456                })
457            }),
458            feature("u", |b| {
459                b.element(macro_with("u", "a", Vec::new()).modes([Mode::Math]))?;
460                b.override_callable(CallableKind::Macro, "b")
461            }),
462        ]);
463        let declarations = registry.declarations();
464        let written: Vec<(&str, &str)> =
465            declarations.elements().iter().map(|def| (def.owner.as_str(), def.names[0].as_str())).collect();
466        assert_eq!(written, [("t", "a"), ("t", "b"), ("t", "list"), ("u", "a")]);
467        assert_eq!(declarations.scoped_packages().len(), 1);
468        assert_eq!(declarations.fallbacks().len(), 1);
469        assert_eq!(declarations.overrides().len(), 1);
470        assert_eq!(declarations.elements_of("t").count(), 3);
471        assert_eq!(declarations.elements_of("u").count(), 1);
472        assert_eq!(declarations.scoped_packages_of("t").count(), 1);
473
474        let a = declarations.named(CallableKind::Macro, "a");
475        let owners: Vec<&str> = a.iter().map(|def| def.owner.as_str()).collect();
476        assert_eq!(owners, ["t", "u"]);
477        #[cfg(feature = "docs")]
478        assert_eq!(a[0].docs, "The a.");
479        assert_eq!(arg_names(a[0]), [Some("x")]);
480        assert!(declarations.named(CallableKind::Environment, "a").is_empty());
481        assert!(declarations.named(CallableKind::Macro, "item").is_empty());
482
483        let items = declarations.scoped_package("t.items").expect("declared");
484        assert_eq!(items.elements[0].names[0], "item");
485        let uses = declarations.scoped_package_uses("t.items");
486        assert_eq!(uses.len(), 1);
487        assert!(matches!(uses[0], super::ScopedPackageUse::Body { within: None, .. }));
488        assert_eq!(uses[0].declaration().names[0], "list");
489    }
490
491    /// A finalizer that declares the macro `\x` for its feature.
492    struct LateX;
493
494    impl Finalizer for LateX {
495        fn finalize(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
496            b.element(macro_with("a", "x", Vec::new()))
497        }
498    }
499
500    #[test]
501    fn a_finalizer_s_declarations_join_its_feature_s_and_the_last_one_named_is_in_force() {
502        // `a` declares `\x` from its finalizer, after `b` declared `\x` (with an
503        // override) in the first round; the language stacks `b`'s definitions
504        // above all of `a`'s, so `b`'s `\x` is in force.
505        let registry = built(vec![
506            feature("a", |b| {
507                b.element(macro_with("a", "y", Vec::new()))?;
508                b.finalizer(Arc::new(LateX))
509            }),
510            feature("b", |b| {
511                b.element(macro_with("b", "x", Vec::new()))?;
512                b.override_callable(CallableKind::Macro, "x")
513            }),
514        ]);
515        let declarations = registry.declarations();
516        let written: Vec<(&str, &str)> =
517            declarations.elements().iter().map(|def| (def.owner.as_str(), def.names[0].as_str())).collect();
518        assert_eq!(written, [("a", "y"), ("a", "x"), ("b", "x")]);
519        let x = declarations.named(CallableKind::Macro, "x");
520        let owners: Vec<&str> = x.iter().map(|def| def.owner.as_str()).collect();
521        assert_eq!(owners, ["a", "b"]);
522        let symbol = Symbol { kind: CallableKind::Macro, name: String::from("x") };
523        let in_force = registry.lang().symbols().get(&symbol).expect("`\\x` is defined");
524        assert_eq!(x.last().map(|def| &def.owner), Some(in_force));
525    }
526
527    #[test]
528    fn a_resolved_peer_element_value_is_kept_and_an_unresolved_one_is_not() {
529        let registry = built(vec![
530            feature("t", |b| b.element(macro_with("t", "own", Vec::new()))),
531            feature("u", |b| {
532                b.peer_element_value(ElementDef::new("u", ["also"], SyntaxDef::Macro { args: Vec::new() }, element("t.own")))?;
533                b.peer_element_value(ElementDef::new("u", ["none"], SyntaxDef::Macro { args: Vec::new() }, element("v.none")))
534            }),
535        ]);
536        let names: Vec<&str> =
537            registry.declarations().elements().iter().map(|def| def.names[0].as_str()).collect();
538        assert_eq!(names, ["own", "also"]);
539    }
540
541    // --- argument roles ---------------------------------------------------------------------
542
543    #[test]
544    fn a_declared_role_is_listed_and_found_on_its_arguments() {
545        let registry = built(vec![feature("t", |b| {
546            b.argument_role("t.key", "A key.")?;
547            b.element(macro_with("t", "k", vec![ArgDef::mandatory("key").role("t.key")]))
548        })]);
549        let role = registry.argument_role_named("t.key").expect("declared");
550        assert_eq!(role.owner, "t");
551        #[cfg(feature = "docs")]
552        assert_eq!(role.docs, "A key.");
553        assert_eq!(registry.argument_roles().len(), 1);
554        let uses = registry.declarations().role_uses("t.key");
555        assert_eq!(uses.len(), 1);
556        assert_eq!(uses[0].arg.name.as_deref(), Some("key"));
557        assert_eq!(uses[0].declaration.names[0], "k");
558        assert!(registry.argument_role_named("t.other").is_none());
559    }
560
561    #[test]
562    fn a_role_no_feature_declares_is_an_error_naming_the_feature_command_argument_and_role() {
563        let error = refused(vec![feature("t", |b| {
564            b.argument_role("t.key", "A key.")?;
565            let field = TackOnField::new("tag", vec![ArgDef::mandatory("name").role("t.tag")]);
566            b.element(macro_with(
567                "t",
568                "k",
569                vec![ArgDef::new(ArgStdKind::Mandatory).role("t.kye"), ArgDef::new(ArgStdKind::TackOn { fields: vec![field] })],
570            ))
571        })]);
572        let roles: Vec<(&str, Option<&str>, Option<&str>)> = error
573            .errors
574            .iter()
575            .filter_map(|error| match error {
576                BuildError::UndeclaredArgumentRole { role, place, .. } => {
577                    Some((role.as_str(), place.argument.as_deref(), place.field.as_deref()))
578                }
579                _ => None,
580            })
581            .collect();
582        assert_eq!(roles, [("t.kye", None, None), ("t.tag", Some("name"), Some("tag"))]);
583        match &error.errors[0] {
584            BuildError::UndeclaredArgumentRole { feature, place, role, roster } => {
585                assert_eq!((feature.as_str(), place.command.as_str(), role.as_str()), ("t", "\\k", "t.kye"));
586                assert_eq!(roster, &[Name::from("t.key")]);
587                assert_eq!((place.argument.as_deref(), place.index, place.field.as_deref()), (None, 0, None));
588            }
589            other => panic!("unexpected error: {other:?}"),
590        }
591    }
592
593    #[test]
594    fn another_feature_s_role_needs_no_peer_declaration_when_that_feature_is_present() {
595        let registry = built(vec![
596            feature("t", |b| b.argument_role("t.key", "A key.")),
597            feature("u", |b| b.element(macro_with("u", "k", vec![ArgDef::mandatory("key").role("t.key")]))),
598        ]);
599        assert_eq!(registry.declarations().role_uses("t.key").len(), 1);
600        assert!(registry.peer_argument_roles().is_empty());
601    }
602
603    #[test]
604    fn a_peer_declared_role_resolves_and_an_unresolved_one_is_a_note() {
605        let user = || {
606            feature("u", |b| {
607                b.peer_argument_role("t.key")?;
608                b.peer_argument_role("t.key")?;
609                b.element(macro_with("u", "k", vec![ArgDef::mandatory("key").role("t.key")]))
610            })
611        };
612        let resolved = built(vec![feature("t", |b| b.argument_role("t.key", "A key.")), user()]);
613        assert_eq!(resolved.peer_argument_roles().len(), 1);
614        assert!(resolved.peer_argument_roles()[0].resolved);
615        assert!(notes(&resolved).is_empty(), "{:?}", notes(&resolved));
616
617        let alone = built(vec![user()]);
618        assert_eq!(alone.peer_argument_roles().len(), 1);
619        assert!(!alone.peer_argument_roles()[0].resolved);
620        assert_eq!(notes(&alone), ["flm.registry.unresolved-peer"]);
621        let note = alone.build_diagnostics().iter().next().expect("one note");
622        let data = note.data().downcast_ref::<UnresolvedPeer>().expect("an unresolved peer");
623        assert_eq!(data.kind, "argument role");
624        assert_eq!((data.feature.as_str(), data.name.as_str()), ("u", "t.key"));
625        assert_eq!(alone.declarations().role_uses("t.key").len(), 1);
626    }
627
628    #[test]
629    fn two_declarations_of_one_role_are_an_error_naming_both_features() {
630        let error = refused(vec![
631            feature("t", |b| b.argument_role("x.key", "A key.")),
632            feature("u", |b| b.argument_role("x.key", "Another key.")),
633        ]);
634        assert!(
635            matches!(
636                &error.errors[..],
637                [BuildError::Duplicate { kind: "argument role", name, first, second }]
638                    if name.as_str() == "x.key" && first.as_str() == "t" && second.as_str() == "u"
639            ),
640            "{error:?}"
641        );
642    }
643
644    #[test]
645    fn a_role_is_not_an_input_of_the_digest() {
646        let with = |role: bool| {
647            built(vec![feature("t", move |b| {
648                b.argument_role("t.key", "A key.")?;
649                let mut arg = ArgDef::mandatory("key");
650                if role {
651                    arg = arg.role("t.key");
652                }
653                b.element(macro_with("t", "k", vec![arg]))
654            })])
655            .digest()
656        };
657        assert_eq!(with(false), with(true));
658        let without_declaration =
659            built(vec![feature("t", |b| b.element(macro_with("t", "k", vec![ArgDef::mandatory("key")])))]).digest();
660        assert_eq!(with(false), without_declaration);
661    }
662}