use std::any::TypeId;
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;
use tilo_actions::{ActionArgs, ActionParam, ActionSpec, ActionType, ExecutionLocus, Target};
use crate::collection::Id;
use crate::resource::Resource;
use crate::vocabulary::{Declaration, Vocabulary, vocabulary};
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemText {
pub field: &'static str,
pub id: Id,
pub label: String,
pub text: String,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItemCollection {
pub field: &'static str,
pub labelled: bool,
pub items: Vec<(Id, String)>,
pub within: Vec<(&'static str, Id)>,
}
pub trait ItemSource {
fn item_collection(&self, field: &'static str) -> ItemCollection;
fn item_presence(&self) -> usize;
fn label_of_item(&self, id: &Id) -> Option<String>;
fn item_texts(&self, field: &'static str, found: &mut Vec<ItemText>);
fn nested_items(&self, field: &'static str, out: &mut Vec<ItemCollection>);
}
pub fn nested_resource_id<R: Resource>(within: &[(&str, Id)], field: &str, item: &Id) -> String {
nested_resource_id_in(R::KIND, within, field, item)
}
fn nested_resource_id_in(kind: &str, within: &[(&str, Id)], field: &str, item: &Id) -> String {
let mut id = kind.to_owned();
for (outer, outer_id) in within {
id.push('/');
id.push_str(outer);
id.push('/');
id.push_str(outer_id.as_str());
}
format!("{id}/{field}/{item}")
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ItemAction {
pub action: &'static str,
pub param: &'static str,
pub collection: Option<&'static str>,
pub within: &'static [&'static str],
pub within_params: &'static [&'static str],
}
pub fn item_resource_id<R: Resource>(field: &str, item: &Id) -> String {
item_resource_id_in(R::KIND, field, item)
}
pub fn item_resource_id_in(kind: &str, field: &str, item: &Id) -> String {
format!("{kind}/{field}/{item}")
}
pub use tilo_actions::item_kind;
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Ref(String);
impl Ref {
#[must_use]
pub fn new(text: impl Into<String>) -> Self {
Self(text.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<Id> for Ref {
fn from(id: Id) -> Self {
Self(id.as_str().to_owned())
}
}
impl From<&Id> for Ref {
fn from(id: &Id) -> Self {
Self(id.as_str().to_owned())
}
}
impl From<String> for Ref {
fn from(text: String) -> Self {
Self(text)
}
}
impl From<&str> for Ref {
fn from(text: &str) -> Self {
Self(text.to_owned())
}
}
impl serde::Serialize for Ref {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(&self.0)
}
}
const REFERENCE_FIELDS: [&str; 2] = ["id", "label"];
impl<'de> serde::Deserialize<'de> for Ref {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
use serde::de::Error as _;
struct Reading;
impl<'de> serde::de::Visitor<'de> for Reading {
type Value = Ref;
fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("an item's id or name, or a reference to it")
}
fn visit_str<E: serde::de::Error>(self, text: &str) -> Result<Ref, E> {
Ok(Ref(text.to_owned()))
}
fn visit_map<M: serde::de::MapAccess<'de>>(self, mut map: M) -> Result<Ref, M::Error> {
let mut named: Option<String> = None;
while let Some(key) = map.next_key::<String>()? {
let value = map.next_value::<Option<String>>()?;
if named.is_none()
&& REFERENCE_FIELDS.contains(&key.as_str())
&& let Some(value) = value.filter(|value| !value.trim().is_empty())
{
named = Some(value);
}
}
named.map(Ref).ok_or_else(|| {
M::Error::custom("a reference names its item by `id` or by `label`")
})
}
}
deserializer.deserialize_any(Reading)
}
}
impl crate::JsonSchema for Ref {
fn json_schema() -> serde_json::Value {
serde_json::json!({"type": "string", "minLength": 1})
}
fn field_type(_: &mut crate::TypeSet) -> crate::FieldType {
crate::FieldType::Text
}
}
pub fn item_of_resource<R: Resource>(resource_id: &str) -> Option<(&str, Id)> {
item_of_resource_in(R::KIND, resource_id)
}
#[must_use]
pub fn item_of_resource_in<'a>(kind: &str, resource_id: &'a str) -> Option<(&'a str, Id)> {
let rest = resource_id.strip_prefix(kind)?.strip_prefix('/')?;
let (field, item) = rest.split_once('/')?;
Some((field, Id::from_raw(item)))
}
fn targets(action: &ItemAction, fields: &[&str], field: &str) -> bool {
if !action.within.is_empty() {
return false;
}
if let Some(named) = action.collection {
return named == field;
}
if fields.contains(&action.param) {
action.param == field
} else {
fields.len() == 1
}
}
pub const ITEM_PAGE: usize = 256;
type Cached = HashMap<Id, (String, u64, tilo_actions::ResourceSpec)>;
thread_local! {
static BUILT: RefCell<HashMap<(TypeId, String), Cached>> = RefCell::new(HashMap::new());
}
fn item_resource(
vocabulary: &'static Vocabulary,
scoped: &[(&ItemAction, &Declaration)],
field: &str,
id: &Id,
label: &str,
) -> tilo_actions::ResourceSpec {
cached_item((vocabulary.type_id)(), field, id, label, &|| {
build_item(vocabulary, scoped, field, id, label)
})
}
fn cached_item(
kind: TypeId,
field: &str,
id: &Id,
label: &str,
build: &dyn Fn() -> tilo_actions::ResourceSpec,
) -> tilo_actions::ResourceSpec {
let epoch = crate::resource::words_epoch();
let key = (kind, field.to_owned());
let cached = BUILT.with(|built| {
built
.borrow()
.get(&key)
.and_then(|items| items.get(id))
.filter(|(cached_label, cached_epoch, _)| {
cached_label == label && *cached_epoch == epoch
})
.map(|(_, _, resource)| resource.clone())
});
if let Some(resource) = cached {
debug_assert_eq!(
fingerprint(&resource),
fingerprint(&build()),
"a cached item resource differs from a fresh one"
);
return resource;
}
let resource = build();
BUILT.with(|built| {
built
.borrow_mut()
.entry(key)
.or_default()
.insert(id.clone(), (label.to_owned(), epoch, resource.clone()));
});
resource
}
fn build_item(
vocabulary: &'static Vocabulary,
scoped: &[(&ItemAction, &Declaration)],
field: &str,
id: &Id,
label: &str,
) -> tilo_actions::ResourceSpec {
let mut child = tilo_actions::ResourceSpec::new(
item_resource_id_in(vocabulary.kind, field, id),
format!("{}.{field}", vocabulary.kind),
label,
);
child = child.with_type(crate::words::item_words(vocabulary.kind, field));
for (action, decl) in scoped {
child = child.with_action(item_spec(decl, action.param, id));
}
for spec in (vocabulary.item_effects)(field, id) {
child = child.with_action(spec);
}
for view in (vocabulary.item_views)(field, id) {
child = child.with_view(view);
}
crate::share::offer(&mut child);
if let Some(rename) = rename_spec(vocabulary, field, id)
&& !child.actions.iter().any(|action| action.id == rename.id)
{
child = child.with_action(rename);
}
if let Some(spec) = crate::resource::item_field_edit_spec_of(vocabulary, field, id) {
child = child.with_action(spec);
}
if let Some((key, item)) = item_shape(vocabulary, field) {
let parent = item_resource_id_in(vocabulary.kind, field, id);
let path = [
crate::Segment::Field(key.to_owned()),
crate::Segment::Item(id.clone()),
];
child = child.with_children(crate::child::nested_children(
vocabulary,
item,
&parent,
&path,
Some(label),
));
}
child
}
fn item_shape(
vocabulary: &'static Vocabulary,
field: &str,
) -> Option<(&'static str, crate::shape::Shape)> {
use crate::shape::Shape;
let collection = (vocabulary.shape)()?
.fields()
.iter()
.find(|candidate| candidate.name == field)?;
match collection.shape {
Shape::Collection(item) | Shape::Keyed(item) => Some((collection.key, *item)),
_ => None,
}
}
pub const RENAME: &str = "rename";
fn rename_spec(vocabulary: &'static Vocabulary, field: &str, id: &Id) -> Option<ActionSpec> {
thread_local! {
static KEPT: RefCell<crate::kept::KeptByPath> = RefCell::default();
}
if !vocabulary.edits {
return None;
}
let key = ((vocabulary.type_id)(), field.to_owned());
crate::kept::kept_type(&KEPT, key, || rename_type(vocabulary, field))
.map(|ty| ty.bind(Target::new(id.clone())))
}
fn rename_type(vocabulary: &'static Vocabulary, field: &str) -> Option<Arc<ActionType>> {
use crate::path::{EditOp, Segment};
use crate::shape::Shape;
let collection = (vocabulary.shape)()?
.fields()
.iter()
.find(|candidate| candidate.name == field)?;
let (Shape::Collection(item) | Shape::Keyed(item)) = collection.shape else {
return None;
};
let label = item.fields().iter().find(|candidate| candidate.label)?;
let plain_text = label.ty.ends_with("String") || label.ty.ends_with("Atom");
if collection.readonly || label.readonly || !plain_text {
return None;
}
let (collection_key, label_key) = (collection.key, label.key);
let param = label.name;
let decl = Declaration::new(
vocabulary,
RENAME,
"Rename".to_owned(),
vec![ActionParam::required_owned(
param,
tilo_actions::ParamType::Text,
label.title,
)],
Arc::new(|_, _| Err("bound to no item".to_owned())),
);
let spec = crate::resource::spec_of_declaration_on(&decl, move |target, args, now_ms| {
let Some(tilo_actions::ArgValue::Text(name)) = args.get(param) else {
return Err(format!("missing `{param}`"));
};
let Some(id) = target.get::<Id>() else {
return Err("bound to no item".to_owned());
};
let path = vec![
Segment::Field(collection_key.to_owned()),
Segment::Item(id.clone()),
Segment::Field(label_key.to_owned()),
];
let edit = crate::Edit::<()>::new(
path,
EditOp::Set {
value: serde_json::Value::String(name.clone()),
},
);
crate::resource::stamped_edit(vocabulary, edit, now_ms)
});
Some(Arc::clone(spec.action_type()))
}
#[must_use]
pub fn fingerprint(resource: &tilo_actions::ResourceSpec) -> String {
use std::fmt::Write as _;
let mut out = format!(
"{}|{}|{}",
resource.id.as_str(),
resource.kind,
resource.label
);
for spec in &resource.actions {
let _ = write!(
out,
"|{}:{}:{:?}:{}",
spec.id, spec.label, spec.kind, spec.contract.kind
);
for param in spec.params() {
let _ = write!(out, ",{}:{:?}:{}", param.name, param.ty, param.required);
}
}
for child in &resource.children {
let _ = write!(out, "[{}]", fingerprint(child));
}
out
}
pub fn item_child<R: Resource>(
resource_id: &str,
fields: &[&str],
actions: &[ItemAction],
label_of: impl Fn(&str, &Id) -> Option<String>,
) -> Option<tilo_actions::ResourceSpec> {
let vocabulary = vocabulary::<R>();
let (field, id) = item_of_resource_in(vocabulary.kind, resource_id)?;
let field = *fields.iter().find(|candidate| **candidate == field)?;
if let Some(label) = label_of(field, &id) {
return Some(scoped_item(vocabulary, fields, actions, field, &id, &label));
}
let (item, _) = id.as_str().split_once('/')?;
let item = Id::from_raw(item);
let label = label_of(field, &item)?;
let resource = scoped_item(vocabulary, fields, actions, field, &item, &label);
descendant(resource, resource_id)
}
fn descendant(
resource: tilo_actions::ResourceSpec,
id: &str,
) -> Option<tilo_actions::ResourceSpec> {
resource.children.into_iter().find_map(|child| {
if child.id.as_str() == id {
Some(child)
} else {
descendant(child, id)
}
})
}
fn scoped_item(
vocabulary: &'static Vocabulary,
fields: &[&str],
actions: &[ItemAction],
field: &str,
id: &Id,
label: &str,
) -> tilo_actions::ResourceSpec {
let declarations = vocabulary.declarations();
let scoped = scoped(&declarations, actions, fields, field);
item_resource(vocabulary, &scoped, field, id, label)
}
fn scoped<'d, 'a>(
declarations: &'d [Declaration],
actions: &'a [ItemAction],
fields: &[&str],
field: &str,
) -> Vec<(&'a ItemAction, &'d Declaration)> {
let mut out = Vec::new();
for action in actions {
if !targets(action, fields, field) {
continue;
}
for decl in declarations {
if decl.id == action.action {
out.push((action, decl));
break;
}
}
}
out
}
#[doc(hidden)]
#[must_use]
pub fn item_field(
collections: &'static [&'static str],
param: &str,
named: &str,
) -> Option<&'static str> {
if !named.is_empty() {
return collections.iter().copied().find(|field| *field == named);
}
collections
.iter()
.copied()
.find(|field| *field == param)
.or(match collections {
[only] => Some(*only),
_ => None,
})
}
#[doc(hidden)]
#[must_use]
pub const fn item_target(collections: &[&str], param: &str, named: &str) -> bool {
if !named.is_empty() {
return contains(collections, named);
}
contains(collections, param) || collections.len() == 1
}
#[doc(hidden)]
#[must_use]
pub fn target_field<'a>(collections: &[&'a str], param: &str, named: &str) -> Option<&'a str> {
if !named.is_empty() {
return collections.iter().copied().find(|field| *field == named);
}
if let Some(field) = collections.iter().copied().find(|field| *field == param) {
return Some(field);
}
match collections {
[only] if one_of(only, param) => Some(only),
_ => None,
}
}
fn one_of(field: &str, param: &str) -> bool {
tilo_actions::singular(&tilo_actions::in_words(field)) == tilo_actions::in_words(param)
}
#[doc(hidden)]
#[must_use]
pub const fn entry_target(outboxes: &[&str], named: &str) -> bool {
!named.is_empty() && contains(outboxes, named)
}
#[allow(
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
reason = "a const fn walks the slices by index, bounded by their lengths"
)]
const fn contains(names: &[&str], name: &str) -> bool {
let mut index = 0;
while index < names.len() {
if same(names[index].as_bytes(), name.as_bytes()) {
return true;
}
index += 1;
}
false
}
#[allow(
clippy::indexing_slicing,
clippy::arithmetic_side_effects,
reason = "a const fn walks the slices by index, bounded by their lengths"
)]
const fn same(a: &[u8], b: &[u8]) -> bool {
if a.len() != b.len() {
return false;
}
let mut index = 0;
while index < a.len() {
if a[index] != b[index] {
return false;
}
index += 1;
}
true
}
pub fn item_children<R: Resource>(
collections: &[ItemCollection],
actions: &[ItemAction],
) -> Vec<tilo_actions::ResourceSpec> {
let mut children = Vec::new();
for_each_item_child_of(
vocabulary::<R>(),
collections,
actions,
&mut |_, _, _, build| {
children.push(build());
},
);
children
}
pub type ItemChildVisitor<'a> =
dyn FnMut(&ItemCollection, &Id, &str, &dyn Fn() -> tilo_actions::ResourceSpec) + 'a;
pub fn for_each_item_child<R: Resource>(
collections: &[ItemCollection],
actions: &[ItemAction],
each: &mut ItemChildVisitor<'_>,
) {
for_each_item_child_of(vocabulary::<R>(), collections, actions, each);
}
fn for_each_item_child_of(
vocabulary: &'static Vocabulary,
collections: &[ItemCollection],
actions: &[ItemAction],
each: &mut ItemChildVisitor<'_>,
) {
let declarations = vocabulary.declarations();
let fields = own_fields(collections);
for collection in collections {
if !collection.within.is_empty() {
let outer = outer_fields(collection);
let mut verbs: Vec<(&ItemAction, &Declaration)> = Vec::new();
for action in actions {
if action.collection != Some(collection.field) || action.within != outer.as_slice()
{
continue;
}
for decl in declarations.iter() {
if decl.id == action.action {
verbs.push((action, decl));
break;
}
}
}
if collection.labelled || !verbs.is_empty() {
for (id, label) in &collection.items {
each(collection, id, label, &|| {
let mut child = nested_item(
vocabulary,
&collection.within,
collection.field,
id,
label,
);
for (action, decl) in &verbs {
let values = nested_values(action, &collection.within, id);
child = child.with_action(bound(decl, &values));
}
child
});
}
}
continue;
}
let scoped = scoped(&declarations, actions, &fields, collection.field);
let offers_effects = match collection.items.first() {
Some((id, _)) => !(vocabulary.item_effects)(collection.field, id).is_empty(),
None => false,
};
if scoped.is_empty() && !offers_effects && !collection.labelled {
continue;
}
for (id, label) in &collection.items {
each(collection, id, label, &|| {
item_resource(vocabulary, &scoped, collection.field, id, label)
});
}
forget_gone((vocabulary.type_id)(), collection);
}
}
pub fn item_child_id<R: Resource>(collection: &ItemCollection, id: &Id) -> String {
if collection.within.is_empty() {
item_resource_id_in(R::KIND, collection.field, id)
} else {
nested_resource_id_in(R::KIND, &collection.within, collection.field, id)
}
}
pub struct ChildrenParts {
pub others: Vec<tilo_actions::ResourceSpec>,
pub kept: Rc<[Rc<tilo_actions::ResourceSpec>]>,
pub items: Vec<ItemCollection>,
pub item_actions: Vec<ItemAction>,
}
fn own_fields(collections: &[ItemCollection]) -> Vec<&'static str> {
collections
.iter()
.filter(|collection| collection.within.is_empty())
.map(|collection| collection.field)
.collect()
}
fn outer_fields(collection: &ItemCollection) -> Vec<&'static str> {
collection.within.iter().map(|(field, _)| *field).collect()
}
fn nested_values(
action: &ItemAction,
within: &[(&'static str, Id)],
id: &Id,
) -> Vec<(String, serde_json::Value)> {
let mut values: Vec<(String, serde_json::Value)> = action
.within_params
.iter()
.zip(within)
.map(|(param, (_, outer_id))| ((*param).to_owned(), outer_id.as_str().into()))
.collect();
values.push((action.param.to_owned(), id.as_str().into()));
values
}
fn forget_gone(kind: TypeId, collection: &ItemCollection) {
BUILT.with(|built| {
if let Some(items) = built
.borrow_mut()
.get_mut(&(kind, collection.field.to_owned()))
&& items.len() > collection.items.len().saturating_mul(2).max(ITEM_PAGE)
{
let present: std::collections::HashSet<&Id> =
collection.items.iter().map(|(id, _)| id).collect();
items.retain(|id, _| present.contains(id));
}
});
}
fn nested_item(
vocabulary: &'static Vocabulary,
within: &[(&'static str, Id)],
field: &'static str,
id: &Id,
label: &str,
) -> tilo_actions::ResourceSpec {
let mut child = tilo_actions::ResourceSpec::new(
nested_resource_id_in(vocabulary.kind, within, field, id),
format!("{}.{field}", vocabulary.kind),
label,
);
let mut path: Vec<crate::Segment> = Vec::new();
for (outer, outer_id) in within {
path.push(crate::Segment::Field((*outer).to_owned()));
path.push(crate::Segment::Item(outer_id.clone()));
}
path.push(crate::Segment::Field(field.to_owned()));
path.push(crate::Segment::Item(id.clone()));
if let Some(spec) = crate::resource::field_edit_spec_at_of(vocabulary, path) {
child = child.with_action(spec);
}
child
}
pub fn offered_on_items<R: Resource>(
others: &[tilo_actions::ResourceSpec],
derived: &crate::derived::PublishedDerived,
sizes: &[(&'static str, usize)],
actions: &[ItemAction],
nested: &dyn Fn(&ItemAction) -> bool,
) -> Vec<&'static str> {
let declarations = vocabulary::<R>().declarations();
let mut declared: Vec<(&'static str, Vec<&str>)> = Vec::with_capacity(declarations.len());
for decl in declarations.iter() {
let mut names = Vec::with_capacity(decl.params.len());
for param in &decl.params {
names.push(param.name.as_ref());
}
declared.push((decl.id, names));
}
offered_on_items_of(others, derived, sizes, actions, &declared, nested)
}
fn offered_on_items_of(
others: &[tilo_actions::ResourceSpec],
derived: &crate::derived::PublishedDerived,
sizes: &[(&'static str, usize)],
actions: &[ItemAction],
declared: &[(&'static str, Vec<&str>)],
nested: &dyn Fn(&ItemAction) -> bool,
) -> Vec<&'static str> {
let fields: Vec<&str> = sizes.iter().map(|(field, _)| *field).collect();
let first = |id: &str| declared.iter().find(|(declared, _)| *declared == id);
let mut offered = Vec::new();
for (id, params) in declared {
let on_items = actions.iter().any(|action| {
if action.action != *id {
return false;
}
let Some((_, bound)) = first(action.action) else {
return false;
};
if action.within.is_empty() {
let kept = bound.iter().filter(|name| **name != action.param).count();
kept < params.len()
&& sizes
.iter()
.any(|&(field, size)| size > 0 && targets(action, &fields, field))
} else {
let kept = bound
.iter()
.filter(|name| **name != action.param && !action.within_params.contains(name))
.count();
kept < params.len() && nested(action)
}
});
if on_items
|| offered_bound_as(others, id, params.len())
|| derived.offers_bound(id, params.len())
{
offered.push(*id);
}
}
offered
}
fn item_spec(decl: &Declaration, param: &'static str, item: &Id) -> ActionSpec {
bound(
decl,
&[(
param.to_owned(),
serde_json::Value::String(item.as_str().to_owned()),
)],
)
}
pub fn bound<N: AsRef<str>>(decl: &Declaration, values: &[(N, serde_json::Value)]) -> ActionSpec {
let mut owned: Vec<(String, serde_json::Value)> = Vec::with_capacity(values.len());
for (name, value) in values {
owned.push((name.as_ref().to_owned(), value.clone()));
}
bound_to(decl, owned)
}
fn bound_to(decl: &Declaration, values: Vec<(String, serde_json::Value)>) -> ActionSpec {
thread_local! {
static KEPT: std::cell::RefCell<crate::kept::KeptTypes<BoundKey>> =
std::cell::RefCell::default();
}
let names: Vec<String> = values.iter().map(|(name, _)| name.clone()).collect();
let key = (decl.resource, decl.id, decl.refines, names);
crate::kept::kept_type(&KEPT, key, || bound_type(decl, &values))
.bind(Target::new(values.clone()))
.with_bound(values)
}
type BoundKey = (&'static str, &'static str, bool, Vec<String>);
type BoundValues = Vec<(String, serde_json::Value)>;
fn bound_type(decl: &Declaration, values: &[(String, serde_json::Value)]) -> Arc<ActionType> {
let params = unbound_params(&decl.params, values);
let all = decl.params.clone();
let build = Arc::clone(&decl.build);
let label = decl.shown_label();
let spec = ActionSpec::typed_on(
decl.id,
label.clone(),
label,
ExecutionLocus::ClientLocal,
params,
move |target, args| {
let mut arguments = args.to_json();
for (name, value) in target.get::<BoundValues>().into_iter().flatten() {
if !value.is_null() {
arguments.insert(name.clone(), value.clone());
}
}
let action = match ActionArgs::bind_json(&all, &arguments) {
Ok(args) => {
crate::content::invoking(|| build(&args, crate::resource::origin_now_ms()))
}
Err(error) => Err(error.to_string()),
};
crate::resource::encode_built(action)
},
)
.of_kind(decl.kind);
let spec = finish_bound(spec, decl);
Arc::clone(spec.action_type())
}
fn unbound_params(
params: &[ActionParam],
values: &[(String, serde_json::Value)],
) -> Vec<ActionParam> {
params
.iter()
.filter(|candidate| !values.iter().any(|(name, _)| candidate.name == *name))
.cloned()
.collect()
}
fn finish_bound(mut spec: ActionSpec, decl: &Declaration) -> ActionSpec {
if let Some(field) = decl.field {
spec = spec.below_field(field);
}
if let Some(description) = &decl.description {
spec = spec.with_description(description.clone());
}
spec = crate::resource::with_declared_words(spec, decl);
for tag in &decl.tags {
if !spec.contract.tags.contains(tag) {
spec.type_mut().contract.tags.push(tag.clone());
}
}
if decl.destructive {
spec = spec.destructive();
}
let contract = &mut spec.type_mut().contract;
(contract.step, contract.creates) = (decl.step, decl.creates.map(str::to_owned));
if let Some(result) = &decl.result {
spec.type_mut().contract.result = result.clone();
}
spec
}
#[must_use]
pub fn offered_bound(children: &[tilo_actions::ResourceSpec], decl: &Declaration) -> bool {
offered_bound_as(children, decl.id, decl.params.len())
}
fn offered_bound_as(children: &[tilo_actions::ResourceSpec], id: &str, params: usize) -> bool {
children.iter().any(|child| {
child
.actions
.iter()
.any(|spec| spec.id == id && spec.params().len() < params)
|| offered_bound_as(&child.children, id, params)
})
}
#[cfg(test)]
mod item_kind_tests {
#[test]
fn an_items_kind_is_read_from_its_id() {
let id = super::item_resource_id_in("notes.notebook", "pages", &super::Id::from_raw("p1"));
assert_eq!(
super::item_kind(&id).as_deref(),
Some("notes.notebook.pages")
);
assert_eq!(
super::item_kind("notes.notebook"),
None,
"the record itself"
);
assert_eq!(
super::item_kind("deck/slides/s1/elements/e1"),
None,
"a nested item"
);
}
}
#[cfg(test)]
mod target_field_tests {
use super::target_field;
#[test]
fn a_parameter_names_an_item_only_of_the_collection_it_is_named_after() {
assert_eq!(
target_field(&["cards", "archive"], "card", "archive"),
Some("archive")
);
assert_eq!(target_field(&["cards"], "card", "pages"), None);
assert_eq!(
target_field(&["cards", "archive"], "archive", ""),
Some("archive")
);
assert_eq!(target_field(&["issues"], "issue", ""), Some("issues"));
assert_eq!(
target_field(&["shell_parts"], "shell-part", ""),
Some("shell_parts")
);
assert_eq!(target_field(&["messages"], "channel", ""), None);
assert_eq!(target_field(&["cards", "archive"], "place", ""), None);
}
}