use std::any::{Any, TypeId};
use std::fmt;
use std::sync::Arc;
use crate::model::element::ElementSpec;
use crate::core::lowering::LoweringRule;
use crate::model::names::{
BackendName, CapName, ElementName, FeatureName, Name, OutputName, RuleName, StageName,
WorkflowName,
};
use crate::model::options::{Bind, OptionDecl, Options, TypeKey};
use crate::core::registry::entities::{
ArgumentRoleDef, BackendDef, CapabilityDef, CollectionDef, Finalizer, LateInit, NativeImplication,
OrderingDef, OutputDef, ScriptDef, StyleDef, WorkflowDef,
};
use crate::core::registry::feature::FeatureInfo;
use crate::core::registry::frozen::ElementTypeText;
use crate::core::registry::order::FeatureChain;
use crate::core::services::{
Arity, Contribution, ServiceError, ServiceRequirement, Services, SlotDecl, SlotTarget,
};
use crate::core::stage::{RewriteDecl, RewriteStage, Stage, StageDecl};
use crate::core::data::table::{Table, TableDef, TableHandle, TableName, TableType};
use crate::lang::mint::{CallableKind, ElementDef, FallbackDef, OverrideDef, ScopedPackageDef};
use crate::lang::{LangBuildError, PresPayload};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Site {
CapabilityRefines {
capability: CapName,
},
CollectionMember {
collection: CapName,
member: CapName,
},
StageProvides {
stage: StageName,
},
StageWrites {
stage: StageName,
},
OrderingEdges,
OrderingEdge {
stage: StageName,
},
BackendNative {
backend: BackendName,
},
RuleLowers {
rule: RuleName,
},
RuleProduces {
rule: RuleName,
},
RuleRequires {
rule: RuleName,
},
RuleReads {
rule: RuleName,
},
RuleDefaultMark {
rule: RuleName,
},
OutputCapability {
output: OutputName,
},
OutputTable {
output: OutputName,
},
OutputMadeFrom {
output: OutputName,
},
WorkflowExtends {
workflow: WorkflowName,
},
WorkflowOutputs {
workflow: WorkflowName,
},
WorkflowDemands {
workflow: WorkflowName,
},
WorkflowPrefers {
workflow: WorkflowName,
},
WorkflowLoweringSelection {
workflow: WorkflowName,
},
WorkflowLoweringPreference {
workflow: WorkflowName,
},
WorkflowUnsupported {
workflow: WorkflowName,
},
Attachment {
aspect: &'static str,
},
NativeImplication,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ArgumentPlace {
pub command: String,
pub field: Option<String>,
pub argument: Option<String>,
pub index: usize,
}
impl fmt::Display for Site {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Site::CapabilityRefines { capability } => {
write!(f, "capability `{capability}` refines")
}
Site::CollectionMember { collection, .. } => {
write!(f, "a member added to collection `{collection}` is")
}
Site::StageProvides { stage } => write!(f, "stage `{stage}` provides"),
Site::StageWrites { stage } => write!(f, "stage `{stage}` writes"),
Site::OrderingEdges => f.write_str("an ordering declaration applies to"),
Site::OrderingEdge { stage } => {
write!(f, "an ordering declaration of stage `{stage}` refers to")
}
Site::BackendNative { backend } => {
write!(f, "backend `{backend}` declares that it writes natively")
}
Site::RuleLowers { rule } => write!(f, "rule `{rule}` lowers"),
Site::RuleProduces { rule } => write!(f, "rule `{rule}` produces"),
Site::RuleRequires { rule } => write!(f, "rule `{rule}` requires"),
Site::RuleReads { rule } => write!(f, "rule `{rule}` reads"),
Site::RuleDefaultMark { rule } => write!(f, "rule `{rule}` is marked as the default on"),
Site::OutputCapability { output } => write!(f, "output `{output}` demands"),
Site::OutputTable { output } => write!(f, "output `{output}` keeps its artifacts in"),
Site::OutputMadeFrom { output } => write!(f, "output `{output}` is made from"),
Site::WorkflowExtends { workflow } => write!(f, "workflow `{workflow}` extends"),
Site::WorkflowOutputs { workflow } => write!(f, "workflow `{workflow}` asks for"),
Site::WorkflowDemands { workflow } => write!(f, "workflow `{workflow}` demands"),
Site::WorkflowPrefers { workflow } => write!(f, "workflow `{workflow}` prefers"),
Site::WorkflowLoweringSelection { workflow } => {
write!(f, "workflow `{workflow}` selects lowering rules for")
}
Site::WorkflowLoweringPreference { workflow } => {
write!(f, "workflow `{workflow}` prefers")
}
Site::WorkflowUnsupported { workflow } => {
write!(f, "workflow `{workflow}`'s list of elements accepted as unrenderable refers to")
}
Site::Attachment { aspect } => write!(f, "aspect `{aspect}` is attached to"),
Site::NativeImplication => {
f.write_str("a rule that requires backends to write an element natively refers to")
}
}
}
}
impl fmt::Display for ArgumentPlace {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.argument {
Some(name) => write!(f, "the argument `{name}`")?,
None => write!(f, "argument {}", self.index + 1)?,
}
if let Some(field) = &self.field {
write!(f, " of the field `\\{field}`")?;
}
write!(f, " of `{}`", self.command)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RoundTwoAction {
DeclareSlot,
Contribute,
RequireSlot,
RegisterFinalizer,
}
impl fmt::Display for RoundTwoAction {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
RoundTwoAction::DeclareSlot => "declare a service slot",
RoundTwoAction::Contribute => "contribute to a service slot",
RoundTwoAction::RequireSlot => "require a service slot",
RoundTwoAction::RegisterFinalizer => "register a finalizer",
})
}
}
#[derive(Debug, Clone)]
pub enum BuildError {
Feature {
feature: FeatureName,
detail: String,
},
UndeclaredElementTypeText {
feature: FeatureName,
element: ElementName,
declarers: Vec<FeatureName>,
},
DuplicateElementTypeText {
element: ElementName,
first: FeatureName,
second: FeatureName,
},
DuplicateFeature {
feature: FeatureName,
},
Duplicate {
kind: &'static str,
name: Name,
first: FeatureName,
second: FeatureName,
},
TableCapabilityClash {
name: CapName,
table_owner: FeatureName,
capability_owner: FeatureName,
},
Undeclared {
feature: FeatureName,
kind: &'static str,
site: Site,
name: Name,
roster: Vec<Name>,
},
UndeclaredArgumentRole {
feature: FeatureName,
place: Box<ArgumentPlace>,
role: Name,
roster: Vec<Name>,
},
TableTypeMismatch {
feature: FeatureName,
site: Site,
table: CapName,
declared: &'static str,
referenced: &'static str,
},
RefinesCycle {
cycle: Vec<CapName>,
},
TwoDefaults {
parent: CapName,
first: CapName,
second: CapName,
},
DefaultWithoutParent {
name: CapName,
},
CheckWrites {
stage: StageName,
table: CapName,
},
ExternalTableWritten {
stage: StageName,
table: CapName,
},
CollectionAsCapability {
stage: StageName,
site: Site,
collection: CapName,
},
TwoDefaultRules {
element: ElementName,
backend: Option<BackendName>,
first: RuleName,
second: RuleName,
},
ExtendsCycle {
cycle: Vec<WorkflowName>,
},
OutputCapabilityMismatch {
output: OutputName,
capability: CapName,
table: CapName,
},
OutputTableNotArtifactSet {
output: OutputName,
table: CapName,
ty: &'static str,
},
DefinitionPartTable {
kind: &'static str,
definition: Name,
table: CapName,
found: Option<&'static str>,
},
AspectCollision {
feature: FeatureName,
element: ElementName,
aspect: &'static str,
},
NativeSetIncomplete {
backend: BackendName,
because: Option<ElementName>,
must_claim: ElementName,
},
PeerElementMismatch {
feature: FeatureName,
element: ElementName,
declared: Option<&'static str>,
expected: &'static str,
},
PeerTableMismatch {
feature: FeatureName,
table: CapName,
declared: &'static str,
expected: &'static str,
},
Service(ServiceError),
ContributionAfterAssembly {
feature: FeatureName,
action: RoundTwoAction,
},
Lang(LangBuildError),
LateInit {
feature: FeatureName,
detail: String,
},
FeatureOrderCycle {
cycle: Vec<FeatureName>,
chains: Vec<FeatureChain>,
},
}
fn giver(owner: &FeatureName) -> String {
if owner.as_str() == crate::lang::mint::LANGUAGE_OWNER {
String::from("the language")
} else {
format!("feature ‘{owner}’")
}
}
fn givers(owners: &[FeatureName]) -> String {
let named: Vec<String> = owners.iter().map(giver).collect();
match named.split_last() {
Some((last, [])) => last.clone(),
Some((last, head)) => format!("{} and {last}", head.join(", ")),
None => String::new(),
}
}
fn join<'a>(names: impl IntoIterator<Item = &'a Name>) -> String {
names.into_iter().map(|name| name.as_str()).collect::<Vec<_>>().join(", ")
}
impl fmt::Display for BuildError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BuildError::Feature { feature, detail } => {
write!(f, "feature `{feature}`: {detail}")
}
BuildError::UndeclaredElementTypeText { feature, element, declarers } => {
if declarers.is_empty() {
write!(
f,
"Invalid documentation text for undeclared element type ‘{element}’ \
(given by {})",
giver(feature)
)
} else {
write!(
f,
"Invalid documentation text for element type ‘{element}’ from {}: an \
element type’s text must be given by a feature declaring the type \
(declared by {})",
giver(feature),
givers(declarers)
)
}
}
BuildError::DuplicateElementTypeText { element, first, second } => {
if first == second {
write!(
f,
"Duplicate documentation text for element type ‘{element}’ (given twice \
by {})",
giver(first)
)
} else {
write!(
f,
"Duplicate documentation text for element type ‘{element}’ (given by {} \
and by {})",
giver(first),
giver(second)
)
}
}
BuildError::DuplicateFeature { feature } => {
write!(f, "two features are registered under the name `{feature}`")
}
BuildError::Duplicate { kind, name, first, second } => {
write!(f, "{kind} `{name}` is declared twice: first by feature `{first}`, then by feature `{second}`")
}
BuildError::TableCapabilityClash { name, table_owner, capability_owner } => write!(
f,
"`{name}` is declared both as a table, by feature `{table_owner}`, and as a \
capability, by feature `{capability_owner}`; a table's name is already a \
capability, so no capability may be declared under it"
),
BuildError::Undeclared { feature, kind, site, name, roster } => write!(
f,
"feature `{feature}`: {site} the {kind} `{name}`, but no feature declares this \
{kind}; declared {kind} names: [{}]",
join(roster)
),
BuildError::UndeclaredArgumentRole { feature, place, role, roster } => write!(
f,
"feature `{feature}`: {place} has the argument role `{role}`, which no registered \
feature declares; a feature that sets another feature's argument role must \
declare it with `FeatureBuilder::peer_argument_role`; declared argument role \
names: [{}]",
join(roster)
),
BuildError::TableTypeMismatch { feature, site, table, declared, referenced } => write!(
f,
"feature `{feature}`: {site} the table `{table}` as holding `{referenced}`, but \
the table is declared as holding `{declared}`"
),
BuildError::RefinesCycle { cycle } => {
let mut names: Vec<&str> = cycle.iter().map(|n| n.as_str()).collect();
names.push(cycle[0].as_str());
write!(f, "capabilities refine each other in a cycle: {}", names.join(" -> "))
}
BuildError::TwoDefaults { parent, first, second } => write!(
f,
"capability `{parent}` may have only one default refinement, but `{first}` and \
`{second}` are both marked default"
),
BuildError::DefaultWithoutParent { name } => {
write!(f, "capability `{name}` is marked as a default refinement but refines no capability")
}
BuildError::CheckWrites { stage, table } => {
write!(f, "check stage `{stage}` declares a write of table `{table}`; a check stage writes no table")
}
BuildError::ExternalTableWritten { stage, table } => {
write!(
f,
"stage `{stage}` declares a write of the external table `{table}`; only the \
caller installs an external table, and no stage may write it"
)
}
BuildError::CollectionAsCapability { stage, site, collection } => write!(
f,
"{site} the collection `{collection}`; a collection can be demanded but never \
provided, so stage `{stage}` may not provide it"
),
BuildError::TwoDefaultRules { element, backend, first, second } => match backend {
Some(backend) => write!(
f,
"element `{element}` may have only one default lowering rule on backend \
`{backend}`, but rules `{first}` and `{second}` are both marked default there"
),
None => write!(
f,
"element `{element}` may have only one general default lowering rule, but \
rules `{first}` and `{second}` are both marked as the general default"
),
},
BuildError::ExtendsCycle { cycle } => {
let mut names: Vec<&str> = cycle.iter().map(|n| n.as_str()).collect();
names.push(cycle[0].as_str());
write!(f, "workflows extend each other in a cycle: {}", names.join(" -> "))
}
BuildError::OutputCapabilityMismatch { output, capability, table } => write!(
f,
"output `{output}` demands the capability `{capability}`, which is neither the \
capability of its table `{table}` nor a refinement of it"
),
BuildError::OutputTableNotArtifactSet { output, table, ty } => write!(
f,
"the table `{table}` of output `{output}` holds `{ty}`; an output's table must \
hold an artifact set"
),
BuildError::DefinitionPartTable { kind, definition, table, found: None } => write!(
f,
"the table `{table}` that the {kind} definition `{definition}` takes a part from \
must be declared by a feature of the registry"
),
BuildError::DefinitionPartTable { kind, definition, table, found: Some(found) } => write!(
f,
"the table `{table}` that the {kind} definition `{definition}` takes a part from \
must hold `DefinitionText`, not `{found}`"
),
BuildError::AspectCollision { feature, element, aspect } => write!(
f,
"feature `{feature}` attaches aspect `{aspect}` to element `{element}`, which \
already carries that aspect; an element carries each aspect at most once"
),
BuildError::NativeSetIncomplete { backend, because, must_claim } => match because {
Some(because) => write!(
f,
"backend `{backend}` must write the element `{must_claim}` natively, \
because it writes the element `{because}` natively"
),
None => write!(
f,
"backend `{backend}` must write the element `{must_claim}` natively, as \
every backend must"
),
},
BuildError::PeerElementMismatch { feature, element, declared, expected } => {
match declared {
Some(declared) => write!(
f,
"feature `{feature}` refers to the presentation element `{element}` as \
carrying payload `{expected}`, but the element is declared with payload \
`{declared}`"
),
None => write!(
f,
"feature `{feature}` refers to the presentation element `{element}` as \
carrying payload `{expected}`, but `{element}` is declared as an element \
that a parsed document can contain, which carries no payload"
),
}
}
BuildError::PeerTableMismatch { feature, table, declared, expected } => write!(
f,
"feature `{feature}` refers to the table `{table}` as holding `{expected}`, but \
the table is declared as holding `{declared}`"
),
BuildError::Service(error) => fmt::Display::fmt(error, f),
BuildError::ContributionAfterAssembly { feature, action } => write!(
f,
"a finalizer of feature `{feature}` may not {action}; only the feature's \
`register` method may"
),
BuildError::Lang(error) => fmt::Display::fmt(error, f),
BuildError::LateInit { feature, detail } => {
write!(f, "the late-initialization hook of feature `{feature}` failed: {detail}")
}
BuildError::FeatureOrderCycle { cycle, chains } => {
let written: Vec<String> =
chains.iter().map(|chain| format!("`{chain}` ({})", chain.origin())).collect();
let (subject, verb) = match written.as_slice() {
[one] => (format!("the chain {one}"), "orders"),
[first, last] => (format!("the chains {first} and {last}"), "order"),
[head @ .., last] => (format!("the chains {}, and {last}", head.join(", ")), "order"),
[] => (String::from("the chains"), "order"),
};
let mut names: Vec<&str> = cycle.iter().map(|name| name.as_str()).collect();
if let Some(first) = names.first().copied() {
names.push(first);
}
write!(
f,
"the feature order must not contain a cycle, but {subject} {verb} the features \
in the cycle `{}`",
names.join(" < ")
)
}
}
}
}
impl std::error::Error for BuildError {}
impl From<ServiceError> for BuildError {
fn from(error: ServiceError) -> BuildError {
BuildError::Service(error)
}
}
pub struct Attachment {
pub owner: FeatureName,
pub element: ElementName,
pub aspect_id: TypeId,
pub aspect_name: &'static str,
pub imp: Arc<dyn Any + Send + Sync>,
}
pub struct TableRecord {
pub def: TableDef,
pub external: bool,
pub refines: Option<CapName>,
pub default: bool,
}
pub enum StageKind {
Pipeline(Arc<dyn Stage>),
Rewrite(Arc<dyn RewriteStage>),
}
pub struct StageRecord {
pub owner: FeatureName,
pub kind: StageKind,
pub decl: StageDecl,
pub rewrite: Option<RewriteDecl>,
}
pub struct BackendRecord {
pub owner: FeatureName,
pub name: BackendName,
pub native: Vec<ElementName>,
pub docs: String,
pub lowering: usize,
pub emit: usize,
pub final_stage: usize,
}
pub struct PresentationRecord {
pub owner: FeatureName,
pub element: Arc<ElementSpec>,
pub payload: TypeKey,
pub docs: String,
}
pub struct PeerBackendRecord {
pub owner: FeatureName,
pub name: BackendName,
pub docs: String,
}
pub struct PeerElementRecord {
pub owner: FeatureName,
pub name: ElementName,
pub payload: TypeKey,
pub docs: String,
}
pub struct PeerTableRecord {
pub owner: FeatureName,
pub name: CapName,
pub value: TableType,
pub docs: String,
}
pub struct PeerScopedPackageRecord {
pub owner: FeatureName,
pub name: Name,
pub docs: String,
}
pub struct PeerArgumentRoleRecord {
pub owner: FeatureName,
pub name: Name,
}
pub struct PeerElementValueRecord {
pub owner: FeatureName,
pub element: ElementName,
pub names: Vec<Name>,
pub position: usize,
pub resolved: bool,
}
pub struct DigestInput {
pub owner: FeatureName,
pub bytes: Vec<u8>,
}
#[derive(Default)]
pub struct Roster {
pub features: Vec<FeatureInfo>,
pub elements: Vec<ElementDef>,
pub attachments: Vec<Attachment>,
pub fallbacks: Vec<FallbackDef>,
pub scoped_packages: Vec<ScopedPackageDef>,
pub overrides: Vec<OverrideDef>,
pub capabilities: Vec<(FeatureName, CapabilityDef)>,
pub collections: Vec<(FeatureName, CollectionDef)>,
pub argument_roles: Vec<(FeatureName, ArgumentRoleDef)>,
pub element_type_texts: Vec<ElementTypeText>,
pub members: Vec<(FeatureName, CapName, CapName)>,
pub tables: Vec<TableRecord>,
pub stages: Vec<StageRecord>,
pub orderings: Vec<(FeatureName, OrderingDef)>,
pub rules: Vec<(FeatureName, LoweringRule)>,
pub presentation: Vec<PresentationRecord>,
pub backends: Vec<BackendRecord>,
pub outputs: Vec<(FeatureName, OutputDef)>,
pub workflows: Vec<(FeatureName, WorkflowDef)>,
pub workflow_fields: Vec<(FeatureName, WorkflowDef)>,
pub options: Vec<OptionDecl>,
pub slots: Vec<SlotDecl>,
pub contributions: Vec<Contribution>,
pub requirements: Vec<ServiceRequirement>,
pub finalizers: Vec<(FeatureName, Arc<dyn Finalizer>)>,
pub late_inits: Vec<(FeatureName, Arc<dyn LateInit>)>,
pub styles: Vec<(FeatureName, StyleDef)>,
pub scripts: Vec<(FeatureName, ScriptDef)>,
pub native_implications: Vec<(FeatureName, NativeImplication)>,
pub peer_backends: Vec<PeerBackendRecord>,
pub peer_elements: Vec<PeerElementRecord>,
pub peer_tables: Vec<PeerTableRecord>,
pub peer_scoped_packages: Vec<PeerScopedPackageRecord>,
pub peer_element_values: Vec<PeerElementValueRecord>,
pub peer_argument_roles: Vec<PeerArgumentRoleRecord>,
pub digest_inputs: Vec<DigestInput>,
pub errors: Vec<BuildError>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Round {
One,
Two,
}
pub struct FeatureBuilder<'a> {
roster: &'a mut Roster,
feature: FeatureName,
round: Round,
services: Option<&'a Services>,
}
impl<'a> FeatureBuilder<'a> {
pub(crate) fn round_one(roster: &'a mut Roster, feature: FeatureName) -> FeatureBuilder<'a> {
FeatureBuilder { roster, feature, round: Round::One, services: None }
}
pub(crate) fn round_two(
roster: &'a mut Roster,
feature: FeatureName,
services: &'a Services,
) -> FeatureBuilder<'a> {
FeatureBuilder { roster, feature, round: Round::Two, services: Some(services) }
}
pub fn feature(&self) -> &FeatureName {
&self.feature
}
pub fn services(&self) -> Option<&'a Services> {
self.services
}
fn round_one_only(&self, action: RoundTwoAction) -> Result<(), BuildError> {
if self.round == Round::Two {
return Err(BuildError::ContributionAfterAssembly {
feature: self.feature.clone(),
action,
});
}
Ok(())
}
pub fn element(&mut self, mut def: ElementDef) -> Result<(), BuildError> {
def.owner = self.feature.clone();
self.roster.elements.push(def);
Ok(())
}
pub fn peer_element_value(&mut self, mut def: ElementDef) -> Result<(), BuildError> {
def.owner = self.feature.clone();
self.roster.peer_element_values.push(PeerElementValueRecord {
owner: self.feature.clone(),
element: def.element.name.clone(),
names: def.names.clone(),
position: self.roster.elements.len(),
resolved: false,
});
self.roster.elements.push(def);
Ok(())
}
pub fn element_type_text(
&mut self,
name: impl Into<ElementName>,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.element_type_texts.push(ElementTypeText {
element: name.into(),
docs: crate::kept_docs(docs),
owner: self.feature.clone(),
});
Ok(())
}
pub fn attach<A: ?Sized + Any + Send + Sync>(
&mut self,
element: impl Into<ElementName>,
imp: Arc<A>,
) -> Result<(), BuildError> {
const {
assert!(
size_of::<&A>() == 2 * size_of::<*const ()>(),
"the aspect must be given as its trait-object type, as in \
.attach::<dyn MyAspect>(…)"
);
}
self.roster.attachments.push(Attachment {
owner: self.feature.clone(),
element: element.into(),
aspect_id: TypeId::of::<A>(),
aspect_name: std::any::type_name::<A>(),
imp: Arc::new(imp),
});
Ok(())
}
pub fn fallback(&mut self, mut def: FallbackDef) -> Result<(), BuildError> {
def.owner = self.feature.clone();
self.roster.fallbacks.push(def);
Ok(())
}
pub fn scoped_package(&mut self, mut def: ScopedPackageDef) -> Result<(), BuildError> {
def.owner = self.feature.clone();
def.docs = crate::kept_docs(def.docs);
for element in &mut def.elements {
element.owner = self.feature.clone();
}
self.roster.scoped_packages.push(def);
Ok(())
}
pub fn override_callable(
&mut self,
kind: CallableKind,
name: impl Into<Name>,
) -> Result<(), BuildError> {
self.roster.overrides.push(OverrideDef {
owner: self.feature.clone(),
kind,
name: name.into(),
});
Ok(())
}
pub fn capability(&mut self, def: CapabilityDef) -> Result<(), BuildError> {
self.roster.capabilities.push((self.feature.clone(), def));
Ok(())
}
pub fn argument_role(&mut self, name: impl Into<Name>, docs: impl Into<String>) -> Result<(), BuildError> {
self.roster.argument_roles.push((self.feature.clone(), ArgumentRoleDef::new(name, docs)));
Ok(())
}
pub fn peer_argument_role(&mut self, name: impl Into<Name>) -> Result<(), BuildError> {
self.roster.peer_argument_roles.push(PeerArgumentRoleRecord {
owner: self.feature.clone(),
name: name.into(),
});
Ok(())
}
pub fn collection(&mut self, def: CollectionDef) -> Result<(), BuildError> {
self.roster.collections.push((self.feature.clone(), def));
Ok(())
}
pub fn collection_member(
&mut self,
collection: impl Into<CapName>,
member: impl Into<CapName>,
) -> Result<(), BuildError> {
self.roster.members.push((self.feature.clone(), collection.into(), member.into()));
Ok(())
}
pub fn table_type_named(&self, name: &str) -> Option<TableType> {
let declared = self.roster.tables.iter().find(|record| record.def.name.as_str() == name);
declared.map(|record| record.def.ty).or_else(|| {
self.roster
.peer_tables
.iter()
.find(|record| record.owner == self.feature && record.name.as_str() == name)
.map(|record| record.value)
})
}
fn table_record<T: Table>(
&mut self,
name: CapName,
docs: String,
external: bool,
) -> TableHandle<T> {
self.roster.tables.push(TableRecord {
def: TableDef {
name: name.clone(),
ty: TableType::of::<T>(),
docs,
owner: self.feature.clone(),
},
external,
refines: None,
default: false,
});
TableHandle::new(name)
}
pub fn table<T: Table>(
&mut self,
name: TableName<T>,
docs: impl Into<String>,
) -> Result<TableHandle<T>, BuildError> {
Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), false))
}
pub fn table_named<T: Table>(
&mut self,
name: impl Into<CapName>,
docs: impl Into<String>,
) -> Result<TableHandle<T>, BuildError> {
Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), false))
}
pub fn table_refining_named<T: Table>(
&mut self,
name: impl Into<CapName>,
parent: impl Into<CapName>,
docs: impl Into<String>,
) -> Result<TableHandle<T>, BuildError> {
let handle = self.table_record::<T>(name.into(), crate::kept_docs(docs), false);
if let Some(record) = self.roster.tables.last_mut() {
record.refines = Some(parent.into());
}
Ok(handle)
}
pub fn external_table<T: Table>(
&mut self,
name: TableName<T>,
docs: impl Into<String>,
) -> Result<TableHandle<T>, BuildError> {
Ok(self.table_record::<T>(CapName::from(name.name()), crate::kept_docs(docs), true))
}
pub fn external_table_named<T: Table>(
&mut self,
name: impl Into<CapName>,
docs: impl Into<String>,
) -> Result<TableHandle<T>, BuildError> {
Ok(self.table_record::<T>(name.into(), crate::kept_docs(docs), true))
}
fn push_stage(&mut self, stage: Arc<dyn Stage>) -> usize {
let decl = stage.decl();
self.roster.stages.push(StageRecord {
owner: self.feature.clone(),
kind: StageKind::Pipeline(stage),
decl,
rewrite: None,
});
self.roster.stages.len() - 1
}
pub fn stage(&mut self, stage: Arc<dyn Stage>) -> Result<(), BuildError> {
self.push_stage(stage);
Ok(())
}
pub fn rewrite_stage(&mut self, stage: Arc<dyn RewriteStage>) -> Result<(), BuildError> {
let rewrite = stage.decl();
let decl = StageDecl::new(
rewrite.name.clone(),
crate::core::stage::Effect::Compute,
crate::core::stage::Scope::PerTree,
)
.writes(TableHandle::<crate::core::stage::TreesTable>::new(rewrite.publishes.clone()))
.docs(rewrite.docs.clone());
self.roster.tables.push(TableRecord {
def: TableDef {
name: rewrite.publishes.clone(),
ty: TableType::of::<crate::core::stage::TreesTable>(),
docs: rewrite.docs.clone(),
owner: self.feature.clone(),
},
external: false,
refines: rewrite.refines.clone(),
default: rewrite.default,
});
self.roster.stages.push(StageRecord {
owner: self.feature.clone(),
kind: StageKind::Rewrite(stage),
decl,
rewrite: Some(rewrite),
});
Ok(())
}
pub fn ordering(&mut self, def: OrderingDef) -> Result<(), BuildError> {
self.roster.orderings.push((self.feature.clone(), def));
Ok(())
}
pub fn lowering_rule(&mut self, rule: LoweringRule) -> Result<(), BuildError> {
self.roster.rules.push((self.feature.clone(), rule));
Ok(())
}
pub fn presentation_element<P: PresPayload>(
&mut self,
name: impl Into<ElementName>,
docs: impl Into<String>,
) -> Result<Arc<ElementSpec>, BuildError> {
let name = name.into();
let docs = crate::kept_docs(docs);
let element = Arc::new(ElementSpec::new(name).docs(docs.clone()));
self.roster.presentation.push(PresentationRecord {
owner: self.feature.clone(),
element: Arc::clone(&element),
payload: TypeKey::of::<P>(),
docs,
});
Ok(element)
}
pub fn backend(&mut self, def: BackendDef) -> Result<(), BuildError> {
let lowering = self.push_stage(def.lowering);
let emit = self.push_stage(def.emit);
let final_stage = self.push_stage(def.final_stage);
self.roster.backends.push(BackendRecord {
owner: self.feature.clone(),
name: def.name,
native: def.native,
docs: def.docs,
lowering,
emit,
final_stage,
});
Ok(())
}
pub fn native_implication(&mut self, def: NativeImplication) -> Result<(), BuildError> {
self.roster.native_implications.push((self.feature.clone(), def));
Ok(())
}
pub fn peer_backend(
&mut self,
name: impl Into<BackendName>,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_backends.push(PeerBackendRecord {
owner: self.feature.clone(),
name: name.into(),
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn peer_element<P: PresPayload>(
&mut self,
name: impl Into<ElementName>,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_elements.push(PeerElementRecord {
owner: self.feature.clone(),
name: name.into(),
payload: TypeKey::of::<P>(),
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn peer_table<R: Table>(
&mut self,
name: impl Into<CapName>,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_tables.push(PeerTableRecord {
owner: self.feature.clone(),
name: name.into(),
value: TableType::of::<R>(),
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn peer_table_of(
&mut self,
name: impl Into<CapName>,
value: TableType,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_tables.push(PeerTableRecord {
owner: self.feature.clone(),
name: name.into(),
value,
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn presentation_payload_named(&self, name: &str) -> Option<TypeKey> {
self.roster
.presentation
.iter()
.find(|record| record.element.name.as_str() == name)
.map(|record| record.payload)
}
pub fn peer_element_of(
&mut self,
name: impl Into<ElementName>,
payload: TypeKey,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_elements.push(PeerElementRecord {
owner: self.feature.clone(),
name: name.into(),
payload,
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn peer_scoped_package(
&mut self,
name: impl Into<Name>,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.peer_scoped_packages.push(PeerScopedPackageRecord {
owner: self.feature.clone(),
name: name.into(),
docs: crate::kept_docs(docs),
});
Ok(())
}
pub fn output(&mut self, def: OutputDef) -> Result<(), BuildError> {
self.roster.outputs.push((self.feature.clone(), def));
Ok(())
}
pub fn workflow(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
self.roster.workflows.push((self.feature.clone(), def));
Ok(())
}
pub fn workflow_fields(&mut self, def: WorkflowDef) -> Result<(), BuildError> {
self.roster.workflow_fields.push((self.feature.clone(), def));
Ok(())
}
pub fn options<T: Options>(&mut self, bind: Bind) -> Result<(), BuildError> {
self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind));
Ok(())
}
pub fn options_with_docs<T: Options>(
&mut self,
bind: Bind,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.roster.options.push(OptionDecl::of::<T>(self.feature.clone(), bind).docs(docs));
Ok(())
}
pub(crate) fn options_named(&mut self, name: Name, bind: Bind, docs: String) -> Result<(), BuildError> {
self.roster.options.push(OptionDecl::named(name, self.feature.clone(), bind).docs(docs));
Ok(())
}
pub fn service_slot<S: ?Sized + Any + Send + Sync>(
&mut self,
name: impl Into<Name>,
arity: Arity,
docs: impl Into<String>,
) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::DeclareSlot)?;
self.roster.slots.push(SlotDecl {
name: name.into(),
ty: TypeKey::of::<S>(),
arity,
owner: self.feature.clone(),
docs: crate::kept_docs(docs),
});
Ok(())
}
fn contribute_inner<S: ?Sized + Any + Send + Sync>(
&mut self,
target: SlotTarget,
imp: Arc<S>,
prepend: bool,
) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::Contribute)?;
self.roster.contributions.push(Contribution::new(
self.feature.clone(),
target,
imp,
prepend,
));
Ok(())
}
pub fn contribute<S: ?Sized + Any + Send + Sync>(
&mut self,
imp: Arc<S>,
) -> Result<(), BuildError> {
self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, false)
}
pub fn contribute_to<S: ?Sized + Any + Send + Sync>(
&mut self,
slot: impl Into<Name>,
imp: Arc<S>,
) -> Result<(), BuildError> {
self.contribute_inner(SlotTarget::ByName(slot.into()), imp, false)
}
pub fn contribute_first<S: ?Sized + Any + Send + Sync>(
&mut self,
imp: Arc<S>,
) -> Result<(), BuildError> {
self.contribute_inner(SlotTarget::ByType(TypeKey::of::<S>()), imp, true)
}
pub fn contribute_first_to<S: ?Sized + Any + Send + Sync>(
&mut self,
slot: impl Into<Name>,
imp: Arc<S>,
) -> Result<(), BuildError> {
self.contribute_inner(SlotTarget::ByName(slot.into()), imp, true)
}
pub fn peer_slot<S: ?Sized + Any + Send + Sync>(
&mut self,
slot: impl Into<Name>,
imp: Arc<S>,
) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::Contribute)?;
self.roster.contributions.push(
Contribution::new(self.feature.clone(), SlotTarget::ByName(slot.into()), imp, false)
.as_peer(),
);
Ok(())
}
pub fn require_service<S: ?Sized + Any + Send + Sync>(&mut self) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::RequireSlot)?;
self.roster.requirements.push(ServiceRequirement {
owner: self.feature.clone(),
target: SlotTarget::ByType(TypeKey::of::<S>()),
});
Ok(())
}
pub fn require_service_named(&mut self, slot: impl Into<Name>) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::RequireSlot)?;
self.roster.requirements.push(ServiceRequirement {
owner: self.feature.clone(),
target: SlotTarget::ByName(slot.into()),
});
Ok(())
}
pub fn finalizer(&mut self, finalizer: Arc<dyn Finalizer>) -> Result<(), BuildError> {
self.round_one_only(RoundTwoAction::RegisterFinalizer)?;
self.roster.finalizers.push((self.feature.clone(), finalizer));
Ok(())
}
pub fn late_init(&mut self, hook: Arc<dyn LateInit>) -> Result<(), BuildError> {
self.roster.late_inits.push((self.feature.clone(), hook));
Ok(())
}
pub fn style_def(&mut self, mut def: StyleDef) -> Result<(), BuildError> {
def.docs = crate::kept_docs(def.docs);
self.roster.styles.push((self.feature.clone(), def));
Ok(())
}
pub fn script_def(&mut self, mut def: ScriptDef) -> Result<(), BuildError> {
def.docs = crate::kept_docs(def.docs);
self.roster.scripts.push((self.feature.clone(), def));
Ok(())
}
pub fn digest_input(&mut self, bytes: &[u8]) -> Result<(), BuildError> {
self.roster
.digest_inputs
.push(DigestInput { owner: self.feature.clone(), bytes: bytes.to_vec() });
Ok(())
}
}
impl fmt::Debug for FeatureBuilder<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("FeatureBuilder")
.field("feature", &self.feature)
.field("round", &self.round)
.finish()
}
}
pub const HOST_FEATURE: &str = "_host";