flm_core/core/registry/frozen.rs
1//! The finished registry, [`FlmRegistry`]; the entry types its accessors
2//! return; and the dense numeric identifiers that address its entries.
3//!
4//! Once the registry build has checked every declaration, it **numbers** the
5//! declarations: each element value, capability, table, stage and lowering
6//! rule gets a number, and the build creates lookup structures over those
7//! numbers. The result is an [`FlmRegistry`], which never changes again and
8//! is shared as an `Arc<FlmRegistry>` by every document, plan and run.
9//!
10//! # Dense identifiers
11//!
12//! [`CapId`], [`StageIdx`], [`RuleIdx`], [`ElemIdx`] and [`TableId`] are
13//! positions in the lists
14//! of one registry. With them, the frequent questions ("does this element
15//! carry that aspect", "which stage provides this capability") are answered
16//! by a numeric lookup instead of a comparison of names. A number means
17//! nothing without the registry that assigned it: used with a different
18//! registry, it reads the wrong entry, or the accessor panics. Look a name up
19//! once, keep the identifier, and use it only with that registry.
20//!
21//! [`ElemBitset`] applies the same idea to a set of elements: one bit per
22//! element index. [`FlmRegistry::aspect_bitset`] returns the set of every
23//! element that carries a given aspect in this form.
24//!
25//! # Numbering order
26//!
27//! Numbers follow declaration order throughout, so two builds from the same
28//! features in the same order produce the same numbers:
29//!
30//! - elements: the language's structural elements first, in their fixed
31//! order; then the elements of the element declarations, in declaration
32//! order; then the
33//! elements of the fallbacks, then those of the scoped packages, then the
34//! presentation elements, each group in declaration order (a value that
35//! several declarations share is numbered once);
36//! - capabilities: the capabilities declared on their own, then one for each
37//! table;
38//! - tables, stages and lowering rules: each in declaration order.
39//!
40//! The stage numbering also breaks ties when a plan has nothing else to
41//! decide between two stages.
42//!
43//! # Element identity
44//!
45//! The registry keeps an element value's number in a separate table, keyed by
46//! the address of the shared value, and not on the value itself. A value can
47//! therefore outlive the registry that numbered it (as a node in a tree does)
48//! without carrying a number that is wrong for the next registry.
49//!
50//! See also [`super::build`] for how a registry is built and
51//! [`super::builder`] for the declarations it is built from.
52
53use std::any::{Any, TypeId};
54use std::collections::{BTreeMap, BTreeSet};
55use std::fmt;
56use std::sync::Arc;
57
58use crate::model::element::{AmbiguousElement, ElemIdx, ElementSpec};
59use crate::core::lowering::LoweringRule;
60use crate::model::names::{
61 BackendName, CapName, ElementName, FeatureName, Name, OutputName, RuleName, StageName,
62 WorkflowName,
63};
64use crate::model::options::{OptionDecl, OptionKey, TypeKey};
65use crate::core::registry::builder::{BuildError, Roster, Site, StageKind};
66use crate::core::registry::declarations::Declarations;
67use crate::core::registry::entities::{
68 NativeImplication, OrderingDef, OutputDef, PeerName, ScriptDef, StyleDef, WorkflowDef,
69};
70use crate::core::registry::feature::FeatureInfo;
71use crate::core::services::{PeerContribution, Services};
72use crate::core::stage::{RewriteDecl, StageDecl};
73use crate::core::data::table::{TableDef, TableId, TableType};
74use crate::lang::{BuiltLang, FlmDiagnostics};
75use crate::lang::structural::{self, StructuralElements};
76
77/// The number of a capability in one registry, in declaration order.
78///
79/// Get one with [`FlmRegistry::cap_id`], and read the capability's entry with
80/// [`FlmRegistry::capability`]. The number is meaningful only together with
81/// the registry that assigned it.
82///
83/// It is written to data with `Serialize`; see [serialized
84/// forms](crate::core::registry#serialized-forms).
85#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
86#[derive(serde::Serialize, schemars::JsonSchema)]
87pub struct CapId(pub u32);
88
89/// The number of a stage in one registry, in registration order, counting
90/// stages of both forms (rewrite stages and ordinary stages).
91///
92/// The same order breaks ties when a plan has nothing else to decide between
93/// two stages. Get one with [`FlmRegistry::stage_idx`], and read the stage's
94/// entry with [`FlmRegistry::stage`]. The number is meaningful only together
95/// with the registry that assigned it.
96///
97/// It is written to data with `Serialize`; see [serialized
98/// forms](crate::core::registry#serialized-forms).
99#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
100#[derive(serde::Serialize, schemars::JsonSchema)]
101pub struct StageIdx(pub u32);
102
103/// The number of a lowering rule in one registry, in registration order.
104///
105/// Get one with [`FlmRegistry::rule_idx`] or [`FlmRegistry::rules_for`], and
106/// read the rule's entry with [`FlmRegistry::rule`]. The number is meaningful
107/// only together with the registry that assigned it.
108#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
109pub struct RuleIdx(pub u32);
110
111/// A set of element indices, stored as one bit per index.
112///
113/// [`FlmRegistry::aspect_bitset`] returns the set of every element that
114/// carries a given aspect in this form, without comparing names: a stage that
115/// must visit every referenceable element asks once, then tests each node's
116/// element by its index.
117///
118/// # Examples
119///
120/// ```
121/// use flm_core::model::element::ElemIdx;
122/// use flm_core::core::registry::ElemBitset;
123///
124/// let mut set = ElemBitset::new();
125/// set.insert(ElemIdx(3));
126/// set.insert(ElemIdx(70));
127/// assert!(set.contains(ElemIdx(3)));
128/// assert!(!set.contains(ElemIdx(4)));
129/// assert_eq!(set.iter().collect::<Vec<_>>(), [ElemIdx(3), ElemIdx(70)]);
130/// ```
131#[derive(Debug, Clone, Default, PartialEq, Eq)]
132pub struct ElemBitset {
133 bits: Vec<u64>,
134}
135
136impl ElemBitset {
137 /// A set holding no index.
138 pub fn new() -> ElemBitset {
139 ElemBitset::default()
140 }
141
142 /// Adds `idx` to the set; adding an index the set already holds changes
143 /// nothing.
144 ///
145 /// The storage grows to cover the index, so adding a very large index to
146 /// an otherwise small set allocates memory in proportion to that index.
147 pub fn insert(&mut self, idx: ElemIdx) {
148 let (word, bit) = (idx.0 as usize / 64, idx.0 % 64);
149 if self.bits.len() <= word {
150 self.bits.resize(word + 1, 0);
151 }
152 self.bits[word] |= 1 << bit;
153 }
154
155 /// Whether the set holds `idx`.
156 pub fn contains(&self, idx: ElemIdx) -> bool {
157 let (word, bit) = (idx.0 as usize / 64, idx.0 % 64);
158 self.bits.get(word).map(|w| w & (1 << bit) != 0).unwrap_or(false)
159 }
160
161 /// The indices the set holds, in ascending order.
162 pub fn iter(&self) -> impl Iterator<Item = ElemIdx> + '_ {
163 self.bits.iter().enumerate().flat_map(|(word, bits)| {
164 (0..64u32)
165 .filter(move |bit| bits & (1 << bit) != 0)
166 .map(move |bit| ElemIdx(word as u32 * 64 + bit))
167 })
168 }
169
170 /// The number of indices the set holds. Each call counts them, in a time
171 /// proportional to the largest index ever added.
172 pub fn len(&self) -> usize {
173 self.bits.iter().map(|w| w.count_ones() as usize).sum()
174 }
175
176 /// Whether the set holds no index.
177 pub fn is_empty(&self) -> bool {
178 self.len() == 0
179 }
180}
181
182/// The origin of a registered element value.
183#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub enum ElementKind {
185 /// One of the language's structural elements, the elements of the node
186 /// forms that no feature declares (text, groups, paragraphs and the
187 /// others; see [`StructuralElements`]), which exist in every registry.
188 Structural,
189 /// An element that can appear in a parsed document: an element declared
190 /// with a syntax, an element a declaration creates without syntax, the
191 /// element of a field, or the element of a fallback.
192 Source,
193 /// A presentation element, registered with
194 /// [`FeatureBuilder::presentation_element`](super::FeatureBuilder::presentation_element).
195 /// It appears only in the trees a backend writes, never in a parsed
196 /// document.
197 Presentation,
198}
199
200/// One element value as the registry holds it.
201#[derive(Debug, Clone)]
202pub struct ElementEntry {
203 /// The element value itself, shared with every node carrying it.
204 pub element: Arc<ElementSpec>,
205 /// The feature that declared it; of several features that declare one
206 /// value, the one placed last in the feature order. For a structural
207 /// element that no feature declares, the owner is the language's own
208 /// name, `flm`.
209 pub owner: FeatureName,
210 /// This value's number in this registry.
211 pub idx: ElemIdx,
212 /// The origin of the value.
213 pub kind: ElementKind,
214}
215
216/// One capability as the registry holds it, whether it was declared on its
217/// own or together with a table.
218///
219/// Every table's name is also a capability, the capability of the table having
220/// been written; the registry holds both kinds in one list, and
221/// [`table`](CapabilityEntry::table) tells them apart.
222#[derive(Debug, Clone)]
223pub struct CapabilityEntry {
224 /// The capability's name.
225 pub name: CapName,
226 /// Documentation prose from the declaration.
227 pub docs: String,
228 /// The feature that declared it.
229 pub owner: FeatureName,
230 /// This capability's number in this registry.
231 pub id: CapId,
232 /// The capability this one refines (is a stronger form of), if any.
233 pub refines: Option<CapId>,
234 /// Whether this is the default refinement of its parent: the refinement
235 /// that a demand for the parent alone selects when nothing else decides.
236 pub default: bool,
237 /// The table whose capability this is, or `None` for a capability declared
238 /// on its own.
239 pub table: Option<TableId>,
240 /// Whether that table is external: no stage writes it, and only the value
241 /// the caller installs when a run is constructed satisfies this
242 /// capability.
243 pub external: bool,
244 /// What a plan error says when a plan needs this capability and no
245 /// registered stage provides it, from the declaration
246 /// ([`CapabilityDef::unprovided`](super::CapabilityDef::unprovided)); `None`
247 /// for a table's capability.
248 pub unprovided: Option<String>,
249 ancestors: Vec<CapId>,
250 children: Vec<CapId>,
251}
252
253impl CapabilityEntry {
254 /// This capability, followed by the chain of capabilities it refines, the
255 /// nearest first.
256 ///
257 /// Providing this capability provides every capability in the chain;
258 /// a stage's [`provides`](StageEntry::provides) therefore includes the whole
259 /// chain of each capability it provides.
260 pub fn ancestors(&self) -> &[CapId] {
261 &self.ancestors
262 }
263
264 /// The capabilities that refine this one directly, in identifier order;
265 /// their own refinements are not included.
266 pub fn refinements(&self) -> &[CapId] {
267 &self.children
268 }
269}
270
271/// One collection as the registry holds it: a name for a set of capabilities,
272/// with the members that features added to it.
273#[derive(Debug, Clone)]
274pub struct CollectionEntry {
275 /// The collection's name.
276 pub name: CapName,
277 /// Documentation prose from the declaration.
278 pub docs: String,
279 /// The feature that declared the collection. Any feature may add members.
280 pub owner: FeatureName,
281 /// The capabilities added as members, in identifier order. The build
282 /// dropped the members added to a collection that no feature declares.
283 pub members: BTreeSet<CapId>,
284}
285
286/// One table as the registry holds it.
287#[derive(Debug, Clone)]
288pub struct TableEntry {
289 /// The declaration: the table's name, its value type, its documentation
290 /// and the feature that declared it.
291 pub def: TableDef,
292 /// This table's number in this registry.
293 pub id: TableId,
294 /// The capability that comes with the table: the capability of the table
295 /// having been written.
296 pub cap: CapId,
297 /// Whether the table is external: no stage writes it, and its values are
298 /// installed when a run is constructed.
299 pub external: bool,
300}
301
302/// One stage as the registry holds it, of either form, with its declaration
303/// resolved against the rest of the registry.
304pub struct StageEntry {
305 /// The stage's name, unique across the registry.
306 pub name: StageName,
307 /// The stage itself, in its form (rewrite stage or ordinary stage).
308 pub kind: StageKind,
309 /// The declaration read from the stage when it was registered. For a
310 /// rewrite stage, the builder made it from the rewrite's own declaration,
311 /// so that both forms are scheduled the same way.
312 pub decl: StageDecl,
313 /// A rewrite stage's own declaration; `None` for an ordinary stage.
314 pub rewrite: Option<RewriteDecl>,
315 /// The feature that registered it.
316 pub owner: FeatureName,
317 /// This stage's number in this registry.
318 pub idx: StageIdx,
319 /// Every capability that running this stage brings about: those it
320 /// declares, the capabilities of the tables it writes, and every
321 /// capability those refine. Because the refined capabilities are
322 /// included, a plan matches a demand by set membership alone.
323 pub provides: BTreeSet<CapId>,
324 /// The tables the stage writes, in the order declared.
325 pub writes: Vec<TableId>,
326}
327
328impl StageEntry {
329 /// Whether this is a rewrite stage, which changes the trees before they are
330 /// frozen, and not an ordinary stage.
331 pub fn is_rewrite(&self) -> bool {
332 matches!(self.kind, StageKind::Rewrite(_))
333 }
334}
335
336impl fmt::Debug for StageEntry {
337 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
338 f.debug_struct("StageEntry")
339 .field("name", &self.name)
340 .field("rewrite", &self.is_rewrite())
341 .field("provides", &self.provides)
342 .finish()
343 }
344}
345
346/// One lowering rule as the registry holds it.
347#[derive(Debug, Clone)]
348pub struct RuleEntry {
349 /// The rule: the element it lowers, what it produces, and what it needs.
350 pub rule: LoweringRule,
351 /// The feature that registered it.
352 pub owner: FeatureName,
353 /// This rule's number in this registry.
354 pub idx: RuleIdx,
355 /// Why the rule is **set aside**, or empty for a rule that takes part. A
356 /// lowering rule is set aside when a peer declaration it depends on
357 /// resolves to nothing; this list holds those [peer
358 /// declarations](PeerName) of the rule's own feature (a backend in its
359 /// default mark, an element in its `produces`, a table in its `reads`)
360 /// that no feature of this registry declares.
361 ///
362 /// A rule that is set aside is never a candidate when a plan chooses
363 /// rules, and the check that a backend can write every element ignores
364 /// it, exactly as if it had not been registered. It stays listed so that
365 /// a reader can find it and see why. Each unresolved name is also reported
366 /// once as a Note among the [build
367 /// diagnostics](FlmRegistry::build_diagnostics). A rule that refers to an
368 /// unresolved peer table only in `reads_opt` is not set aside: it runs and
369 /// finds the table absent.
370 pub set_aside: Vec<PeerName>,
371}
372
373impl RuleEntry {
374 /// Whether the rule is set aside, that is, whether
375 /// [`set_aside`](RuleEntry::set_aside) is not empty.
376 pub fn is_set_aside(&self) -> bool {
377 !self.set_aside.is_empty()
378 }
379}
380
381/// One [peer declaration](PeerName) of a backend as the registry holds it.
382#[derive(Debug, Clone)]
383pub struct PeerBackendEntry {
384 /// The backend's name.
385 pub name: BackendName,
386 /// The feature that made the declaration.
387 pub owner: FeatureName,
388 /// Documentation prose from the declaration.
389 pub docs: String,
390 /// Whether some feature of this registry registers the backend. When
391 /// `false`, the owner's rules that list the backend in their default mark
392 /// are set aside.
393 pub resolved: bool,
394}
395
396/// One [peer declaration](PeerName) of a presentation element as the registry
397/// holds it.
398#[derive(Debug, Clone)]
399pub struct PeerElementEntry {
400 /// The element's name.
401 pub name: ElementName,
402 /// The payload type given as the declaration's signature. When the
403 /// declaration is resolved, the registered presentation element has this
404 /// payload type: the build refuses any other.
405 pub payload: TypeKey,
406 /// The feature that made the declaration.
407 pub owner: FeatureName,
408 /// Documentation prose from the declaration.
409 pub docs: String,
410 /// Whether some feature of this registry registers a presentation element
411 /// of this name. When `false`, the owner's rules producing the element are
412 /// set aside.
413 pub resolved: bool,
414}
415
416/// One [peer declaration](PeerName) of an element value as the registry holds
417/// it ([`FeatureBuilder::peer_element_value`](super::FeatureBuilder::peer_element_value)).
418#[derive(Debug, Clone)]
419pub struct PeerElementValueEntry {
420 /// The element type's name.
421 pub element: ElementName,
422 /// The callable names (commands) the declaration defines.
423 pub names: Vec<Name>,
424 /// The feature that made the declaration.
425 pub owner: FeatureName,
426 /// Whether some feature of this registry declares the element type. When
427 /// `false`, the build dropped the declaration and its commands are not
428 /// defined; when `true`, the declared value is one of the registry's
429 /// elements like any other.
430 pub resolved: bool,
431}
432
433/// One [peer declaration](PeerName) of a scoped package as the registry holds
434/// it.
435#[derive(Debug, Clone)]
436pub struct PeerScopedPackageEntry {
437 /// The package's name.
438 pub name: Name,
439 /// The feature that made the declaration.
440 pub owner: FeatureName,
441 /// Documentation prose from the declaration.
442 pub docs: String,
443 /// Whether some feature of this registry declares a scoped package of this
444 /// name. When `false`, the owner's environment bodies and arguments that
445 /// refer to the package get no definitions from it.
446 pub resolved: bool,
447}
448
449/// One [peer declaration](PeerName) of a table as the registry holds it.
450#[derive(Debug, Clone)]
451pub struct PeerTableEntry {
452 /// The table's name.
453 pub name: CapName,
454 /// The value type given as the declaration's signature. When the
455 /// declaration is resolved, the declared table holds this type: the build
456 /// refuses any other.
457 pub value: TableType,
458 /// The feature that made the declaration.
459 pub owner: FeatureName,
460 /// Documentation prose from the declaration.
461 pub docs: String,
462 /// Whether some feature of this registry declares a table of this name.
463 /// When `false`, the owner's rules that read the table as a hard
464 /// dependency are set aside, its rules that read it optionally run and
465 /// find the table absent, and its stages that write it are not
466 /// registered.
467 pub resolved: bool,
468}
469
470/// One argument role as the registry holds it: a registered name for what an
471/// argument holds, declared with
472/// [`FeatureBuilder::argument_role`](super::FeatureBuilder::argument_role)
473/// and set on arguments with [`ArgDef::role`](crate::lang::mint::ArgDef::role).
474///
475/// [`FlmRegistry::argument_roles`] lists every role;
476/// [`Declarations::role_uses`](super::Declarations::role_uses) lists the
477/// arguments that have one.
478#[derive(Debug, Clone, PartialEq, Eq)]
479pub struct ArgumentRoleEntry {
480 /// The role's dotted name, unique among the registry's argument roles.
481 pub name: Name,
482 /// Documentation prose from the declaration: what an argument of this
483 /// role holds.
484 pub docs: String,
485 /// The feature that declared the role.
486 pub owner: FeatureName,
487}
488
489/// The documentation text of an element type, with the feature that gave it.
490///
491/// An element type is the name its element values share; each value carries
492/// a text of its own ([`ElementSpec::docs`]), and the type may have one more
493/// text, which says what the nodes of the type mean, whatever their value.
494/// The text comes from one of three places:
495///
496/// - a feature that declares the type, through
497/// [`FeatureBuilder::element_type_text`](super::FeatureBuilder::element_type_text);
498/// - the language, for each of its [structural
499/// elements](crate::lang::structural), with
500/// [`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER) as its owner;
501/// - the declaration of a [presentation
502/// element](super::FeatureBuilder::presentation_element), whose text is
503/// also the text of its type, since a presentation element is the only
504/// value of its type.
505///
506/// A registry holds at most one text per element type
507/// ([`FlmRegistry::element_type_text`]); a type of which no declaration gives
508/// a text has none.
509#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct ElementTypeText {
511 /// The element type's name.
512 pub element: ElementName,
513 /// The documentation text: what the nodes of this type mean.
514 pub docs: String,
515 /// The feature that gave the text, or
516 /// [`LANGUAGE_OWNER`](crate::lang::mint::LANGUAGE_OWNER) for a structural
517 /// element type.
518 pub owner: FeatureName,
519}
520
521/// One [peer declaration](PeerName) of an argument role as the registry holds
522/// it ([`FeatureBuilder::peer_argument_role`](super::FeatureBuilder::peer_argument_role)).
523#[derive(Debug, Clone, PartialEq, Eq)]
524pub struct PeerArgumentRoleEntry {
525 /// The role's name.
526 pub name: Name,
527 /// The feature that made the declaration.
528 pub owner: FeatureName,
529 /// Whether some feature of this registry declares the role. When
530 /// `false`, the owner's arguments that have the role keep it, and the
531 /// registry holds no description of it.
532 pub resolved: bool,
533}
534
535/// One presentation element as the registry holds it.
536#[derive(Debug, Clone)]
537pub struct PresentationEntry {
538 /// The element value created for it, shared with every node that carries
539 /// it.
540 pub element: Arc<ElementSpec>,
541 /// The type of the payload its nodes carry.
542 pub payload: TypeKey,
543 /// Documentation prose from the declaration.
544 pub docs: String,
545 /// The feature that registered it.
546 pub owner: FeatureName,
547}
548
549/// One backend as the registry holds it, with its three stages given by their
550/// numbers.
551#[derive(Debug, Clone)]
552pub struct BackendEntry {
553 /// The backend's name, which is also the last segment of the names of its
554 /// tables.
555 pub name: BackendName,
556 /// The native set: the elements this backend's emit stage writes directly.
557 /// Lowering rules must turn every other element into these.
558 pub native: BTreeSet<ElementName>,
559 /// The lowering stage, which builds the presentation trees from the frozen
560 /// trees.
561 pub lowering: StageIdx,
562 /// The emit stage, which turns the presentation trees into bytes.
563 pub emit: StageIdx,
564 /// The final stage, which assembles the artifact set the caller
565 /// receives.
566 pub final_stage: StageIdx,
567 /// The feature that registered it.
568 pub owner: FeatureName,
569 /// Documentation prose from the declaration.
570 pub docs: String,
571}
572
573/// One output as the registry holds it, with its table and its capability
574/// given by their numbers. The module root re-exports this type as
575/// [`RegisteredOutput`](super::RegisteredOutput); the unrelated
576/// [`entities::OutputEntry`](super::entities::OutputEntry) describes an
577/// output's entry artifact.
578#[derive(Debug, Clone)]
579pub struct OutputEntry {
580 /// The declaration: the output's name, its entry artifact's media type and
581 /// file extension, and its documentation.
582 pub def: OutputDef,
583 /// The feature that registered it.
584 pub owner: FeatureName,
585 /// The table that holds this output's artifacts, as an artifact set.
586 pub table: TableId,
587 /// The capability a plan must reach for this output to exist.
588 pub capability: CapId,
589}
590
591/// One workflow as the registry holds it, as declared, without the fields it
592/// inherits; [`FlmRegistry::combined_workflow`] returns the workflow with
593/// them.
594#[derive(Debug, Clone)]
595pub struct WorkflowEntry {
596 /// The declaration: the outputs, demands, preferences and option values it
597 /// holds, and the workflow it extends. After the build, the declaration
598 /// includes the fields registered for this workflow by name.
599 pub def: WorkflowDef,
600 /// The feature that registered it.
601 pub owner: FeatureName,
602}
603
604// Elements are numbered in a fixed order, the language's structural elements
605// first, then the features' contributions in feature order, so that two builds
606// of one roster agree on every index. The index is held in a table of the
607// registry, not on the element value: an element value is often a shared
608// constant, and building a second registry over it must not fail.
609/// A registry: the frozen record of everything the language and the pipeline
610/// consult for a set of features, built once and shared by every document,
611/// plan and run.
612///
613/// [`RegistryBuilder::build`](super::RegistryBuilder::build) and
614/// [`build_registry`](super::build_registry) produce it. It never changes
615/// afterwards and is shared across threads as an `Arc<FlmRegistry>`.
616///
617/// # Reading a registry
618///
619/// Most entities can be looked up in two ways. An accessor that takes a name
620/// returns an `Option`, because any name may be asked for. An accessor that
621/// takes a capability, table, stage or rule number this registry assigned
622/// returns the entry directly, because such a number is valid by
623/// construction; it panics when the number is beyond this registry's lists,
624/// which can happen only when another registry assigned it. The element
625/// accessors are the exception: [`element`](FlmRegistry::element) returns
626/// `None` and [`has_aspect`](FlmRegistry::has_aspect) returns `false` for an
627/// index beyond this registry's elements. A number that another registry
628/// assigned and that falls within this registry's lists reads the wrong
629/// entry. The accessors, by group:
630///
631/// - **Features and the language.** [`features`](FlmRegistry::features),
632/// [`feature`](FlmRegistry::feature), [`has_feature`](FlmRegistry::has_feature),
633/// [`lang`](FlmRegistry::lang), [`structural`](FlmRegistry::structural),
634/// [`build_diagnostics`](FlmRegistry::build_diagnostics).
635/// - **The declarations of what an author may write.**
636/// [`declarations`](FlmRegistry::declarations) (the element declarations,
637/// scoped packages, fallbacks and overrides, as declared),
638/// [`argument_roles`](FlmRegistry::argument_roles),
639/// [`argument_role_named`](FlmRegistry::argument_role_named).
640/// - **Elements and aspects.** [`elements`](FlmRegistry::elements),
641/// [`element`](FlmRegistry::element), [`elem_idx`](FlmRegistry::elem_idx),
642/// [`elements_named`](FlmRegistry::elements_named),
643/// [`element_named`](FlmRegistry::element_named),
644/// [`element_value`](FlmRegistry::element_value),
645/// [`aspect_bitset`](FlmRegistry::aspect_bitset),
646/// [`has_aspect`](FlmRegistry::has_aspect),
647/// [`aspect_names`](FlmRegistry::aspect_names),
648/// [`occurrable_elements`](FlmRegistry::occurrable_elements),
649/// [`element_type_texts`](FlmRegistry::element_type_texts),
650/// [`element_type_text`](FlmRegistry::element_type_text).
651/// - **Capabilities, collections and tables.**
652/// [`capabilities`](FlmRegistry::capabilities), [`cap_id`](FlmRegistry::cap_id),
653/// [`capability`](FlmRegistry::capability),
654/// [`capability_named`](FlmRegistry::capability_named),
655/// [`default_refinement`](FlmRegistry::default_refinement),
656/// [`collections`](FlmRegistry::collections),
657/// [`collection`](FlmRegistry::collection), [`tables`](FlmRegistry::tables),
658/// [`table_id`](FlmRegistry::table_id), [`table`](FlmRegistry::table),
659/// [`table_named`](FlmRegistry::table_named),
660/// [`external_tables`](FlmRegistry::external_tables),
661/// [`table_has_writer`](FlmRegistry::table_has_writer).
662/// - **Stages and orderings.** [`stages`](FlmRegistry::stages),
663/// [`stage_idx`](FlmRegistry::stage_idx), [`stage`](FlmRegistry::stage),
664/// [`stage_named`](FlmRegistry::stage_named),
665/// [`orderings`](FlmRegistry::orderings).
666/// - **Lowering and presentation.** [`rules`](FlmRegistry::rules),
667/// [`rule_idx`](FlmRegistry::rule_idx), [`rule`](FlmRegistry::rule),
668/// [`rules_for`](FlmRegistry::rules_for),
669/// [`set_aside_rules`](FlmRegistry::set_aside_rules),
670/// [`presentation_elements`](FlmRegistry::presentation_elements),
671/// [`presentation_element`](FlmRegistry::presentation_element),
672/// [`peer_backends`](FlmRegistry::peer_backends),
673/// [`peer_elements`](FlmRegistry::peer_elements),
674/// [`peer_tables`](FlmRegistry::peer_tables),
675/// [`peer_slots`](FlmRegistry::peer_slots),
676/// [`peer_scoped_packages`](FlmRegistry::peer_scoped_packages),
677/// [`peer_element_values`](FlmRegistry::peer_element_values),
678/// [`peer_argument_roles`](FlmRegistry::peer_argument_roles).
679/// - **Backends, outputs and workflows.** [`backends`](FlmRegistry::backends),
680/// [`backend`](FlmRegistry::backend), [`outputs`](FlmRegistry::outputs),
681/// [`output`](FlmRegistry::output), [`workflows`](FlmRegistry::workflows),
682/// [`workflow`](FlmRegistry::workflow).
683/// - **Workflows with what they inherit.**
684/// [`workflow_chain`](FlmRegistry::workflow_chain),
685/// [`combined_workflow`](FlmRegistry::combined_workflow).
686/// - **Options, services, style and script definitions, and the digest.**
687/// [`options`](FlmRegistry::options),
688/// [`option_decl`](FlmRegistry::option_decl),
689/// [`services`](FlmRegistry::services), [`styles`](FlmRegistry::styles),
690/// [`scripts`](FlmRegistry::scripts),
691/// [`native_implications`](FlmRegistry::native_implications),
692/// [`digest`](FlmRegistry::digest).
693///
694/// # Examples
695///
696/// ```
697/// use std::sync::Arc;
698/// use flm_core::core::registry::{
699/// BuildError, CapabilityDef, FeatureBuilder, FeatureInfo, FlmFeature, build_registry,
700/// };
701///
702/// struct Counting;
703/// impl FlmFeature for Counting {
704/// fn info(&self) -> FeatureInfo { FeatureInfo::new("counting", "Counting") }
705/// fn register(&self, b: &mut FeatureBuilder<'_>) -> Result<(), BuildError> {
706/// b.capability(CapabilityDef::new("counting.done"))
707/// }
708/// }
709///
710/// let registry = build_registry([Arc::new(Counting) as Arc<dyn FlmFeature>])?;
711/// let id = registry.cap_id("counting.done").expect("declared above");
712/// assert_eq!(registry.capability(id).owner, "counting");
713/// assert!(registry.cap_id("counting.undone").is_none());
714/// # Ok::<(), flm_core::core::registry::RegistryBuildError>(())
715/// ```
716pub struct FlmRegistry {
717 features: Vec<FeatureInfo>,
718 lang: BuiltLang,
719 structural: Arc<StructuralElements>,
720 elements: Vec<ElementEntry>,
721 elem_index: BTreeMap<usize, ElemIdx>,
722 elements_by_name: BTreeMap<ElementName, Vec<ElemIdx>>,
723 aspects: BTreeMap<TypeId, (&'static str, ElemBitset)>,
724 occurrable: BTreeSet<ElementName>,
725 capabilities: Vec<CapabilityEntry>,
726 cap_ids: BTreeMap<CapName, CapId>,
727 collections: BTreeMap<CapName, CollectionEntry>,
728 tables: Vec<TableEntry>,
729 table_ids: BTreeMap<CapName, TableId>,
730 stages: Vec<StageEntry>,
731 stage_ids: BTreeMap<StageName, StageIdx>,
732 orderings: Vec<OrderingDef>,
733 rules: Vec<RuleEntry>,
734 rule_ids: BTreeMap<RuleName, RuleIdx>,
735 rules_by_element: BTreeMap<ElementName, Vec<RuleIdx>>,
736 presentation: BTreeMap<ElementName, PresentationEntry>,
737 backends: BTreeMap<BackendName, BackendEntry>,
738 outputs: BTreeMap<OutputName, OutputEntry>,
739 workflows: BTreeMap<WorkflowName, WorkflowEntry>,
740 options: BTreeMap<OptionKey, OptionDecl>,
741 services: Services,
742 styles: Vec<(FeatureName, StyleDef)>,
743 scripts: Vec<(FeatureName, ScriptDef)>,
744 native_implications: Vec<(FeatureName, NativeImplication)>,
745 peer_backends: Vec<PeerBackendEntry>,
746 peer_elements: Vec<PeerElementEntry>,
747 peer_tables: Vec<PeerTableEntry>,
748 peer_scoped_packages: Vec<PeerScopedPackageEntry>,
749 peer_element_values: Vec<PeerElementValueEntry>,
750 argument_roles: Vec<ArgumentRoleEntry>,
751 peer_argument_roles: Vec<PeerArgumentRoleEntry>,
752 element_type_texts: BTreeMap<ElementName, ElementTypeText>,
753 declarations: Declarations,
754 digest: u64,
755 build_diagnostics: FlmDiagnostics,
756}
757
758impl FlmRegistry {
759 /// Numbers the checked declarations `roster` and builds the lookup
760 /// structures over them, together with the other results of the build.
761 ///
762 /// `roster` must have passed the checks of the validate phase. Numbering
763 /// resolves names to numbers once more, and returns a reference that the
764 /// checks let through as an error instead of panicking, so a gap in the
765 /// checks makes the build fail instead of a later step. `set_aside` is
766 /// the result of resolving the peer declarations: for each rule name, the
767 /// unresolved names the rule depends on.
768 ///
769 /// # Errors
770 ///
771 /// Every [`BuildError::Undeclared`] found while numbering.
772 pub(crate) fn assemble(
773 roster: Roster,
774 structural: Arc<StructuralElements>,
775 lang: BuiltLang,
776 services: Services,
777 digest: u64,
778 build_diagnostics: FlmDiagnostics,
779 set_aside: BTreeMap<RuleName, Vec<PeerName>>,
780 ) -> Result<FlmRegistry, Vec<BuildError>> {
781 let mut errors: Vec<BuildError> = Vec::new();
782
783 // --- elements -----------------------------------------------------------------
784 let mut elements: Vec<ElementEntry> = Vec::new();
785 let mut elem_index: BTreeMap<usize, ElemIdx> = BTreeMap::new();
786 let mut elements_by_name: BTreeMap<ElementName, Vec<ElemIdx>> = BTreeMap::new();
787 // An element value two features declare is numbered where it is first
788 // met, and owned by the feature placed last in the final order: between
789 // features, the feature placed last wins. The language's own elements
790 // are owned by no feature, so a feature that declares one owns it. The
791 // final order is the one the user states, so the user decides which
792 // feature owns such a value.
793 let final_order = &roster.features;
794 let position = |owner: &FeatureName| final_order.iter().position(|info| info.name == *owner);
795 let mut intern_element =
796 |element: &Arc<ElementSpec>, owner: FeatureName, kind: ElementKind| {
797 let key = Arc::as_ptr(element) as usize;
798 if let Some(idx) = elem_index.get(&key) {
799 let entry = &mut elements[idx.0 as usize];
800 if position(&owner) > position(&entry.owner) {
801 entry.owner = owner;
802 }
803 return;
804 }
805 let idx = ElemIdx(elements.len() as u32);
806 elem_index.insert(key, idx);
807 elements_by_name.entry(element.name.clone()).or_default().push(idx);
808 elements.push(ElementEntry { element: Arc::clone(element), owner, idx, kind });
809 };
810 let language_owner: FeatureName = FeatureName::from(crate::lang::mint::LANGUAGE_OWNER);
811 for element in structural.all() {
812 intern_element(element, language_owner.clone(), ElementKind::Structural);
813 }
814 let mut values: Vec<(Arc<ElementSpec>, FeatureName)> = Vec::new();
815 for def in &roster.elements {
816 values.push((Arc::clone(&def.element), def.owner.clone()));
817 }
818 for fallback in &roster.fallbacks {
819 values.push((Arc::clone(&fallback.element), fallback.owner.clone()));
820 }
821 for package in &roster.scoped_packages {
822 for def in &package.elements {
823 values.push((Arc::clone(&def.element), def.owner.clone()));
824 }
825 }
826 for (element, owner) in &values {
827 intern_element(element, owner.clone(), ElementKind::Source);
828 }
829 for record in &roster.presentation {
830 intern_element(&record.element, record.owner.clone(), ElementKind::Presentation);
831 }
832 let mut aspects: BTreeMap<TypeId, (&'static str, ElemBitset)> = BTreeMap::new();
833 for entry in &elements {
834 for (id, name, _) in entry.element.aspects.entries() {
835 aspects.entry(id).or_insert_with(|| (name, ElemBitset::new())).1.insert(entry.idx);
836 }
837 }
838 let occurrable: BTreeSet<ElementName> = elements
839 .iter()
840 .filter(|entry| entry.kind != ElementKind::Presentation)
841 .filter(|entry| entry.element.name != structural::PLACEHOLDER)
842 .map(|entry| entry.element.name.clone())
843 .collect();
844
845 // --- capabilities and tables ----------------------------------------------------
846 let mut capabilities: Vec<CapabilityEntry> = Vec::new();
847 let mut cap_ids: BTreeMap<CapName, CapId> = BTreeMap::new();
848 let mut refines_names: Vec<Option<CapName>> = Vec::new();
849 for (owner, def) in &roster.capabilities {
850 let id = CapId(capabilities.len() as u32);
851 cap_ids.insert(def.name.clone(), id);
852 refines_names.push(def.refines.clone());
853 capabilities.push(CapabilityEntry {
854 name: def.name.clone(),
855 docs: def.docs.clone(),
856 owner: owner.clone(),
857 id,
858 refines: None,
859 default: def.default,
860 table: None,
861 external: false,
862 unprovided: def.unprovided.clone(),
863 ancestors: Vec::new(),
864 children: Vec::new(),
865 });
866 }
867 let mut tables: Vec<TableEntry> = Vec::new();
868 let mut table_ids: BTreeMap<CapName, TableId> = BTreeMap::new();
869 for record in &roster.tables {
870 let table_id = TableId(tables.len() as u32);
871 let cap_id = CapId(capabilities.len() as u32);
872 cap_ids.insert(record.def.name.clone(), cap_id);
873 table_ids.insert(record.def.name.clone(), table_id);
874 refines_names.push(record.refines.clone());
875 capabilities.push(CapabilityEntry {
876 name: record.def.name.clone(),
877 docs: record.def.docs.clone(),
878 owner: record.def.owner.clone(),
879 id: cap_id,
880 refines: None,
881 default: record.default,
882 table: Some(table_id),
883 external: record.external,
884 unprovided: None,
885 ancestors: Vec::new(),
886 children: Vec::new(),
887 });
888 tables.push(TableEntry {
889 def: record.def.clone(),
890 id: table_id,
891 cap: cap_id,
892 external: record.external,
893 });
894 }
895 for (index, parent) in refines_names.iter().enumerate() {
896 if let Some(parent) = parent {
897 match cap_ids.get(parent) {
898 Some(parent_id) => {
899 capabilities[index].refines = Some(*parent_id);
900 capabilities[parent_id.0 as usize].children.push(CapId(index as u32));
901 }
902 None => errors.push(BuildError::Undeclared {
903 feature: capabilities[index].owner.clone(),
904 kind: "capability",
905 site: Site::CapabilityRefines {
906 capability: capabilities[index].name.clone(),
907 },
908 name: parent.name().clone(),
909 roster: cap_ids.keys().map(|n| n.name().clone()).collect(),
910 }),
911 }
912 }
913 }
914 for index in 0..capabilities.len() {
915 let mut chain = vec![CapId(index as u32)];
916 let mut current = capabilities[index].refines;
917 while let Some(parent) = current {
918 if chain.contains(&parent) {
919 break;
920 }
921 chain.push(parent);
922 current = capabilities[parent.0 as usize].refines;
923 }
924 capabilities[index].ancestors = chain;
925 }
926 let cap_roster: Vec<Name> = cap_ids.keys().map(|n| n.name().clone()).collect();
927 let mut collections: BTreeMap<CapName, CollectionEntry> = BTreeMap::new();
928 for (owner, def) in &roster.collections {
929 collections.insert(
930 def.name.clone(),
931 CollectionEntry {
932 name: def.name.clone(),
933 docs: def.docs.clone(),
934 owner: owner.clone(),
935 members: BTreeSet::new(),
936 },
937 );
938 }
939 for (owner, collection, member) in &roster.members {
940 match (collections.get_mut(collection), cap_ids.get(member)) {
941 (Some(entry), Some(id)) => {
942 entry.members.insert(*id);
943 }
944 _ => errors.push(BuildError::Undeclared {
945 feature: owner.clone(),
946 kind: "capability",
947 site: Site::CollectionMember {
948 collection: collection.clone(),
949 member: member.clone(),
950 },
951 name: member.name().clone(),
952 roster: cap_roster.clone(),
953 }),
954 }
955 }
956
957 // --- stages -----------------------------------------------------------------------
958 let mut stages: Vec<StageEntry> = Vec::new();
959 let mut stage_ids: BTreeMap<StageName, StageIdx> = BTreeMap::new();
960 for record in roster.stages {
961 let idx = StageIdx(stages.len() as u32);
962 let mut provides: BTreeSet<CapId> = BTreeSet::new();
963 let mut writes: Vec<TableId> = Vec::new();
964 let add_cap = |id: CapId, provides: &mut BTreeSet<CapId>| {
965 provides.extend(capabilities[id.0 as usize].ancestors.iter().copied());
966 };
967 for capability in &record.decl.provides {
968 match cap_ids.get(capability) {
969 Some(id) => add_cap(*id, &mut provides),
970 None => errors.push(BuildError::Undeclared {
971 feature: record.owner.clone(),
972 kind: "capability",
973 site: Site::StageProvides { stage: record.decl.name.clone() },
974 name: capability.name().clone(),
975 roster: cap_roster.clone(),
976 }),
977 }
978 }
979 for table in &record.decl.writes {
980 match table_ids.get(&table.name) {
981 Some(id) => {
982 writes.push(*id);
983 add_cap(tables[id.0 as usize].cap, &mut provides);
984 }
985 None => errors.push(BuildError::Undeclared {
986 feature: record.owner.clone(),
987 kind: "table",
988 site: Site::StageWrites { stage: record.decl.name.clone() },
989 name: table.name.name().clone(),
990 roster: table_ids.keys().map(|n| n.name().clone()).collect(),
991 }),
992 }
993 }
994 stage_ids.insert(record.decl.name.clone(), idx);
995 stages.push(StageEntry {
996 name: record.decl.name.clone(),
997 kind: record.kind,
998 decl: record.decl,
999 rewrite: record.rewrite,
1000 owner: record.owner,
1001 idx,
1002 provides,
1003 writes,
1004 });
1005 }
1006 let orderings: Vec<OrderingDef> =
1007 roster.orderings.into_iter().map(|(_, def)| def).collect();
1008
1009 // --- rules, presentation, backends, outputs, workflows ------------------------
1010 let mut rules: Vec<RuleEntry> = Vec::new();
1011 let mut rule_ids: BTreeMap<RuleName, RuleIdx> = BTreeMap::new();
1012 let mut rules_by_element: BTreeMap<ElementName, Vec<RuleIdx>> = BTreeMap::new();
1013 for (owner, rule) in roster.rules {
1014 let idx = RuleIdx(rules.len() as u32);
1015 rule_ids.insert(rule.name.clone(), idx);
1016 rules_by_element.entry(rule.element.clone()).or_default().push(idx);
1017 let set_aside = set_aside.get(&rule.name).cloned().unwrap_or_default();
1018 rules.push(RuleEntry { rule, owner, idx, set_aside });
1019 }
1020 let presentation: BTreeMap<ElementName, PresentationEntry> = roster
1021 .presentation
1022 .into_iter()
1023 .map(|record| {
1024 (
1025 record.element.name.clone(),
1026 PresentationEntry {
1027 element: record.element,
1028 payload: record.payload,
1029 docs: record.docs,
1030 owner: record.owner,
1031 },
1032 )
1033 })
1034 .collect();
1035 let backends: BTreeMap<BackendName, BackendEntry> = roster
1036 .backends
1037 .into_iter()
1038 .map(|record| {
1039 (
1040 record.name.clone(),
1041 BackendEntry {
1042 name: record.name,
1043 native: record.native.into_iter().collect(),
1044 lowering: StageIdx(record.lowering as u32),
1045 emit: StageIdx(record.emit as u32),
1046 final_stage: StageIdx(record.final_stage as u32),
1047 owner: record.owner,
1048 docs: record.docs,
1049 },
1050 )
1051 })
1052 .collect();
1053 let mut outputs: BTreeMap<OutputName, OutputEntry> = BTreeMap::new();
1054 for (owner, def) in roster.outputs {
1055 match (table_ids.get(&def.table), cap_ids.get(&def.capability)) {
1056 (Some(table), Some(capability)) => {
1057 outputs.insert(
1058 def.name.clone(),
1059 OutputEntry { table: *table, capability: *capability, def, owner },
1060 );
1061 }
1062 (None, _) => errors.push(BuildError::Undeclared {
1063 feature: owner.clone(),
1064 kind: "table",
1065 site: Site::OutputTable { output: def.name.clone() },
1066 name: def.table.name().clone(),
1067 roster: table_ids.keys().map(|n| n.name().clone()).collect(),
1068 }),
1069 (_, None) => errors.push(BuildError::Undeclared {
1070 feature: owner.clone(),
1071 kind: "capability",
1072 site: Site::OutputCapability { output: def.name.clone() },
1073 name: def.capability.name().clone(),
1074 roster: cap_roster.clone(),
1075 }),
1076 }
1077 }
1078 let workflows: BTreeMap<WorkflowName, WorkflowEntry> = roster
1079 .workflows
1080 .into_iter()
1081 .map(|(owner, def)| (def.name.clone(), WorkflowEntry { def, owner }))
1082 .collect();
1083 let options: BTreeMap<OptionKey, OptionDecl> =
1084 roster.options.into_iter().map(|decl| (decl.key.clone(), decl)).collect();
1085 let peer_backends: Vec<PeerBackendEntry> = roster
1086 .peer_backends
1087 .into_iter()
1088 .map(|record| PeerBackendEntry {
1089 resolved: backends.contains_key(&record.name),
1090 name: record.name,
1091 owner: record.owner,
1092 docs: record.docs,
1093 })
1094 .collect();
1095 let peer_elements: Vec<PeerElementEntry> = roster
1096 .peer_elements
1097 .into_iter()
1098 .map(|record| PeerElementEntry {
1099 resolved: presentation.contains_key(&record.name),
1100 name: record.name,
1101 payload: record.payload,
1102 owner: record.owner,
1103 docs: record.docs,
1104 })
1105 .collect();
1106 let peer_tables: Vec<PeerTableEntry> = roster
1107 .peer_tables
1108 .into_iter()
1109 .map(|record| PeerTableEntry {
1110 resolved: table_ids.contains_key(&record.name),
1111 name: record.name,
1112 value: record.value,
1113 owner: record.owner,
1114 docs: record.docs,
1115 })
1116 .collect();
1117 let packages: BTreeSet<&Name> =
1118 roster.scoped_packages.iter().map(|package| &package.name).collect();
1119 let peer_scoped_packages: Vec<PeerScopedPackageEntry> = roster
1120 .peer_scoped_packages
1121 .into_iter()
1122 .map(|record| PeerScopedPackageEntry {
1123 resolved: packages.contains(&record.name),
1124 name: record.name,
1125 owner: record.owner,
1126 docs: record.docs,
1127 })
1128 .collect();
1129 let peer_element_values: Vec<PeerElementValueEntry> = roster
1130 .peer_element_values
1131 .into_iter()
1132 .map(|record| PeerElementValueEntry {
1133 element: record.element,
1134 names: record.names,
1135 owner: record.owner,
1136 resolved: record.resolved,
1137 })
1138 .collect();
1139
1140 let argument_roles: Vec<ArgumentRoleEntry> = roster
1141 .argument_roles
1142 .into_iter()
1143 .map(|(owner, def)| ArgumentRoleEntry { name: def.name, docs: def.docs, owner })
1144 .collect();
1145 let peer_argument_roles: Vec<PeerArgumentRoleEntry> = roster
1146 .peer_argument_roles
1147 .into_iter()
1148 .map(|record| PeerArgumentRoleEntry {
1149 resolved: argument_roles.iter().any(|role| role.name == record.name),
1150 name: record.name,
1151 owner: record.owner,
1152 })
1153 .collect();
1154 let element_type_texts: BTreeMap<ElementName, ElementTypeText> = roster
1155 .element_type_texts
1156 .into_iter()
1157 .map(|text| (text.element.clone(), text))
1158 .collect();
1159 // The declarations are kept as the build leaves them: moved, not
1160 // copied, now that nothing else reads them.
1161 let declarations =
1162 Declarations::new(roster.elements, roster.scoped_packages, roster.fallbacks, roster.overrides);
1163
1164 if !errors.is_empty() {
1165 return Err(errors);
1166 }
1167 Ok(FlmRegistry {
1168 features: roster.features,
1169 lang,
1170 structural,
1171 elements,
1172 elem_index,
1173 elements_by_name,
1174 aspects,
1175 occurrable,
1176 capabilities,
1177 cap_ids,
1178 collections,
1179 tables,
1180 table_ids,
1181 stages,
1182 stage_ids,
1183 orderings,
1184 rules,
1185 rule_ids,
1186 rules_by_element,
1187 presentation,
1188 backends,
1189 outputs,
1190 workflows,
1191 options,
1192 services,
1193 styles: roster.styles,
1194 scripts: roster.scripts,
1195 native_implications: roster.native_implications,
1196 peer_backends,
1197 peer_elements,
1198 peer_tables,
1199 peer_scoped_packages,
1200 peer_element_values,
1201 argument_roles,
1202 peer_argument_roles,
1203 element_type_texts,
1204 declarations,
1205 digest,
1206 build_diagnostics,
1207 })
1208 }
1209
1210 // --- features and the language ----------------------------------------------------
1211
1212 /// The registry's build diagnostics: the problems found while the registry
1213 /// was built that did not make the build fail.
1214 ///
1215 /// They are of two kinds:
1216 ///
1217 /// - What the [late-initialization hooks](super::LateInit) reported about
1218 /// the configuration they prepared (for example, the errors and warnings
1219 /// of author-written definitions compiled when the registry was built,
1220 /// each identifying the definition it belongs to).
1221 /// - One Note ([`UnresolvedPeer`](super::UnresolvedPeer)) for each [peer
1222 /// declaration](PeerName) that no feature of this registry resolves,
1223 /// which gives the feature, the name, and the rules and stages set aside
1224 /// because of it. For a service slot or an element type, there is one
1225 /// Note per feature and name, however many values the feature gave for
1226 /// it.
1227 ///
1228 /// Nothing else is recorded here; for example, a member added to a
1229 /// collection that no feature declares is dropped without a diagnostic.
1230 ///
1231 /// The build succeeds even when these diagnostics include errors. (The
1232 /// user-definitions feature, for example, keeps a refused definition
1233 /// registered and reports it again wherever a document uses it.) An
1234 /// embedding program can report this collection once per build, so that
1235 /// the cause appears next to its consequences.
1236 pub fn build_diagnostics(&self) -> &FlmDiagnostics {
1237 &self.build_diagnostics
1238 }
1239
1240 /// The description of each registered feature, in registration order.
1241 pub fn features(&self) -> &[FeatureInfo] {
1242 &self.features
1243 }
1244
1245 /// Whether a feature called `name` is registered. A stage or a host that
1246 /// adapts to the presence of a feature asks here.
1247 pub fn has_feature(&self, name: &str) -> bool {
1248 self.features.iter().any(|info| info.name == name)
1249 }
1250
1251 /// The description of the feature called `name`, or `None` when no such
1252 /// feature is registered.
1253 pub fn feature(&self, name: &str) -> Option<&FeatureInfo> {
1254 self.features.iter().find(|info| info.name == name)
1255 }
1256
1257 /// The FLM language with which every document is parsed under this
1258 /// registry: the callable names, their syntax and the parsing settings,
1259 /// built from the element declarations of every feature.
1260 pub fn lang(&self) -> &BuiltLang {
1261 &self.lang
1262 }
1263
1264 /// The language's structural elements as this registry froze them, with
1265 /// the aspects that features attached to them.
1266 pub fn structural(&self) -> &Arc<StructuralElements> {
1267 &self.structural
1268 }
1269
1270 /// The element declarations, scoped packages, fallbacks and overrides
1271 /// that this registry's features declared, as declared
1272 /// ([`Declarations`]).
1273 ///
1274 /// The language that documents are parsed with ([`FlmRegistry::lang`])
1275 /// was built from them, and keeps only what a parse needs. This accessor
1276 /// gives the declarations themselves, with the names, syntax, arguments,
1277 /// argument roles, parsing modes and documentation of every command, for
1278 /// a program that describes what an author may write.
1279 pub fn declarations(&self) -> &Declarations {
1280 &self.declarations
1281 }
1282
1283 // --- elements ---------------------------------------------------------------------
1284
1285 /// Every registered element value, in numbering order: entry `n` is the
1286 /// element with index `n`.
1287 pub fn elements(&self) -> &[ElementEntry] {
1288 &self.elements
1289 }
1290
1291 /// This registry's number for the element **value** `element`, or `None`
1292 /// when this registry does not hold that value.
1293 ///
1294 /// Values are told apart by identity (which shared value it is), not by
1295 /// name: a value copied from another registry is not found here, even if
1296 /// a value of the same name is registered. An index is therefore
1297 /// unambiguous even when two features register elements under one name.
1298 pub fn elem_idx(&self, element: &Arc<ElementSpec>) -> Option<ElemIdx> {
1299 self.elem_index.get(&(Arc::as_ptr(element) as usize)).copied()
1300 }
1301
1302 /// The element entry numbered `idx`, or `None` when this registry has no
1303 /// such number, which means that the index came from another registry.
1304 pub fn element(&self, idx: ElemIdx) -> Option<&ElementEntry> {
1305 self.elements.get(idx.0 as usize)
1306 }
1307
1308 /// The numbers of every registered value whose element type name is
1309 /// `name`, in numbering order; empty when no value has that name.
1310 ///
1311 /// Two features may each register an element of the same type name, so
1312 /// this method returns a list.
1313 pub fn elements_named(&self, name: &str) -> &[ElemIdx] {
1314 self.elements_by_name.get(name).map(Vec::as_slice).unwrap_or(&[])
1315 }
1316
1317 /// A registered value whose element type name is `name`, or `None` when
1318 /// no value has that name. Where several features register a value under
1319 /// the name, the value of the feature placed last in the feature order;
1320 /// of one feature's values, the first in numbering order.
1321 ///
1322 /// Use [`element_value`](FlmRegistry::element_value) instead wherever
1323 /// taking one of several values would be wrong.
1324 pub fn element_named(&self, name: &str) -> Option<&Arc<ElementSpec>> {
1325 let mut chosen: Option<&ElementEntry> = None;
1326 for entry in self.elements_named(name).iter().filter_map(|idx| self.element(*idx)) {
1327 let later = match chosen {
1328 Some(best) => self.feature_position(&entry.owner) > self.feature_position(&best.owner),
1329 None => true,
1330 };
1331 if later {
1332 chosen = Some(entry);
1333 }
1334 }
1335 chosen.map(|entry| &entry.element)
1336 }
1337
1338 /// The position of the feature `name` in the final order of the features
1339 /// (their registration order), counting from zero, or `None` when `name`
1340 /// is no feature of this registry, such as the language's own name or the
1341 /// embedding program's ([`HOST_FEATURE`](super::HOST_FEATURE)).
1342 ///
1343 /// Comparing positions picks, of several competing items of different
1344 /// features, the one of the feature placed last; an item of no feature
1345 /// compares lower than every feature's.
1346 pub(crate) fn feature_position(&self, name: &str) -> Option<usize> {
1347 self.features.iter().position(|info| info.name == name)
1348 }
1349
1350 /// The registered value whose element type name is `name`, when that
1351 /// value is unique: `Ok(Some(..))` when exactly one value has the name,
1352 /// `Ok(None)` when none does, and an error when several do.
1353 ///
1354 /// Reading a stored tree back uses this lookup. A node written to storage
1355 /// holds its element's type name, not the element itself, so reading it
1356 /// back must find the value again by name. Where the name does not
1357 /// identify one value, reading refuses instead of taking the first match,
1358 /// because a wrong element would make an incorrect document whose damage
1359 /// would be found much later.
1360 ///
1361 /// # Errors
1362 ///
1363 /// [`AmbiguousElement`], which lists every feature that registered a
1364 /// value under `name`.
1365 pub fn element_value(&self, name: &str) -> Result<Option<&Arc<ElementSpec>>, AmbiguousElement> {
1366 match self.elements_named(name) {
1367 [] => Ok(None),
1368 [idx] => Ok(self.element(*idx).map(|entry| &entry.element)),
1369 several => Err(AmbiguousElement {
1370 name: ElementName::from(name),
1371 owners: several
1372 .iter()
1373 .filter_map(|idx| self.element(*idx))
1374 .map(|e| e.owner.clone())
1375 .collect(),
1376 }),
1377 }
1378 }
1379
1380 /// Every documentation text of an element type, in the order of the
1381 /// types' names: the texts of the language's structural element types,
1382 /// of the presentation elements, and those that features gave
1383 /// ([`FeatureBuilder::element_type_text`](super::FeatureBuilder::element_type_text)).
1384 /// An element type of which no declaration gives a text is not listed.
1385 pub fn element_type_texts(&self) -> impl Iterator<Item = &ElementTypeText> + '_ {
1386 self.element_type_texts.values()
1387 }
1388
1389 /// The documentation text of the element type `name`, with the feature
1390 /// that gave it; `None` when no declaration gives that type a text, or
1391 /// when no feature declares it. See [`ElementTypeText`].
1392 pub fn element_type_text(&self, name: &str) -> Option<&ElementTypeText> {
1393 self.element_type_texts.get(name)
1394 }
1395
1396 /// The set of every registered element that carries the aspect `A`, given
1397 /// as its trait-object type: `registry.aspect_bitset::<dyn Referenceable>()`.
1398 /// Empty when no element carries it.
1399 ///
1400 /// The registry build computes the set, so this method copies a small bit
1401 /// set instead of searching. A stage that visits every element with some
1402 /// behavior asks once, then tests each node against the result.
1403 pub fn aspect_bitset<A: ?Sized + Any>(&self) -> ElemBitset {
1404 self.aspects.get(&TypeId::of::<A>()).map(|(_, bits)| bits.clone()).unwrap_or_default()
1405 }
1406
1407 /// Whether the element numbered `idx` carries the aspect `A`. `false` when
1408 /// no element carries it, and when `idx` is not a number of this
1409 /// registry.
1410 pub fn has_aspect<A: ?Sized + Any>(&self, idx: ElemIdx) -> bool {
1411 self.aspects.get(&TypeId::of::<A>()).map(|(_, bits)| bits.contains(idx)).unwrap_or(false)
1412 }
1413
1414 /// The type names of every aspect that some registered element carries, in
1415 /// name order. This list serves to show a person what a registry offers,
1416 /// not for lookup.
1417 pub fn aspect_names(&self) -> Vec<&'static str> {
1418 let mut names: Vec<&'static str> = self.aspects.values().map(|(name, _)| *name).collect();
1419 names.sort_unstable();
1420 names
1421 }
1422
1423 /// The type names of every element that can appear in a parsed document:
1424 /// every element of [`ElementKind::Source`] (an element declared with a
1425 /// syntax, an element a declaration creates without syntax, the element of
1426 /// a field, the element of a fallback), and every structural element
1427 /// except the template placeholder, which exists only inside a template.
1428 ///
1429 /// Presentation elements are not in the set, because they appear only in
1430 /// the trees a backend writes. The elements that represent a command no
1431 /// feature defines (`flm.unknown.macro`, `flm.unknown.environment`) are in
1432 /// the set, since a document can contain one.
1433 ///
1434 /// When a plan is built, the check that a backend can write everything a
1435 /// document may contain runs over this set: every element in it must have
1436 /// a lowering into the backend's native set.
1437 pub fn occurrable_elements(&self) -> &BTreeSet<ElementName> {
1438 &self.occurrable
1439 }
1440
1441 // --- capabilities -----------------------------------------------------------------
1442
1443 /// Every capability, including the capabilities of tables, in identifier
1444 /// order: entry `n` is the capability with identifier `n`.
1445 pub fn capabilities(&self) -> &[CapabilityEntry] {
1446 &self.capabilities
1447 }
1448
1449 /// The identifier of the capability called `name` (one declared on its own
1450 /// or one that came with a table), or `None` when no capability has that
1451 /// name.
1452 pub fn cap_id(&self, name: &str) -> Option<CapId> {
1453 self.cap_ids.get(name).copied()
1454 }
1455
1456 /// The capability with the identifier `id`.
1457 ///
1458 /// # Panics
1459 ///
1460 /// Panics when `id` is beyond this registry's capabilities, which can
1461 /// happen only when another registry assigned it; an identifier from
1462 /// another registry that falls within range returns the wrong entry
1463 /// instead. Identifiers obtained from this registry, from its entries, or
1464 /// from a plan built with it are always valid here.
1465 pub fn capability(&self, id: CapId) -> &CapabilityEntry {
1466 &self.capabilities[id.0 as usize]
1467 }
1468
1469 /// The capability called `name`, or `None` when no capability has that
1470 /// name.
1471 pub fn capability_named(&self, name: &str) -> Option<&CapabilityEntry> {
1472 self.cap_id(name).map(|id| self.capability(id))
1473 }
1474
1475 /// The default refinement of the capability `id`, which a demand for that
1476 /// capability alone selects, or `None` when none of its refinements is
1477 /// marked as the default.
1478 ///
1479 /// The registry build checks that at most one refinement of a capability
1480 /// is marked as the default.
1481 ///
1482 /// # Panics
1483 ///
1484 /// Panics when `id` is not an identifier of this registry.
1485 pub fn default_refinement(&self, id: CapId) -> Option<CapId> {
1486 self.capability(id)
1487 .refinements()
1488 .iter()
1489 .copied()
1490 .find(|child| self.capability(*child).default)
1491 }
1492
1493 /// Every declared collection, in name order.
1494 pub fn collections(&self) -> impl Iterator<Item = &CollectionEntry> + '_ {
1495 self.collections.values()
1496 }
1497
1498 /// The collection called `name`, or `None` when no collection has that
1499 /// name.
1500 pub fn collection(&self, name: &str) -> Option<&CollectionEntry> {
1501 self.collections.get(name)
1502 }
1503
1504 // --- tables -------------------------------------------------------------------------
1505
1506 /// Every declared table, in identifier order: entry `n` is the table with
1507 /// identifier `n`.
1508 pub fn tables(&self) -> &[TableEntry] {
1509 &self.tables
1510 }
1511
1512 /// The identifier of the table called `name`, or `None` when no table has
1513 /// that name.
1514 pub fn table_id(&self, name: &str) -> Option<TableId> {
1515 self.table_ids.get(name).copied()
1516 }
1517
1518 /// The table with the identifier `id`.
1519 ///
1520 /// # Panics
1521 ///
1522 /// Panics when `id` is not an identifier of this registry.
1523 pub fn table(&self, id: TableId) -> &TableEntry {
1524 &self.tables[id.0 as usize]
1525 }
1526
1527 /// The table called `name`, or `None` when no table has that name.
1528 pub fn table_named(&self, name: &str) -> Option<&TableEntry> {
1529 self.table_id(name).map(|id| self.table(id))
1530 }
1531
1532 /// The external tables: the tables that no stage writes, whose values the
1533 /// caller installs when a run is constructed, in identifier order. A host
1534 /// asks here which values it must supply.
1535 pub fn external_tables(&self) -> impl Iterator<Item = &TableEntry> + '_ {
1536 self.tables.iter().filter(|entry| entry.external)
1537 }
1538
1539 /// Whether some registered stage writes the table `id`; only then can a
1540 /// plan schedule a stage that writes it.
1541 ///
1542 /// A declared table is in one of three situations, and this method tells
1543 /// the first from the other two: some stage writes it; it is an
1544 /// [external](TableEntry::external) table, whose value the host installs
1545 /// when a run is constructed and which no stage may write; or it is
1546 /// neither, because the stage that writes it belongs to a feature this
1547 /// registry does not hold, and nothing can provide it. `id`
1548 /// is an identifier of this registry, as for
1549 /// [`table`](FlmRegistry::table); an identifier beyond this registry's
1550 /// tables returns `false`.
1551 pub fn table_has_writer(&self, id: TableId) -> bool {
1552 self.stages.iter().any(|stage| stage.writes.contains(&id))
1553 }
1554
1555 // --- stages -----------------------------------------------------------------------
1556
1557 /// Every registered stage, of both forms, in registration order: entry `n`
1558 /// is the stage with index `n`.
1559 pub fn stages(&self) -> &[StageEntry] {
1560 &self.stages
1561 }
1562
1563 /// The index of the stage called `name`, or `None` when no stage has that
1564 /// name.
1565 pub fn stage_idx(&self, name: &str) -> Option<StageIdx> {
1566 self.stage_ids.get(name).copied()
1567 }
1568
1569 /// The stage with index `idx`.
1570 ///
1571 /// # Panics
1572 ///
1573 /// Panics when `idx` is not an index of this registry.
1574 pub fn stage(&self, idx: StageIdx) -> &StageEntry {
1575 &self.stages[idx.0 as usize]
1576 }
1577
1578 /// The stage called `name`, or `None` when no stage has that name.
1579 pub fn stage_named(&self, name: &str) -> Option<&StageEntry> {
1580 self.stage_idx(name).map(|idx| self.stage(idx))
1581 }
1582
1583 /// Every set of ordering edges that a feature placed on a stage, in
1584 /// registration order. A plan applies them in addition to the order that
1585 /// the stages' own declarations imply.
1586 pub fn orderings(&self) -> &[OrderingDef] {
1587 &self.orderings
1588 }
1589
1590 // --- rules and presentation ---------------------------------------------------------
1591
1592 /// Every registered lowering rule, in registration order: entry `n` is the
1593 /// rule with index `n`. The list includes the rules that are set aside.
1594 pub fn rules(&self) -> &[RuleEntry] {
1595 &self.rules
1596 }
1597
1598 /// The index of the lowering rule called `name`, or `None` when no rule has
1599 /// that name.
1600 pub fn rule_idx(&self, name: &str) -> Option<RuleIdx> {
1601 self.rule_ids.get(name).copied()
1602 }
1603
1604 /// The lowering rule with index `idx`.
1605 ///
1606 /// # Panics
1607 ///
1608 /// Panics when `idx` is not an index of this registry.
1609 pub fn rule(&self, idx: RuleIdx) -> &RuleEntry {
1610 &self.rules[idx.0 as usize]
1611 }
1612
1613 /// The lowering rules that lower the element type called `element`, in
1614 /// registration order; empty when no rule does. The list includes the
1615 /// rules that are set aside.
1616 ///
1617 /// Several rules may lower one element (one per backend, or several
1618 /// renderings to choose from). A plan chooses one per backend in the rule
1619 /// selection order ([`SelectedRules`](crate::core::plan::SelectedRules)),
1620 /// from the plan request's lowering selections and the rules' default
1621 /// marks.
1622 pub fn rules_for(&self, element: &str) -> &[RuleIdx] {
1623 self.rules_by_element.get(element).map(Vec::as_slice).unwrap_or(&[])
1624 }
1625
1626 /// Every lowering rule that is set aside, in registration order. A rule is
1627 /// set aside when it depends on a [peer declaration](PeerName) of its own
1628 /// feature (a backend, an element, or a table it reads) that no feature
1629 /// of this registry declares. A plan never selects such a rule, and the
1630 /// check that a backend can write every element ignores it; each entry's
1631 /// [`set_aside`](RuleEntry::set_aside) lists the unresolved names. Empty
1632 /// for a registry in which every peer declaration resolves, such as one
1633 /// built from the standard features alone.
1634 pub fn set_aside_rules(&self) -> impl Iterator<Item = &RuleEntry> + '_ {
1635 self.rules.iter().filter(|entry| entry.is_set_aside())
1636 }
1637
1638 /// Every [peer declaration](PeerName) of a backend that a feature made, in
1639 /// declaration order, each marked as resolved or not.
1640 pub fn peer_backends(&self) -> &[PeerBackendEntry] {
1641 &self.peer_backends
1642 }
1643
1644 /// Every [peer declaration](PeerName) of a presentation element that a
1645 /// feature made, in declaration order, each marked as resolved or not. A
1646 /// resolved entry's payload type is the registered element's: the build
1647 /// refuses any other.
1648 pub fn peer_elements(&self) -> &[PeerElementEntry] {
1649 &self.peer_elements
1650 }
1651
1652 /// Every [peer declaration](PeerName) of a table that a feature made, in
1653 /// declaration order, each marked as resolved or not. A resolved entry's
1654 /// value type is the declared table's: the build refuses any other.
1655 pub fn peer_tables(&self) -> &[PeerTableEntry] {
1656 &self.peer_tables
1657 }
1658
1659 /// Every [peer declaration](PeerName) of a scoped package that a feature
1660 /// made, in declaration order, each marked as resolved or not
1661 /// ([`FeatureBuilder::peer_scoped_package`](super::FeatureBuilder::peer_scoped_package)).
1662 pub fn peer_scoped_packages(&self) -> &[PeerScopedPackageEntry] {
1663 &self.peer_scoped_packages
1664 }
1665
1666 /// Every [peer declaration](PeerName) of an element value that a feature
1667 /// made, in declaration order, each marked as resolved or not
1668 /// ([`FeatureBuilder::peer_element_value`](super::FeatureBuilder::peer_element_value)).
1669 /// The value of a resolved declaration is also among the registry's
1670 /// [elements](FlmRegistry::elements); the value of an unresolved one was
1671 /// dropped.
1672 pub fn peer_element_values(&self) -> &[PeerElementValueEntry] {
1673 &self.peer_element_values
1674 }
1675
1676 /// Every [peer declaration](PeerName) of an argument role that a feature
1677 /// made, in declaration order, each marked as resolved or not
1678 /// ([`FeatureBuilder::peer_argument_role`](super::FeatureBuilder::peer_argument_role)).
1679 pub fn peer_argument_roles(&self) -> &[PeerArgumentRoleEntry] {
1680 &self.peer_argument_roles
1681 }
1682
1683 // --- argument roles -----------------------------------------------------------------
1684
1685 /// Every argument role, in declaration order. An argument role is a
1686 /// registered name for what an argument holds (a label, a citation key,
1687 /// the path of a file), declared with
1688 /// [`FeatureBuilder::argument_role`](super::FeatureBuilder::argument_role);
1689 /// the arguments that have a role are listed by
1690 /// [`Declarations::role_uses`](super::Declarations::role_uses).
1691 pub fn argument_roles(&self) -> &[ArgumentRoleEntry] {
1692 &self.argument_roles
1693 }
1694
1695 /// The argument role called `name`, or `None` when no feature of this
1696 /// registry declares it.
1697 pub fn argument_role_named(&self, name: &str) -> Option<&ArgumentRoleEntry> {
1698 self.argument_roles.iter().find(|role| role.name == *name)
1699 }
1700
1701 /// Every peer contribution: every value that a feature contributed to a
1702 /// service slot another feature owns
1703 /// ([`FeatureBuilder::peer_slot`](super::FeatureBuilder::peer_slot)), in
1704 /// contribution order, each marked as resolved or not. An unresolved
1705 /// contribution refers to a service slot that no feature of this registry
1706 /// declares, and its value was dropped when the service slots were
1707 /// assembled.
1708 ///
1709 /// This is the service-slot form of a [peer declaration](PeerName). Read
1710 /// the values themselves through [`services`](FlmRegistry::services), where
1711 /// a resolved contribution is one value of its service slot like any other.
1712 pub fn peer_slots(&self) -> &[PeerContribution] {
1713 self.services.peer_contributions()
1714 }
1715
1716 /// Every registered presentation element, in name order.
1717 pub fn presentation_elements(&self) -> impl Iterator<Item = &PresentationEntry> + '_ {
1718 self.presentation.values()
1719 }
1720
1721 /// The presentation element called `name`, or `None` when no presentation
1722 /// element has that name.
1723 pub fn presentation_element(&self, name: &str) -> Option<&PresentationEntry> {
1724 self.presentation.get(name)
1725 }
1726
1727 // --- backends, outputs, workflows -----------------------------------------------------
1728
1729 /// Every registered backend, in name order.
1730 pub fn backends(&self) -> impl Iterator<Item = &BackendEntry> + '_ {
1731 self.backends.values()
1732 }
1733
1734 /// The backend called `name`, or `None` when no backend has that name.
1735 pub fn backend(&self, name: &str) -> Option<&BackendEntry> {
1736 self.backends.get(name)
1737 }
1738
1739 /// Every registered output, in name order. A host lists these to show what
1740 /// can be produced.
1741 pub fn outputs(&self) -> impl Iterator<Item = &OutputEntry> + '_ {
1742 self.outputs.values()
1743 }
1744
1745 /// The output called `name`, or `None` when no output has that name.
1746 pub fn output(&self, name: &str) -> Option<&OutputEntry> {
1747 self.outputs.get(name)
1748 }
1749
1750 /// Every registered workflow, in name order, as declared (without the
1751 /// fields it inherits).
1752 pub fn workflows(&self) -> impl Iterator<Item = &WorkflowEntry> + '_ {
1753 self.workflows.values()
1754 }
1755
1756 /// The workflow called `name` as declared (without the fields it
1757 /// inherits), or `None` when no workflow has that name.
1758 pub fn workflow(&self, name: &str) -> Option<&WorkflowEntry> {
1759 self.workflows.get(name)
1760 }
1761
1762 /// The workflow called `name` and the workflows it extends, directly or
1763 /// not, in order from the workflow that extends none to the workflow
1764 /// called `name`, which comes last. `None` when no workflow has that name.
1765 ///
1766 /// A workflow's fields are read along this chain
1767 /// ([`combined_workflow`](FlmRegistry::combined_workflow)); a host that
1768 /// keeps data per workflow walks the chain to find what a workflow
1769 /// inherits. The registry build refuses a workflow that extends an
1770 /// unregistered workflow, and a chain that leads back to itself, so the
1771 /// chain always starts at a registered workflow that extends none.
1772 pub fn workflow_chain(&self, name: &str) -> Option<Vec<&WorkflowDef>> {
1773 let mut chain = vec![&self.workflow(name)?.def];
1774 while let Some(parent) = chain.last().and_then(|def| def.extends.as_ref()) {
1775 // The registry build rules out both ends of this walk; the checks only keep
1776 // it finite.
1777 let Some(entry) = self.workflow(parent) else { break };
1778 if chain.len() > self.workflows.len() {
1779 break;
1780 }
1781 chain.push(&entry.def);
1782 }
1783 chain.reverse();
1784 Some(chain)
1785 }
1786
1787 /// The workflow called `name` with the fields it inherits: the fields of
1788 /// the workflows of its [chain](FlmRegistry::workflow_chain), combined
1789 /// from the workflow that extends none towards the workflow called
1790 /// `name`, each field a workflow declares replacing the inherited one
1791 /// ([`WorkflowDef::replace_declared_fields`]). A workflow that lists
1792 /// outputs therefore replaces the inherited list instead of adding to it,
1793 /// and a workflow that lists none inherits the whole list. The result has
1794 /// the name `name` and the `extends` of the workflow called `name`. `None`
1795 /// when no workflow has that name.
1796 pub fn combined_workflow(&self, name: &str) -> Option<WorkflowDef> {
1797 let chain = self.workflow_chain(name)?;
1798 let named = chain.last()?.name.clone();
1799 let mut combined = WorkflowDef::new(named);
1800 for def in chain {
1801 combined.replace_declared_fields(def.clone());
1802 }
1803 Some(combined)
1804 }
1805
1806 // --- options, services, records, digest -----------------------------------------------
1807
1808 /// Every declared option type, keyed by the type itself, in key order.
1809 /// See [option types](crate::model::options).
1810 pub fn options(&self) -> &BTreeMap<OptionKey, OptionDecl> {
1811 &self.options
1812 }
1813
1814 /// The declaration of the option type `key`, or `None` when no feature
1815 /// declared it. The declaration gives the feature that owns the option
1816 /// type and its binding: where its values may be set.
1817 pub fn option_decl(&self, key: &OptionKey) -> Option<&OptionDecl> {
1818 self.options.get(key)
1819 }
1820
1821 /// The assembled services: every service slot that features declared,
1822 /// filled with the contributions that features and the embedding program
1823 /// made. See [`crate::core::services`].
1824 pub fn services(&self) -> &Services {
1825 &self.services
1826 }
1827
1828 /// The [style definitions](StyleDef) that features recorded, each with the
1829 /// feature that recorded it, in registration order.
1830 ///
1831 /// A backend that writes stylesheets into its output resolves the
1832 /// requirements recorded for its trees against this list, in this order. A
1833 /// host that assembles the stylesheets itself reads the list directly.
1834 pub fn styles(&self) -> &[(FeatureName, StyleDef)] {
1835 &self.styles
1836 }
1837
1838 /// The [script definitions](ScriptDef) that features recorded, each with
1839 /// the feature that recorded it, in registration order: the counterpart of
1840 /// [`styles`](FlmRegistry::styles) for scripts, resolved the same way.
1841 pub fn scripts(&self) -> &[(FeatureName, ScriptDef)] {
1842 &self.scripts
1843 }
1844
1845 /// The [native-set implications](NativeImplication) that features
1846 /// declared, each with the feature that declared it, in registration
1847 /// order.
1848 ///
1849 /// The build checked that every backend of this registry satisfies every
1850 /// implication, so a backend's native set holds what each implication
1851 /// requires. This list serves a host or a test that inspects them. They are
1852 /// not inputs of the [digest](FlmRegistry::digest), because an implication
1853 /// decides whether a registry builds, never what a run produces.
1854 pub fn native_implications(&self) -> &[(FeatureName, NativeImplication)] {
1855 &self.native_implications
1856 }
1857
1858 /// This registry's [digest](crate::model::digest): a 64-bit number that
1859 /// stands for everything about the registry that can change what
1860 /// processing produces.
1861 ///
1862 /// It is part of every cache key the library forms, so that data computed
1863 /// under one registry is never read back under another.
1864 pub fn digest(&self) -> u64 {
1865 self.digest
1866 }
1867}
1868
1869impl fmt::Debug for FlmRegistry {
1870 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1871 f.debug_struct("FlmRegistry")
1872 .field("features", &self.features.iter().map(|i| &i.name).collect::<Vec<_>>())
1873 .field("elements", &self.elements.len())
1874 .field("capabilities", &self.capabilities.len())
1875 .field("tables", &self.tables.len())
1876 .field("stages", &self.stages.len())
1877 .field("rules", &self.rules.len())
1878 .field("digest", &format_args!("{:016x}", self.digest))
1879 .finish()
1880 }
1881}
1882
1883#[cfg(test)]
1884mod tests {
1885 use super::*;
1886
1887 #[test]
1888 fn a_bitset_holds_and_lists_its_indices() {
1889 let mut set = ElemBitset::new();
1890 set.insert(ElemIdx(3));
1891 set.insert(ElemIdx(70));
1892 assert!(set.contains(ElemIdx(3)));
1893 assert!(!set.contains(ElemIdx(4)));
1894 assert_eq!(set.iter().collect::<Vec<_>>(), [ElemIdx(3), ElemIdx(70)]);
1895 assert_eq!(set.len(), 2);
1896 }
1897}