Skip to main content

whisker_runtime/
element_registry.rs

1//! Bootstrap-time normalization of built-in and module-provided elements.
2
3use std::collections::HashMap;
4use std::error::Error;
5use std::fmt;
6
7use crate::ElementTag;
8use whisker_engine::whisker_protocol::{
9    ElementRegistration, ElementRegistrationError, ElementSchema, ElementTypeId,
10};
11use whisker_engine::whisker_style::SpecifiedStyle;
12
13type SchemaKey = String;
14
15/// Constructor for one custom element contract linked into an application.
16#[cfg(not(target_arch = "wasm32"))]
17pub type LinkedElementProvider = fn() -> ElementProviderMetadata;
18
19/// Custom element contracts contributed anywhere in the linked Rust graph.
20///
21/// The linker collects constructors only; schemas are built, sorted, validated,
22/// and assigned compact IDs synchronously before a native Host bootstraps.
23#[cfg(not(target_arch = "wasm32"))]
24#[linkme::distributed_slice]
25#[doc(hidden)]
26pub static LINKED_ELEMENT_PROVIDERS: [LinkedElementProvider];
27
28/// Authoring syntax generated for one element provider.
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum ElementAuthoringBinding {
31    /// A standard `render!` tag implemented through the provider path.
32    Builtin(ElementTag),
33    /// A generated module component resolved by its schema name.
34    Named,
35}
36
37/// Generated bootstrap metadata for one UI-providing module definition.
38///
39/// Service-only modules do not emit this value and continue through the
40/// existing function, event, and observer registration path. This is an owned
41/// description rather than a public factory trait so build-generated metadata
42/// can be normalized before a target Host binds its implementation.
43#[derive(Clone, Debug, PartialEq, Eq)]
44pub struct ElementProviderMetadata {
45    /// Host-independent element contract.
46    pub schema: ElementSchema,
47    /// Authoring syntax that resolves to this contract.
48    pub authoring: ElementAuthoringBinding,
49    /// Host-independent declarations applied before the caller's style.
50    pub base_style: SpecifiedStyle,
51}
52
53/// Generated Rust-side definition for one element-provider module.
54///
55/// A module owns its element schemas and authoring bindings as one bootstrap
56/// unit. Host packages bind target-specific factories to the resulting
57/// element names before the first frame.
58#[derive(Clone, Debug, PartialEq, Eq)]
59pub struct ElementModuleDefinition {
60    /// Stable package/module identity used in bootstrap diagnostics.
61    pub module_name: String,
62    /// Visual elements exported by this module.
63    pub elements: Vec<ElementProviderMetadata>,
64}
65
66impl ElementModuleDefinition {
67    /// Creates an element-provider module definition.
68    pub fn new(
69        module_name: impl Into<String>,
70        elements: impl IntoIterator<Item = ElementProviderMetadata>,
71    ) -> Self {
72        Self {
73            module_name: module_name.into(),
74            elements: elements.into_iter().collect(),
75        }
76    }
77}
78
79impl ElementProviderMetadata {
80    /// Describes one standard element implemented through the provider path.
81    pub fn builtin(tag: ElementTag, schema: ElementSchema) -> Self {
82        Self {
83            schema,
84            authoring: ElementAuthoringBinding::Builtin(tag),
85            base_style: SpecifiedStyle::new(),
86        }
87    }
88
89    /// Describes one generated module element.
90    ///
91    /// Its Rust authoring name, schema name, and Host binding key are the same
92    /// package-qualified [`ElementSchema::name`].
93    pub fn named(schema: ElementSchema) -> Self {
94        Self {
95            schema,
96            authoring: ElementAuthoringBinding::Named,
97            base_style: SpecifiedStyle::new(),
98        }
99    }
100
101    /// Applies provider-owned defaults while preserving caller declarations as
102    /// the later, overriding style fragment.
103    pub fn with_base_style(mut self, style: SpecifiedStyle) -> Self {
104        self.base_style = style;
105        self
106    }
107}
108
109/// Immutable element contracts and authoring bindings for one registry epoch.
110///
111/// Compact IDs are assigned when an [`ElementRegistryBuilder`] is built. They
112/// are therefore independent of [`ElementTag`] discriminants and are never
113/// supplied by a module schema.
114#[derive(Clone, Debug)]
115pub struct ElementRegistry {
116    registrations: Vec<ElementRegistration>,
117    base_styles: Vec<SpecifiedStyle>,
118    builtins: HashMap<ElementTag, usize>,
119    names: HashMap<String, usize>,
120}
121
122impl ElementRegistry {
123    /// Starts an empty registry definition.
124    pub fn builder() -> ElementRegistryBuilder {
125        ElementRegistryBuilder::default()
126    }
127
128    /// Starts a registry definition containing the standard Whisker elements.
129    ///
130    /// Callers can append module schemas and authoring-name bindings before
131    /// building the immutable surface registry.
132    pub fn standard_builder() -> ElementRegistryBuilder {
133        Self::builder().register_module(crate::standard_ui::standard_ui_module_definition())
134    }
135
136    /// Returns the standard Whisker element registry.
137    pub fn standard() -> Self {
138        Self::standard_builder()
139            .build()
140            .expect("standard element schemas are valid and uniquely bound")
141    }
142
143    /// Builds the native application registry from every linked module schema.
144    ///
145    /// Sorting by package-qualified schema name makes compact IDs independent
146    /// of linker section order. The returned registry is the complete epoch a
147    /// native Host negotiates before application authoring begins.
148    #[cfg(not(target_arch = "wasm32"))]
149    pub fn standard_with_linked_providers() -> Result<Self, ElementRegistryError> {
150        let mut providers = LINKED_ELEMENT_PROVIDERS
151            .iter()
152            .map(|provider| provider())
153            .collect::<Vec<_>>();
154        providers.sort_unstable_by(|left, right| left.schema.name.cmp(&right.schema.name));
155        Self::standard_builder()
156            .register_providers(providers)
157            .build()
158    }
159
160    /// Returns the normalized contracts in compact-ID order.
161    pub fn registrations(&self) -> &[ElementRegistration] {
162        &self.registrations
163    }
164
165    pub(crate) fn base_style(&self, registration: &ElementRegistration) -> &SpecifiedStyle {
166        let index = registration.element_type.get() as usize - 1;
167        self.base_styles
168            .get(index)
169            .expect("registrations and base styles share one compact-ID order")
170    }
171
172    /// Resolves one built-in authoring tag to its normalized contract.
173    pub fn registration_for_builtin(&self, tag: ElementTag) -> Option<&ElementRegistration> {
174        self.builtins
175            .get(&tag)
176            .and_then(|index| self.registrations.get(*index))
177    }
178
179    /// Resolves one generated or compatibility authoring name.
180    pub fn registration_for_name(&self, name: &str) -> Option<&ElementRegistration> {
181        self.names
182            .get(name)
183            .and_then(|index| self.registrations.get(*index))
184    }
185}
186
187/// Mutable bootstrap description used to construct an [`ElementRegistry`].
188#[derive(Clone, Debug, Default)]
189pub struct ElementRegistryBuilder {
190    schemas: Vec<(ElementSchema, SpecifiedStyle)>,
191    builtin_bindings: Vec<(ElementTag, SchemaKey)>,
192    name_bindings: Vec<(String, SchemaKey)>,
193}
194
195impl ElementRegistryBuilder {
196    /// Adds every generated element exported by one module definition.
197    pub fn register_module(self, definition: ElementModuleDefinition) -> Self {
198        self.register_providers(definition.elements)
199    }
200
201    /// Adds a sequence of generated element-provider modules.
202    pub fn register_modules(
203        mut self,
204        definitions: impl IntoIterator<Item = ElementModuleDefinition>,
205    ) -> Self {
206        for definition in definitions {
207            self = self.register_module(definition);
208        }
209        self
210    }
211
212    /// Adds generated metadata for one UI-providing module.
213    pub fn register_provider(mut self, provider: ElementProviderMetadata) -> Self {
214        let name = provider.schema.name.clone();
215        self.schemas.push((provider.schema, provider.base_style));
216        match provider.authoring {
217            ElementAuthoringBinding::Builtin(tag) => {
218                self.builtin_bindings.push((tag, name));
219            }
220            ElementAuthoringBinding::Named => {
221                self.name_bindings.push((name.clone(), name));
222            }
223        }
224        self
225    }
226
227    /// Adds every UI provider emitted by generated application metadata.
228    pub fn register_providers(
229        mut self,
230        providers: impl IntoIterator<Item = ElementProviderMetadata>,
231    ) -> Self {
232        for provider in providers {
233            self = self.register_provider(provider);
234        }
235        self
236    }
237
238    /// Adds a Host-independent schema to the registry epoch.
239    ///
240    /// Prefer [`Self::register_provider`] for generated module metadata. This
241    /// lower-level method supports schemas whose authoring binding is supplied
242    /// separately or which are retained only for Host negotiation.
243    pub fn register(mut self, schema: ElementSchema) -> Self {
244        self.schemas.push((schema, SpecifiedStyle::new()));
245        self
246    }
247
248    /// Maps a built-in authoring tag to a schema name.
249    pub fn bind_builtin(mut self, tag: ElementTag, name: impl Into<String>) -> Self {
250        self.builtin_bindings.push((tag, name.into()));
251        self
252    }
253
254    /// Maps a generated or compatibility authoring name to a schema key.
255    pub fn bind_name(
256        mut self,
257        authoring_name: impl Into<String>,
258        element_name: impl Into<String>,
259    ) -> Self {
260        self.name_bindings
261            .push((authoring_name.into(), element_name.into()));
262        self
263    }
264
265    /// Validates schemas and bindings, then assigns compact IDs for the epoch.
266    pub fn build(self) -> Result<ElementRegistry, ElementRegistryError> {
267        let mut registrations = Vec::with_capacity(self.schemas.len());
268        let mut base_styles = Vec::with_capacity(self.schemas.len());
269        let mut schemas = HashMap::with_capacity(self.schemas.len());
270        for (index, (schema, base_style)) in self.schemas.into_iter().enumerate() {
271            schema
272                .validate()
273                .map_err(|error| ElementRegistryError::InvalidSchema {
274                    name: schema.name.clone(),
275                    error,
276                })?;
277            let key = schema.name.clone();
278            if schemas.contains_key(&key) {
279                return Err(ElementRegistryError::DuplicateName { name: key });
280            }
281            let raw_id = u32::try_from(index)
282                .ok()
283                .and_then(|value| value.checked_add(1))
284                .and_then(ElementTypeId::new)
285                .ok_or(ElementRegistryError::ElementTypeIdExhausted)?;
286            schemas.insert(key, registrations.len());
287            registrations.push(schema.bind(raw_id));
288            base_styles.push(base_style);
289        }
290
291        let mut builtins = HashMap::with_capacity(self.builtin_bindings.len());
292        for (tag, key) in self.builtin_bindings {
293            if tag == ElementTag::RawText {
294                return Err(ElementRegistryError::VirtualBuiltinBinding { tag });
295            }
296            let index = schemas
297                .get(&key)
298                .copied()
299                .ok_or_else(|| ElementRegistryError::UnknownSchemaBinding { name: key.clone() })?;
300            if builtins.insert(tag, index).is_some() {
301                return Err(ElementRegistryError::DuplicateBuiltinBinding { tag });
302            }
303        }
304
305        let mut names = HashMap::with_capacity(self.name_bindings.len());
306        for (name, key) in self.name_bindings {
307            if name.trim().is_empty() {
308                return Err(ElementRegistryError::EmptyAuthoringName);
309            }
310            let index = schemas
311                .get(&key)
312                .copied()
313                .ok_or_else(|| ElementRegistryError::UnknownSchemaBinding { name: key.clone() })?;
314            if names.insert(name.clone(), index).is_some() {
315                return Err(ElementRegistryError::DuplicateAuthoringName { name });
316            }
317        }
318
319        Ok(ElementRegistry {
320            registrations,
321            base_styles,
322            builtins,
323            names,
324        })
325    }
326}
327
328/// Bootstrap failure while normalizing an element registry.
329#[derive(Clone, Debug, PartialEq, Eq)]
330pub enum ElementRegistryError {
331    /// A schema violated a Host-independent contract invariant.
332    InvalidSchema {
333        /// Element name retained for diagnostics.
334        name: String,
335        /// Rejected contract combination.
336        error: ElementRegistrationError,
337    },
338    /// Two schemas declared the same name.
339    DuplicateName {
340        /// Conflicting package-qualified name.
341        name: String,
342    },
343    /// A declaration reused a name with a different contract.
344    ConflictingSchema {
345        /// Stable name whose contract changed within one registry epoch.
346        name: String,
347    },
348    /// A binding referred to a schema absent from this registry definition.
349    UnknownSchemaBinding {
350        /// Missing package-qualified name.
351        name: String,
352    },
353    /// A built-in tag was bound more than once.
354    DuplicateBuiltinBinding {
355        /// Conflicting authoring tag.
356        tag: ElementTag,
357    },
358    /// Virtual raw text cannot have a Host element schema.
359    VirtualBuiltinBinding {
360        /// Rejected virtual tag.
361        tag: ElementTag,
362    },
363    /// A generated or compatibility authoring name was empty.
364    EmptyAuthoringName,
365    /// A generated or compatibility authoring name was bound more than once.
366    DuplicateAuthoringName {
367        /// Conflicting authoring name.
368        name: String,
369    },
370    /// The registry cannot allocate another non-zero compact element ID.
371    ElementTypeIdExhausted,
372}
373
374impl fmt::Display for ElementRegistryError {
375    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
376        write!(formatter, "Whisker element registry error: {self:?}")
377    }
378}
379
380impl Error for ElementRegistryError {}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385    use whisker_engine::whisker_protocol::{ChildPolicy, ElementMeasurement};
386
387    fn custom_schema(name: &str) -> ElementSchema {
388        ElementSchema {
389            name: name.into(),
390            child_policy: ChildPolicy::Elements,
391            measurement: ElementMeasurement::None,
392            text_style: false,
393            properties: Vec::new(),
394            events: Vec::new(),
395            commands: Vec::new(),
396        }
397    }
398
399    #[test]
400    fn standard_and_module_schemas_share_one_id_allocator() {
401        let registry = ElementRegistry::standard_builder()
402            .register_module(ElementModuleDefinition::new(
403                "example.maps",
404                [ElementProviderMetadata::named(custom_schema(
405                    "example.maps/Map",
406                ))],
407            ))
408            .build()
409            .unwrap();
410
411        assert_eq!(registry.registrations().len(), 4);
412        assert_eq!(
413            registry
414                .registration_for_name("example.maps/Map")
415                .unwrap()
416                .element_type,
417            ElementTypeId::new(4).unwrap()
418        );
419        assert!(
420            registry
421                .registration_for_builtin(ElementTag::Page)
422                .is_none()
423        );
424        assert_ne!(
425            registry
426                .registration_for_builtin(ElementTag::ScrollView)
427                .unwrap()
428                .element_type
429                .get(),
430            ElementTag::ScrollView as u32
431        );
432    }
433
434    #[test]
435    fn duplicate_names_fail_before_a_surface_starts() {
436        let result = ElementRegistry::builder()
437            .register(custom_schema("example/Map"))
438            .register(custom_schema("example/Map"))
439            .build();
440
441        assert!(matches!(
442            result,
443            Err(ElementRegistryError::DuplicateName { .. })
444        ));
445    }
446
447    #[test]
448    fn authoring_bindings_must_resolve_uniquely() {
449        let result = ElementRegistry::builder()
450            .register(custom_schema("example/Map"))
451            .bind_name("map", "example/Map")
452            .bind_name("map", "example/Map")
453            .build();
454        assert_eq!(
455            result.unwrap_err(),
456            ElementRegistryError::DuplicateAuthoringName { name: "map".into() }
457        );
458    }
459}