use std::collections::BTreeMap;
use crate::identity::NodeId;
use crate::interchange::LanguageId;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AuthoringOperation {
Create,
Modify,
}
impl AuthoringOperation {
pub fn as_str(self) -> &'static str {
match self {
Self::Create => "create",
Self::Modify => "modify",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum FieldUpdate<T> {
Keep,
Clear,
Set(T),
}
impl<T> FieldUpdate<T> {
pub fn is_keep(&self) -> bool {
matches!(self, Self::Keep)
}
pub fn is_clear(&self) -> bool {
matches!(self, Self::Clear)
}
pub fn value(&self) -> Option<&T> {
match self {
Self::Set(value) => Some(value),
Self::Keep | Self::Clear => None,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ParentReference {
Root,
Identity(NodeId),
Object {
id: NodeId,
module: String,
},
Catalog {
id: NodeId,
path: String,
},
Named(String),
}
impl ParentReference {
pub fn named(&self) -> Option<&str> {
match self {
Self::Named(text) => Some(text),
Self::Root | Self::Identity(_) | Self::Object { .. } | Self::Catalog { .. } => None,
}
}
pub fn id(&self) -> Option<NodeId> {
match self {
Self::Identity(id) | Self::Object { id, .. } | Self::Catalog { id, .. } => Some(*id),
Self::Root | Self::Named(_) => None,
}
}
pub fn module(&self) -> Option<&str> {
match self {
Self::Object { module, .. } => Some(module),
Self::Root | Self::Identity(_) | Self::Named(_) | Self::Catalog { .. } => None,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RegistrationField {
Module,
Kind,
Preset,
Parts,
NameZh,
NameEn,
SummaryZh,
SummaryEn,
Exports,
StableName,
NeedsRegistry,
GettingFromOtherRegistry,
RegistrationRule,
Admission,
HandleTraits,
HandleContracts,
PartTraits,
PartContracts,
Requires,
Provides,
RuntimeChecks,
Flow,
FlowProvider,
}
impl RegistrationField {
pub const ALL: &'static [Self] = &[
Self::Module,
Self::Kind,
Self::Preset,
Self::Parts,
Self::NameZh,
Self::NameEn,
Self::SummaryZh,
Self::SummaryEn,
Self::Exports,
Self::StableName,
Self::NeedsRegistry,
Self::GettingFromOtherRegistry,
Self::RegistrationRule,
Self::Admission,
Self::HandleTraits,
Self::HandleContracts,
Self::PartTraits,
Self::PartContracts,
Self::Requires,
Self::Provides,
Self::RuntimeChecks,
Self::Flow,
Self::FlowProvider,
];
pub fn as_str(self) -> &'static str {
match self {
Self::Module => "module",
Self::Kind => "kind",
Self::Preset => "preset",
Self::Parts => "parts",
Self::NameZh => "name_zh",
Self::NameEn => "name_en",
Self::SummaryZh => "summary_zh",
Self::SummaryEn => "summary_en",
Self::Exports => "exports",
Self::StableName => "stable_name",
Self::NeedsRegistry => "needs_registry",
Self::GettingFromOtherRegistry => "getting_from_other_registry",
Self::RegistrationRule => "registration_rule",
Self::Admission => "admission",
Self::HandleTraits => "handle_traits",
Self::HandleContracts => "handle_contracts",
Self::PartTraits => "part_traits",
Self::PartContracts => "part_contracts",
Self::Requires => "requires",
Self::Provides => "provides",
Self::RuntimeChecks => "runtime_checks",
Self::Flow => "flow",
Self::FlowProvider => "flow_provider",
}
}
#[deprecated(
note = "use RegistrationField::parse_field; this alias keeps 0.2 callers compiling"
)]
pub fn parse(text: &str) -> Result<Self, String> {
Self::parse_field(text)
}
pub fn parse_field(text: &str) -> Result<Self, String> {
Self::ALL
.iter()
.copied()
.find(|field| field.as_str() == text)
.ok_or_else(|| {
format!(
"`{text}` is not a registration field; the fields are {}",
Self::ALL
.iter()
.map(|field| field.as_str())
.collect::<Vec<_>>()
.join(", ")
)
})
}
pub fn is_rust_expression(self) -> bool {
matches!(
self,
Self::Preset
| Self::Parts
| Self::GettingFromOtherRegistry
| Self::RegistrationRule
| Self::Admission
| Self::HandleTraits
| Self::HandleContracts
| Self::PartTraits
| Self::PartContracts
| Self::Requires
| Self::RuntimeChecks
| Self::Flow
| Self::FlowProvider
)
}
pub fn is_list(self) -> bool {
matches!(
self,
Self::Exports
| Self::HandleTraits
| Self::HandleContracts
| Self::PartTraits
| Self::PartContracts
| Self::Requires
| Self::Provides
| Self::RuntimeChecks
)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct RegistrationUpdate {
values: BTreeMap<RegistrationField, String>,
}
impl RegistrationUpdate {
pub fn new() -> Self {
Self::default()
}
pub fn is_empty(&self) -> bool {
self.values.is_empty()
}
#[deprecated(
note = "use RegistrationUpdate::find_field; this alias keeps 0.2 callers compiling"
)]
pub fn get(&self, field: RegistrationField) -> FieldUpdate<&str> {
self.find_field(field)
}
pub fn find_field(&self, field: RegistrationField) -> FieldUpdate<&str> {
match self.values.get(&field) {
None => FieldUpdate::Keep,
Some(value) if value.is_empty() => FieldUpdate::Clear,
Some(value) => FieldUpdate::Set(value.as_str()),
}
}
pub fn named(&self) -> impl Iterator<Item = (RegistrationField, &str)> {
self.values
.iter()
.map(|(field, value)| (*field, value.as_str()))
}
pub fn set_text(
&mut self,
field: RegistrationField,
update: FieldUpdate<&str>,
) -> Result<(), String> {
let normalized = match update {
FieldUpdate::Keep => {
self.values.remove(&field);
return Ok(());
}
FieldUpdate::Clear => String::new(),
FieldUpdate::Set(text) => normalize_field(field, text)?,
};
self.values.insert(field, normalized);
Ok(())
}
pub fn set_normalized(&mut self, field: RegistrationField, update: FieldUpdate<String>) {
match update {
FieldUpdate::Keep => {
self.values.remove(&field);
}
FieldUpdate::Clear => {
self.values.insert(field, String::new());
}
FieldUpdate::Set(value) => {
self.values.insert(field, value);
}
}
}
pub fn satisfies(&self, read_back: &Self) -> bool {
self.values.iter().all(|(field, value)| {
let theirs = read_back.find_field(*field);
match (value.is_empty(), theirs) {
(true, FieldUpdate::Clear) => true,
(false, FieldUpdate::Set(theirs)) => value == theirs,
_ => false,
}
})
}
pub fn agrees_with(&self, other: &Self) -> bool {
let fields: std::collections::BTreeSet<RegistrationField> = self
.values
.keys()
.chain(other.values.keys())
.copied()
.collect();
fields.into_iter().all(|field| {
let mine = self.find_field(field);
let theirs = other.find_field(field);
mine == theirs
})
}
}
fn normalize_field(field: RegistrationField, text: &str) -> Result<String, String> {
if text.contains(['\n', '\r']) {
return Err(format!("`{}` cannot contain a newline", field.as_str()));
}
match field {
RegistrationField::Module => {
crate::authoring::validation::validate_name(text)?;
Ok(text.to_owned())
}
RegistrationField::Kind => {
crate::authoring::validation::validate_kind_name(text)?;
Ok(text.to_owned())
}
RegistrationField::StableName => {
let valid = !text.is_empty()
&& text
.chars()
.all(|character| character == '_' || character.is_ascii_alphanumeric());
if !valid {
return Err(format!(
"`{text}` is not a stable name; use letters, digits and `_`"
));
}
Ok(text.to_owned())
}
RegistrationField::NeedsRegistry => match text {
"true" | "false" => Ok(text.to_owned()),
_ => Err("`needs_registry` must be `true` or `false`".to_owned()),
},
field if field.is_list() => {
let mut entries: Vec<&str> = text
.split(',')
.map(str::trim)
.filter(|entry| !entry.is_empty())
.collect();
entries.sort_unstable();
entries.dedup();
Ok(entries.join(","))
}
_ => Ok(text.trim().to_owned()),
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct LanguageCapabilities {
pub language: LanguageId,
pub file_extensions: &'static [&'static str],
pub operations: &'static [AuthoringOperation],
pub fields: &'static [RegistrationField],
}
impl LanguageCapabilities {
pub fn supports(&self, field: RegistrationField) -> bool {
self.fields.contains(&field)
}
pub fn supports_operation(&self, operation: AuthoringOperation) -> bool {
self.operations.contains(&operation)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FaceAuthoringRequest {
pub language: LanguageId,
pub operation: AuthoringOperation,
pub destination: String,
pub parent: ParentReference,
pub registration: RegistrationUpdate,
pub source_context: SourceContext,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct SourceContext {
pub existing_source: Option<String>,
pub module_path: Option<String>,
pub namespace: Option<String>,
}
impl SourceContext {
pub fn new() -> Self {
Self::default()
}
pub fn source_text(&self) -> Option<&str> {
self.existing_source.as_deref()
}
pub fn with_existing_source(mut self, source: impl Into<String>) -> Self {
self.existing_source = Some(source.into());
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlannedEdit {
pub start: usize,
pub end: usize,
pub replacement: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlannedFile {
pub path: String,
pub original: Option<String>,
pub updated: String,
pub edits: Vec<PlannedEdit>,
pub remove: bool,
}
impl PlannedFile {
pub fn creates(&self) -> bool {
self.original.is_none()
}
pub fn changes(&self) -> bool {
self.remove || self.original.as_deref() != Some(self.updated.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DiagnosticSeverity {
Note,
Warning,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PlanDiagnostic {
pub severity: DiagnosticSeverity,
pub message: String,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ObligationKind {
RoundTrip,
Build,
Registration,
Call,
Identity,
}
impl ObligationKind {
pub fn as_str(self) -> &'static str {
match self {
Self::RoundTrip => "round-trip",
Self::Build => "build",
Self::Registration => "registration",
Self::Call => "call",
Self::Identity => "identity",
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ValidationObligation {
pub kind: ObligationKind,
pub detail: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FaceAuthoringPlan {
pub language: LanguageId,
pub operation: AuthoringOperation,
pub files: Vec<PlannedFile>,
pub diagnostics: Vec<PlanDiagnostic>,
pub obligations: Vec<ValidationObligation>,
}
impl FaceAuthoringPlan {
pub fn changed_files(&self) -> impl Iterator<Item = &PlannedFile> {
self.files.iter().filter(|file| file.changes())
}
pub fn writes_nothing(&self) -> bool {
self.changed_files().next().is_none()
}
}
pub fn validate_request(
request: &FaceAuthoringRequest,
capabilities: &LanguageCapabilities,
) -> Result<(), String> {
if capabilities.language != request.language {
return Err(format!(
"the capability table describes `{}` but the request targets `{}`",
capabilities.language.as_str(),
request.language.as_str()
));
}
if !capabilities.supports_operation(request.operation) {
return Err(format!(
"`{}` does not implement `{}`; this build has no adapter for that operation",
request.language.as_str(),
request.operation.as_str()
));
}
for (field, _) in request.registration.named() {
if !capabilities.supports(field) {
let reason = if field.is_rust_expression() {
"its value is a Rust expression, which this language cannot consume"
} else {
"this language's registration record does not carry it"
};
return Err(format!(
"`{}` cannot carry `{}`: {reason}; drop the field or use a language that supports it",
request.language.as_str(),
field.as_str()
));
}
}
Ok(())
}
#[cfg(test)]
#[path = "request_tests.rs"]
mod request_tests;