repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/cli/src/output/cli_output_target.rs
crate/cli/src/output/cli_output_target.rs
#[cfg(feature = "output_in_memory")] use peace_rt_model_core::indicatif::InMemoryTerm; /// Where to output progress updates to -- stdout or stderr. /// /// This defaults to `stderr`. /// /// # Implementation Note /// /// `PartialEq` and `Eq` are implemented manually. For `InMemory`, equality is /// defined by the [`contents`] of the in-memory terminal. /// /// [`contents`]: https://docs.rs/indicatif/latest/indicatif/struct.InMemoryTerm.html#method.contents #[derive(Clone, Debug, Default)] pub enum CliOutputTarget { /// Standard error -- file descriptor 1. Stdout, /// Standard error -- file descriptor 2. #[default] Stderr, /// Render to an in-memory buffer. /// /// This variant can be constructed using the `in_memory` function: /// /// ```rust /// # #[cfg(feature = "output_in_memory")] /// # fn main() { /// use peace_rt_model_native::CliOutputTarget; /// /// let progress_target = CliOutputTarget::in_memory(50, 120); /// # } /// # /// # #[cfg(not(feature = "output_in_memory"))] /// # fn main() {} /// ``` #[cfg(feature = "output_in_memory")] InMemory(InMemoryTerm), } impl PartialEq for CliOutputTarget { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::Stdout, Self::Stdout) | (Self::Stderr, Self::Stderr) => true, #[cfg(feature = "output_in_memory")] (Self::InMemory(term_self), Self::InMemory(term_other)) => { term_self.contents() == term_other.contents() } _ => false, } } } impl Eq for CliOutputTarget {} impl CliOutputTarget { /// Returns `CliOutputTarget::InMemory` with an empty buffer. /// /// # Parameters /// /// * `row_count`: Number of rows (lines) of the in-memory terminal. /// * `col_count`: Number of columns (characters) of the in-memory terminal. #[cfg(feature = "output_in_memory")] pub fn in_memory(row_count: u16, col_count: u16) -> Self { Self::InMemory(InMemoryTerm::new(row_count, col_count)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/accessors.rs
crate/data/src/accessors.rs
//! Accessors to fetch data from `Resources`. //! //! * `R<'_, T>`: Immutable access to a `T` resource. //! * `W<'_, T>`: Mutable access to a `T` resource. //! * `RMaybe<'_, T>`: Immutable access to a `T` resource, if it has been //! inserted. //! * `WMaybe<'_, T>`: Mutable access to a `T` resource, if it has been //! inserted. //! * `ROpt<'_, T>`: Immutable access to an `Option<T>` resource. //! * `WOpt<'_, T>`: Mutable access to an `Option<T>` resource. //! //! Notably if you want to insert a resource during item execution, you //! should use `WOpt` instead of `WMaybe`, and correspondingly read it using //! `ROpt`. pub use self::{r_maybe::RMaybe, r_opt::ROpt, w_maybe::WMaybe, w_opt::WOpt}; pub use fn_graph::{R, W}; mod r_maybe; mod r_opt; mod w_maybe; mod w_opt;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/lib.rs
crate/data/src/lib.rs
//! Data model for the peace automation framework. // Re-exports pub use fn_graph::{self, resman, DataAccess, DataAccessDyn, Resources, TypeIds}; pub use peace_data_derive::Data; pub use crate::data::Data; pub mod accessors; pub mod marker; mod data;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/data.rs
crate/data/src/data.rs
use std::fmt::Debug; use fn_graph::{DataAccess, DataAccessDyn, DataBorrow, Resources, R, W}; use peace_item_model::ItemId; /// Defines the logic to instantiate and retrieve runtime data. /// /// # Note for API Consumers /// /// This trait is implemented by using the [`Data` derive]. /// /// [`Data` derive]: peace_data_derive::Data pub trait Data<'borrow>: DataAccess + DataAccessDyn + Send { /// Borrows each of `Self`'s fields from the provided [`Resources`]. /// /// This takes in the `item_id`, so that the type that implements this /// trait may further filter specific data within the borrowed data, scope /// to the item. /// /// # Parameters /// /// * `item_id`: ID of the item this borrow is used for. /// * `resources`: `Any` map to borrow the data from. fn borrow(item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self; } impl<'borrow> Data<'borrow> for () { fn borrow(_item_id: &'borrow ItemId, _resources: &'borrow Resources) -> Self {} } impl<'borrow> Data<'borrow> for &'borrow () { fn borrow(_item_id: &'borrow ItemId, _resources: &'borrow Resources) -> Self { &() } } impl<'borrow, T> Data<'borrow> for R<'borrow, T> where T: Debug + Send + Sync + 'static, { fn borrow(_item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self { <Self as DataBorrow>::borrow(resources) } } impl<'borrow, T> Data<'borrow> for W<'borrow, T> where T: Debug + Send + Sync + 'static, { fn borrow(_item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self { <Self as DataBorrow>::borrow(resources) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker.rs
crate/data/src/marker.rs
//! Markers for `State`s inserted into `Resources`. //! //! For `SingleProfileSingleFlow` commands, `Current<Item::State>(None)` and //! `Goal<Item::State>(None)` are inserted into `Resources` when the //! command context is built, and automatically mutated to `Some` when either //! `Item::state_current` or `Item::state_goal` is executed. // Corresponds to variants in `crate/params/src/value_resolution_mode.rs`. // Remember to update there when updating here. pub use self::{apply_dry::ApplyDry, clean::Clean, current::Current, goal::Goal}; #[cfg(feature = "item_state_example")] pub use self::example::Example; mod apply_dry; mod clean; mod current; mod goal; #[cfg(feature = "item_state_example")] mod example;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/accessors/w_maybe.rs
crate/data/src/accessors/w_maybe.rs
use std::{any::TypeId, fmt::Debug}; use fn_graph::{ resman::{BorrowFail, RefMut}, DataAccess, DataAccessDyn, Resources, TypeIds, }; use peace_item_model::ItemId; use crate::Data; /// A mutable resource that may or may not exist. /// /// For an immutable version of this, see [`RMaybe`]. /// /// [`RMaybe`]: crate::RMaybe #[derive(Debug, PartialEq)] pub struct WMaybe<'borrow, T>(Option<RefMut<'borrow, T>>) where T: Debug + Send + Sync + 'static; impl<'borrow, T> From<Option<RefMut<'borrow, T>>> for WMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { fn from(opt: Option<RefMut<'borrow, T>>) -> Self { Self(opt) } } impl<'borrow, T> std::ops::Deref for WMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { type Target = Option<RefMut<'borrow, T>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for WMaybe<'_, T> where T: Debug + Send + Sync + 'static, { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<'borrow, T> Data<'borrow> for WMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { fn borrow(_item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self { resources .try_borrow_mut::<T>() .map_err(|borrow_fail| match borrow_fail { e @ BorrowFail::ValueNotFound => e, BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => { panic!("Encountered {borrow_fail:?}") } }) .ok() .into() } } impl<T> DataAccess for WMaybe<'_, T> where T: Debug + Send + Sync + 'static, { fn borrows() -> TypeIds where Self: Sized, { TypeIds::new() } fn borrow_muts() -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<T>()); type_ids } } impl<T> DataAccessDyn for WMaybe<'_, T> where T: Debug + Send + Sync + 'static, { fn borrows(&self) -> TypeIds where Self: Sized, { TypeIds::new() } fn borrow_muts(&self) -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<T>()); type_ids } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/accessors/w_opt.rs
crate/data/src/accessors/w_opt.rs
use crate::fn_graph::W; /// Type alias for `W<'_, Option<T>>`. pub type WOpt<'borrow, T> = W<'borrow, Option<T>>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/accessors/r_maybe.rs
crate/data/src/accessors/r_maybe.rs
use std::{any::TypeId, fmt::Debug}; use fn_graph::{ resman::{BorrowFail, Ref}, DataAccess, DataAccessDyn, Resources, TypeIds, }; use peace_item_model::ItemId; use crate::Data; /// A resource that may or may not exist. /// /// For a mutable version of this, see [`WMaybe`]. /// /// [`WMaybe`]: crate::WMaybe #[derive(Clone, Debug, PartialEq)] pub struct RMaybe<'borrow, T>(Option<Ref<'borrow, T>>) where T: Debug + Send + Sync + 'static; impl<'borrow, T> From<Option<Ref<'borrow, T>>> for RMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { fn from(opt: Option<Ref<'borrow, T>>) -> Self { Self(opt) } } impl<'borrow, T> std::ops::Deref for RMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { type Target = Option<Ref<'borrow, T>>; fn deref(&self) -> &Self::Target { &self.0 } } impl<'borrow, T> Data<'borrow> for RMaybe<'borrow, T> where T: Debug + Send + Sync + 'static, { fn borrow(_item_id: &'borrow ItemId, resources: &'borrow Resources) -> Self { resources .try_borrow::<T>() .map_err(|borrow_fail| match borrow_fail { e @ BorrowFail::ValueNotFound => e, BorrowFail::BorrowConflictImm | BorrowFail::BorrowConflictMut => { panic!("Encountered {borrow_fail:?}") } }) .ok() .into() } } impl<T> DataAccess for RMaybe<'_, T> where T: Debug + Send + Sync + 'static, { fn borrows() -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<T>()); type_ids } fn borrow_muts() -> TypeIds where Self: Sized, { TypeIds::new() } } impl<T> DataAccessDyn for RMaybe<'_, T> where T: Debug + Send + Sync + 'static, { fn borrows(&self) -> TypeIds where Self: Sized, { let mut type_ids = TypeIds::new(); type_ids.push(TypeId::of::<T>()); type_ids } fn borrow_muts(&self) -> TypeIds where Self: Sized, { TypeIds::new() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/accessors/r_opt.rs
crate/data/src/accessors/r_opt.rs
use crate::fn_graph::R; /// Type alias for `R<'_, Option<T>>`. pub type ROpt<'borrow, T> = R<'borrow, Option<T>>;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker/apply_dry.rs
crate/data/src/marker/apply_dry.rs
use serde::{Deserialize, Serialize}; /// Marker for apply-dry state. /// /// This is used for referential param values, where an item param value is /// dependent on the state of a predecessor's state. /// /// An `ApplyDry<Item::State>` is set to `Some` whenever an item is dry applied, /// enabling a subsequent successor's params to access that value when the /// successor's `apply_dry` function is run. /// /// Note: A successor's dry-applied state is dependent on the predecessor's /// dry-applied state, which should not affect its current stored state when /// `ApplyFns::exec_dry` is executed. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ApplyDry<T>(pub Option<T>); impl<T> std::ops::Deref for ApplyDry<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for ApplyDry<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker/goal.rs
crate/data/src/marker/goal.rs
use serde::{Deserialize, Serialize}; /// Marker for goal state. /// /// This is used for referential param values, where an item param value is /// dependent on the state of a predecessor's state. /// /// A `Goal<Item::State>` is set to `Some` whenever an item's goal state /// is discovered. enabling a subsequent successor's params to access that value /// when the successor's goal state function is run. /// /// Note: A successor's goal state is dependent on the predecessor's goal /// state, which should be in sync with its current state after /// `ApplyFns::exec` has been executed. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Goal<T>(pub Option<T>); impl<T> std::ops::Deref for Goal<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for Goal<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker/example.rs
crate/data/src/marker/example.rs
use serde::{Deserialize, Serialize}; /// Marker for example state. /// /// This is used for referential param values, where an item param value is /// dependent on the state of a predecessor's state. /// /// An `Example<Item::State>` is set to `Some` whenever an item's example state /// is discovered. This is used for rendering outcome diagrams in the following /// cases: /// /// 1. Rendering an example fully deployed state. /// 2. Rendering invisible placeholder nodes and edges, so that the layout of a /// diagram is consistent as more items are applied. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Example<T>(pub Option<T>); impl<T> std::ops::Deref for Example<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for Example<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker/clean.rs
crate/data/src/marker/clean.rs
use serde::{Deserialize, Serialize}; /// Marker for clean state. /// /// This is used for referential param values, where an item param value is /// dependent on the state of a predecessor's state. /// /// A `Clean<Item::State>` is set to `Some` whenever an item's clean state is /// needed, e.g. preparing for applying the clean state. enabling a subsequent /// successor's params to access that value when the successor's `state_clean` /// function is run. /// /// Note: A successor's clean state may be dependent on its predecessor's /// current state for state discovery. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Clean<T>(pub Option<T>); impl<T> std::ops::Deref for Clean<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for Clean<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/data/src/marker/current.rs
crate/data/src/marker/current.rs
use serde::{Deserialize, Serialize}; /// Marker for current state. /// /// This is used for referential param values, where an item param value is /// dependent on the state of a predecessor's state. /// /// A `Current<Item::State>` is set to `Some` whenever an item's current state /// is discovered. enabling a subsequent successor's params to access that value /// when the successor's **goal** state function is run. /// /// Note: A successor's goal state is dependent on the predecessor's goal /// state, which should be in sync with its current state after /// `ApplyFns::exec` has been executed. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct Current<T>(pub Option<T>); impl<T> std::ops::Deref for Current<T> { type Target = Option<T>; fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for Current<T> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/rt_model_hack/src/lib.rs
crate/rt_model_hack/src/lib.rs
//! Hack to selectively enable features in target specific crates.
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_default.rs
crate/params_derive/src/impl_default.rs
use syn::{Data, DeriveInput, Fields, Ident, ImplGenerics, Path, TypeGenerics, WhereClause}; use crate::util::fields_deconstruct_none; /// Implement `Default` for the given type. /// /// This avoids the unnecessary `Default` bound on type parameters from /// `#[derive(Default)]`. /// /// For enums, the variant annotated with `#[default]` on the original `Params` /// struct will be used. If none are annotated with `#[default]`, then the last /// variant is used as the default. /// /// This does nothing for unions. /// /// # Parameters /// /// * `ast`: The `Params` type. /// * `generics_split`: Generics of the `Params` type. /// * `type_name`: Name of the type to generate. pub fn impl_default( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), type_name: &Ident, ) -> Option<proc_macro2::TokenStream> { let (impl_generics, ty_generics, where_clause) = generics_split; match &ast.data { Data::Struct(data_struct) => { let fields = &data_struct.fields; let impl_default_body = impl_default_body(&parse_quote!(#type_name), fields); let tokens = quote! { impl #impl_generics ::std::default::Default for #type_name #ty_generics #where_clause { fn default() -> Self { #impl_default_body } } }; Some(tokens) } Data::Enum(data_enum) => { let variant_for_default = data_enum .variants .iter() .find(|variant| { variant .attrs .iter() .any(|attr| attr.path().is_ident("default")) }) .or(data_enum.variants.last()); if let Some(variant_for_default) = variant_for_default { let variant_name = &variant_for_default.ident; let fields = &variant_for_default.fields; let impl_default_body = impl_default_body(&parse_quote!(#type_name::#variant_name), fields); let tokens = quote! { impl #impl_generics ::std::default::Default for #type_name #ty_generics #where_clause { fn default() -> Self { #impl_default_body } } }; Some(tokens) } else { // Cannot implement default for an enum with no variants. None } } Data::Union(_) => None, } } fn impl_default_body(type_path: &Path, fields: &Fields) -> proc_macro2::TokenStream { let struct_fields_none = fields_deconstruct_none(fields); match fields { Fields::Named(_) => quote! { #type_path { #(#struct_fields_none),* } }, Fields::Unnamed(_) => quote! { #type_path(#(#struct_fields_none),*) }, Fields::Unit => quote!(#type_path), } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/spec_merge.rs
crate/params_derive/src/spec_merge.rs
use syn::{punctuated::Punctuated, DeriveInput, Fields, Ident, Path, Variant}; use crate::util::{ fields_deconstruct, fields_deconstruct_rename_other, fields_stmt_map, variant_match_arm, }; pub fn spec_merge( ast: &DeriveInput, params_field_wise_name: &Ident, peace_params_path: &Path, ) -> proc_macro2::TokenStream { let merge_logic = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_spec_merge(params_field_wise_name, fields, peace_params_path) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_spec_merge(params_field_wise_name, variants, peace_params_path) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_spec_merge(params_field_wise_name, &fields, peace_params_path) } }; quote! { fn merge(&mut self, other_boxed: &dyn #peace_params_path::AnySpecDataType) where Self: Sized, { let other: Option<&Self> = other_boxed.downcast_ref(); let Some(other) = other else { let self_ty_name = #peace_params_path::tynm::type_name::<Self>(); // Args need to be manually specified because Rust 1.69.0 does not allow // capturing args from scope within generated macro. // // ```ignore // to avoid ambiguity, `format_args!` cannot capture variables when the format string is expanded from a macro // ``` panic!("Failed to downcast value into `{self_ty_name}`. Value: `{other_boxed:#?}`.", self_ty_name = self_ty_name, other_boxed = other_boxed, ); }; #merge_logic } } } /// Deep merges spec fields within this struct. pub fn struct_fields_spec_merge( params_field_wise_name: &Ident, fields: &Fields, peace_params_path: &Path, ) -> proc_macro2::TokenStream { let fields_spec_merge = fields_spec_merge(fields, peace_params_path); let fields_deconstructed = fields_deconstruct(fields); let fields_deconstructed_other = fields_deconstruct_rename_other(fields); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_field_wise_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // let #params_field_wise_name { // field_1: field_1_other, // field_2: field_2_other, // marker: PhantomData, // } = other; // // AnySpecRt::merge(field_1, field_1_other); // AnySpecRt::merge(field_2, field_2_other); // ``` quote! { let #params_field_wise_name { #(#fields_deconstructed),* } = self; let #params_field_wise_name { #(#fields_deconstructed_other),* } = other; #fields_spec_merge } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(_0, _1, PhantomData,) = self; // let #params_name(_0_other, _1_other, PhantomData,) = other; // // AnySpecRt::merge(_0, _0_other); // AnySpecRt::merge(_1, _1_other); // ``` quote! { let #params_field_wise_name(#(#fields_deconstructed),*) = self; let #params_field_wise_name(#(#fields_deconstructed_other),*) = other; #fields_spec_merge } } Fields::Unit => quote!(), } } /// Deep merges spec fields within this enum. pub fn variants_spec_merge( params_field_wise_name: &Ident, variants: &Punctuated<Variant, Token![,]>, peace_params_path: &Path, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match self { // ValueSpec::Variant1 => true, // ValueSpec::Variant2(_0, _1, PhantomData) => { // AnySpecRt::merge(_0, _0_other); // AnySpecRt::merge(_1, _1_other); // } // ValueSpec::Variant3 { // field_1, // field_2, // marker: PhantomData, // } => { // AnySpecRt::merge(field_1, field_1_other); // AnySpecRt::merge(field_2, field_2_other); // } // } // ``` let variant_resolve_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let fields = &variant.fields; let fields_deconstructed = fields_deconstruct(fields); let fields_deconstructed_other = fields_deconstruct_rename_other(fields); let variant_fields_spec_merge = { let fields_spec_merge = fields_spec_merge(fields, peace_params_path); let variant_deconstruct_other_and_merge = variant_match_arm( params_field_wise_name, variant, &fields_deconstructed_other, fields_spec_merge, ); // Note: This only merges fields of the same variant. // // If we wanted to compare different variants, then we'd have to generate a // `variant_match_arm` for each of the variants. quote! { match other { #variant_deconstruct_other_and_merge // If `other` is a different variant, we don't mutate this spec. _ => {}, } } }; tokens.extend(variant_match_arm( params_field_wise_name, variant, &fields_deconstructed, variant_fields_spec_merge, )); tokens }); quote! { match self { #variant_resolve_arms } } } fn fields_spec_merge(fields: &Fields, peace_params_path: &Path) -> proc_macro2::TokenStream { fields_stmt_map(fields, move |_field, field_name, _field_index| { let field_name_other = format_ident!("{}_other", field_name); quote! { #peace_params_path::AnySpecRt::merge(#field_name, #field_name_other); } }) .fold( proc_macro2::TokenStream::new(), |mut tokens, next_tokens| { tokens.extend(next_tokens); tokens }, ) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_from_params_for_params_partial.rs
crate/params_derive/src/impl_from_params_for_params_partial.rs
use syn::{ punctuated::Punctuated, Data, DeriveInput, Fields, Ident, ImplGenerics, TypeGenerics, Variant, WhereClause, }; use crate::util::{fields_deconstruct, fields_deconstruct_some, variant_match_arm}; /// `impl From<Params> for ParamsPartial`, so that users can use /// `params_partial.try_into()` in `Item::try_state_*` without needing to /// deconstruct the `Params::Partial`. pub fn impl_from_params_for_params_partial( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), params_name: &Ident, params_partial_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let from_body = match &ast.data { Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_map_from_value(params_name, params_partial_name, fields) } Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_map_from_value(params_name, params_partial_name, variants) } Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_map_from_value(params_name, params_partial_name, &fields) } }; quote! { impl #impl_generics ::std::convert::From<#params_name #ty_generics> for #params_partial_name #ty_generics #where_clause { fn from(params: #params_name #ty_generics) -> Self { #from_body } } } } fn struct_fields_map_from_value( params_name: &Ident, params_partial_name: &Ident, fields: &Fields, ) -> proc_macro2::TokenStream { let fields_deconstructed = fields_deconstruct(fields); let fields_deconstructed_some = fields_deconstruct_some(fields); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_name { // field_1, // field_2, // marker: PhantomData, // } // // #params_partial_name { // field_1: Some(field_1), // field_2: Some(field_2), // marker: PhantomData, // } // ``` quote! { let #params_name { #(#fields_deconstructed),* } = params; #params_partial_name { #(#fields_deconstructed_some),* } } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(field_1, field_2, PhantomData,) = params; // // #params_partial_name(Some(field_1), Some(field_2), PhantomData,) // ``` quote! { let #params_name( #(#fields_deconstructed),* ) = params; #params_partial_name(#(#fields_deconstructed_some),*) } } Fields::Unit => quote!(#params_partial_name), } } fn variants_map_from_value( params_name: &Ident, params_partial_name: &Ident, variants: &Punctuated<Variant, Token![,]>, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match params { // #params_name::Variant1 => #params_partial_name::Variant1, // #params_name::Variant2(_0, _1, PhantomData) => { // #fields_to_owned // // #params_partial_name::Variant2( // Some(_0), // Some(_1), // PhantomData, // ) // } // #params_name::Variant3 { // field_1, // field_2, // marker: PhantomData, // } => { // #fields_to_owned // // #params_partial_name::Variant3 { // Some(field_1), // Some(field_2), // marker: PhantomData, // } // } // } // ``` let variant_map_from_value_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let variant_fields = fields_deconstruct(&variant.fields); let variant_fields_map_from_value = variant_fields_map_from_value( params_partial_name, &variant.ident, &variant.fields, ); tokens.extend(variant_match_arm( params_name, variant, &variant_fields, variant_fields_map_from_value, )); tokens }); quote! { match params { #variant_map_from_value_arms } } } fn variant_fields_map_from_value( params_partial_name: &Ident, variant_name: &Ident, fields: &Fields, ) -> proc_macro2::TokenStream { let fields_deconstructed_some = fields_deconstruct_some(fields); match fields { Fields::Named(_fields_named) => { quote! { #params_partial_name::#variant_name { #(#fields_deconstructed_some),* } } } Fields::Unnamed(_fields_unnamed) => { quote! { #params_partial_name::#variant_name(#(#fields_deconstructed_some),*) } } Fields::Unit => quote!(Self::#variant_name), } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/lib.rs
crate/params_derive/src/lib.rs
#![recursion_limit = "256"] extern crate proc_macro; extern crate proc_macro2; #[macro_use] extern crate quote; #[macro_use] extern crate syn; use proc_macro::TokenStream; use quote::ToTokens; use syn::{ Data, DeriveInput, GenericParam, Ident, ImplGenerics, Path, Type, TypeGenerics, WhereClause, WherePredicate, }; use crate::{ field_wise_enum_builder_ctx::FieldWiseEnumBuilderCtx, fields_map::{fields_to_optional, fields_to_value_spec}, impl_any_spec_rt_for_field_wise::impl_any_spec_rt_for_field_wise, impl_default::impl_default, impl_field_wise_builder::impl_field_wise_builder, impl_field_wise_spec_rt_for_field_wise::impl_field_wise_spec_rt_for_field_wise, impl_field_wise_spec_rt_for_field_wise_external::impl_field_wise_spec_rt_for_field_wise_external, impl_from_params_for_params_field_wise::impl_from_params_for_params_field_wise, impl_from_params_for_params_partial::impl_from_params_for_params_partial, impl_params_merge_ext_for_params::impl_params_merge_ext_for_params, impl_try_from_params_partial_for_params::impl_try_from_params_partial_for_params, impl_value_spec_rt_for_field_wise::impl_value_spec_rt_for_field_wise, type_gen::TypeGen, type_gen_external::type_gen_external, util::{is_fieldless_type, serde_bounds_for_type_params, ImplMode}, }; mod field_wise_enum_builder_ctx; mod fields_map; mod impl_any_spec_rt_for_field_wise; mod impl_default; mod impl_field_wise_builder; mod impl_field_wise_spec_rt_for_field_wise; mod impl_field_wise_spec_rt_for_field_wise_external; mod impl_from_params_for_params_field_wise; mod impl_from_params_for_params_partial; mod impl_params_merge_ext_for_params; mod impl_try_from_params_partial_for_params; mod impl_value_spec_rt_for_field_wise; mod spec_is_usable; mod spec_merge; mod type_gen; mod type_gen_external; mod util; /// Used to `#[derive]` the `ValueSpec` and `ValueSpecRt` traits. /// /// For regular usage, use `#[derive(Params)]` /// /// For peace crates, also add the `#[peace_internal]` attribute, which /// references the `peace_params` crate instead of the `peace::params` /// re-export. /// /// # Generated Types /// /// * `*ParamsSpec`: Similar to `Params`, with each field taking in a /// specification of how the value is set. /// * `*ParamsPartial`: Similar to `Params`, with each field wrapped in /// `Option`. /// /// Both of these generated types will have: /// /// * A constructor if not all fields are `pub`. /// * Getters and mut getters for non-`pub`, non-`PhantomData` fields. /// /// Maybe we should also generate a `SpecBuilder` -- see commit `10f63611` which /// removed builder generation. /// /// # Attributes: /// /// * `peace_internal`: Type level attribute indicating the `peace_params` crate /// is referenced by `peace_params` instead of the default `peace::params`. /// /// * `crate_internal`: Type level attribute indicating the `peace_params` crate /// is referenced by `crate` instead of the default `peace::params`. /// /// * `value_spec(fieldless)`: Used as either of: /// /// - Type level attribute indicating fields are not known, and so /// `ParamsPartial` will instead hold an `Option<Params>` field. /// - Field level attribute indicating a third party type is in use, and a /// newtype wrapper should be generated to implement the /// `peace_params::Value` trait. /// /// * `default`: Enum variant attribute to indicate which variant to instantiate /// for `ParamsPartial::default()`. #[proc_macro_derive( Params, attributes(peace_internal, crate_internal, value_spec, default, serde) )] pub fn value_spec(input: TokenStream) -> TokenStream { let mut ast = syn::parse(input) .expect("`Params` derive: Failed to parse item as struct, enum, or union."); let gen = impl_value(&mut ast, ImplMode::Fieldwise); gen.into() } /// Used to `#[derive]` the `ParamsSpecFieldless` and `ValueSpecRt` traits. /// /// For regular usage, use `#[derive(ParamsFieldless)]` /// /// For peace crates, also add the `#[peace_internal]` attribute, which /// references the `peace_params` crate instead of the `peace::params` /// re-export. /// /// # Attributes: /// /// * `peace_internal`: Type level attribute indicating the `peace_params` crate /// is referenced by `peace_params` instead of the default `peace::params`. /// /// * `crate_internal`: Type level attribute indicating the `peace_params` crate /// is referenced by `crate` instead of the default `peace::params`. /// /// * `value_spec(fieldless)`: Type level attribute indicating fields are not /// known, and so `ParamsPartial` will instead hold an `Option<Value>` field. /// /// * `default`: Enum variant attribute to indicate which variant to instantiate /// for `ParamsPartial::default()`. #[proc_macro_derive( ParamsFieldless, attributes(peace_internal, crate_internal, value_spec, default) )] pub fn value_spec_fieldless(input: TokenStream) -> TokenStream { let mut ast = syn::parse(input) .expect("`ParamsFieldless` derive: Failed to parse item as struct, enum, or union."); let gen = impl_value(&mut ast, ImplMode::Fieldless); gen.into() } #[proc_macro] pub fn value_impl(input: TokenStream) -> TokenStream { let mut ast = syn::parse(input) .expect("`peace_params::value_impl`: Failed to parse item as struct, enum, or union."); let gen = impl_value(&mut ast, ImplMode::Fieldless); gen.into() } fn impl_value(ast: &mut DeriveInput, impl_mode: ImplMode) -> proc_macro2::TokenStream { let (peace_params_path, peace_resource_rt_path): (Path, Path) = ast .attrs .iter() .find_map(|attr| { if attr.path().is_ident("peace_internal") { Some((parse_quote!(peace_params), parse_quote!(peace_resource_rt))) } else if attr.path().is_ident("crate_internal") { Some((parse_quote!(crate), parse_quote!(peace_resource_rt))) } else { None } }) .unwrap_or_else(|| { ( parse_quote!(peace::params), parse_quote!(peace::resource_rt), ) }); type_parameters_constrain(ast); let value_name = &ast.ident; let generics = &ast.generics; let generics_split = generics.split_for_impl(); // MyValue -> MyValuePartial let t_partial_name = { let mut t_partial_name = ast.ident.to_string(); t_partial_name.push_str("Partial"); Ident::new(&t_partial_name, ast.ident.span()) }; // MyValue -> MyValueFieldWise let t_field_wise_name = { let mut t_field_wise_name = ast.ident.to_string(); t_field_wise_name.push_str("FieldWise"); Ident::new(&t_field_wise_name, ast.ident.span()) }; // MyValue -> MyValueFieldWiseBuilder let t_field_wise_builder_name = { let mut t_field_wise_builder_name = ast.ident.to_string(); t_field_wise_builder_name.push_str("FieldWiseBuilder"); Ident::new(&t_field_wise_builder_name, ast.ident.span()) }; let field_wise_enum_builder_ctx = { // `EnumParams`' generics with `VariantSelection` inserted beforehand. let generics = { let mut generics = ast.generics.clone(); generics.params.insert(0, parse_quote!(VariantSelection)); generics }; let variant_none = format_ident!("{}VariantNone", t_field_wise_builder_name); // Used for PhantomData type parameters, as well as `Default` impl type // parameters. let ty_generics_idents = ast.generics.params.iter().fold( proc_macro2::TokenStream::new(), |mut tokens, generic_param| { match generic_param { GenericParam::Lifetime(_) => { panic!("Lifetime generics are not supported in Params derive.") } GenericParam::Type(type_param) => { tokens.extend(type_param.ident.to_token_stream()) } GenericParam::Const(const_param) => { tokens.extend(const_param.ident.to_token_stream()) } } tokens }, ); let type_params_with_variant_none = quote!(<#variant_none, #ty_generics_idents>); FieldWiseEnumBuilderCtx { generics, variant_none, ty_generics_idents, type_params_with_variant_none, } }; let builder_generics = if matches!(&ast.data, Data::Enum(_)) { #[allow(clippy::redundant_clone)] // False positive 2023-05-19 field_wise_enum_builder_ctx .type_params_with_variant_none .clone() } else { let ty_generics = &generics_split.1; quote!(#ty_generics) }; let (t_partial, t_field_wise, t_field_wise_builder, impl_params_merge_ext_for_params) = if is_fieldless_type(ast) || impl_mode == ImplMode::Fieldless { let ty_generics = &generics_split.1; let value_ty: Type = parse_quote!(#value_name #ty_generics); let t_partial = t_partial_external(ast, &generics_split, &value_ty, &t_partial_name); let t_field_wise = t_field_wise_external( ast, &generics_split, &peace_params_path, &peace_resource_rt_path, &value_ty, value_name, &t_field_wise_name, &t_partial_name, ); (t_partial, t_field_wise, None, None) } else { let t_partial = t_partial(ast, &generics_split, value_name, &t_partial_name); let t_field_wise = t_field_wise( ast, &generics_split, &peace_params_path, &peace_resource_rt_path, value_name, &t_field_wise_name, &t_partial_name, ); let t_field_wise_builder = impl_field_wise_builder( ast, &generics_split, &peace_params_path, &t_field_wise_name, &t_field_wise_builder_name, impl_mode, &field_wise_enum_builder_ctx, ); let impl_params_merge_ext_for_params = impl_params_merge_ext_for_params( ast, &generics_split, &peace_params_path, value_name, &t_partial_name, ); ( t_partial, t_field_wise, Some(t_field_wise_builder), Some(impl_params_merge_ext_for_params), ) }; let (impl_generics, ty_generics, where_clause) = &generics_split; let mut impl_value_tokens = proc_macro2::TokenStream::new(); match impl_mode { ImplMode::Fieldwise => impl_value_tokens.extend(quote! { impl #impl_generics #peace_params_path::Params for #value_name #ty_generics #where_clause { type Spec = #peace_params_path::ParamsSpec<#value_name #ty_generics>; type Partial = #t_partial_name #ty_generics; type FieldWiseSpec = #t_field_wise_name #ty_generics; type FieldWiseBuilder = #t_field_wise_builder_name #builder_generics; fn field_wise_spec() -> Self::FieldWiseBuilder { Self::FieldWiseBuilder::default() } } }), ImplMode::Fieldless => {} } impl_value_tokens.extend(quote! { impl #impl_generics #peace_params_path::ParamsFieldless for #value_name #ty_generics #where_clause { type Spec = #peace_params_path::ParamsSpecFieldless<#value_name #ty_generics>; type Partial = #t_partial_name #ty_generics; } #t_partial #t_field_wise #t_field_wise_builder #impl_params_merge_ext_for_params }); impl_value_tokens } /// Adds trait bounds on each of the type parameters. /// /// * `Send + Sync + 'static` is always added /// * If a type has `#[serde(bound = "<Bound>")]`s, those bounds are used. /// * If a type does not have `#[serde(bound = "")]`, `Serialize + /// DeserializeOwned` is added for each type parameter. fn type_parameters_constrain(ast: &mut DeriveInput) { let serde_bounds_for_type_params = serde_bounds_for_type_params(ast); let additional_bounds = ast .generics .params .iter() .filter_map(|generic_param| match generic_param { GenericParam::Lifetime(_) => None, GenericParam::Type(type_param) => Some(type_param), GenericParam::Const(_) => None, }) .map(|type_param| parse_quote!(#type_param: Send + Sync + 'static)) .collect::<Vec<WherePredicate>>(); let generics = &mut ast.generics; let where_predicates = generics.make_where_clause(); where_predicates.predicates.extend(additional_bounds); where_predicates .predicates .extend(serde_bounds_for_type_params); } /// Generates something like the following: /// /// ```rust,ignore /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct MyParamsPartial { /// src: Option<PathBuf>, /// dest_ip: Option<IpAddr>, /// dest_path: Option<PathBuf>, /// } /// ``` fn t_partial( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), params_name: &Ident, t_partial_name: &Ident, ) -> proc_macro2::TokenStream { let mut t_partial = TypeGen::gen_from_value_type( ast, generics_split, t_partial_name, fields_to_optional, &[ parse_quote! { #[doc="\ Item parameters that may not necessarily have values.\n\ \n\ This is used for `try_state_current` and `try_state_goal` where values \n\ could be referenced from predecessors, which may not yet be available, such \n\ as the IP address of a server that is yet to be launched, or may change, \n\ such as the content hash of a file which is to be re-downloaded.\n\ "] }, parse_quote!(#[derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)]), ], true, ); t_partial.extend(impl_try_from_params_partial_for_params( ast, generics_split, params_name, t_partial_name, )); t_partial.extend(impl_default(ast, generics_split, t_partial_name)); t_partial.extend(impl_from_params_for_params_partial( ast, generics_split, params_name, t_partial_name, )); t_partial } /// Generates something like the following: /// /// ```rust,ignore /// #[derive(Clone, Debug, PartialEq, Eq)] /// struct MyParamsPartial(Option<MyParams>) /// ``` fn t_partial_external( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), value_ty: &Type, t_partial_name: &Ident, ) -> proc_macro2::TokenStream { type_gen_external( ast, generics_split, value_ty, t_partial_name, &[ parse_quote! { #[doc="\ Item parameters that may not necessarily have values.\n\ \n\ This is used for `try_state_current` and `try_state_goal` where values \n\ could be referenced from predecessors, which may not yet be available, such \n\ as the IP address of a server that is yet to be launched, or may change, \n\ such as the content hash of a file which is to be re-downloaded.\n\ "] }, parse_quote!(#[derive(PartialEq, Eq, serde::Serialize, serde::Deserialize)]), ], ) } /// Generates something like the following: /// /// ```rust,ignore /// struct MyParamsFieldWise { /// src: peace_params::ParamsSpecFieldless<PathBuf>, /// dest_ip: peace_params::ParamsSpecFieldless<IpAddr>, /// dest_path: peace_params::ParamsSpecFieldless<PathBuf>, /// } /// ``` fn t_field_wise( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, peace_resource_rt_path: &Path, params_name: &Ident, t_field_wise_name: &Ident, t_partial_name: &Ident, ) -> proc_macro2::TokenStream { let mut t_field_wise = TypeGen::gen_from_value_type( ast, generics_split, t_field_wise_name, |fields| fields_to_value_spec(fields, peace_params_path), &[ parse_quote! { #[doc="Specification of how to look up values for an item's parameters."] }, // `Clone` and `Debug` are implemented manually, so that type parameters do not receive // the `Clone` and `Debug` bounds. parse_quote!(#[derive(serde::Serialize, serde::Deserialize)]), ], true, ); t_field_wise.extend(impl_field_wise_spec_rt_for_field_wise( ast, generics_split, peace_params_path, peace_resource_rt_path, params_name, t_field_wise_name, t_partial_name, )); t_field_wise.extend(impl_value_spec_rt_for_field_wise( ast, generics_split, peace_params_path, peace_resource_rt_path, params_name, t_field_wise_name, )); t_field_wise.extend(impl_from_params_for_params_field_wise( ast, generics_split, peace_params_path, params_name, t_field_wise_name, )); t_field_wise.extend(impl_any_spec_rt_for_field_wise( ast, generics_split, peace_params_path, t_field_wise_name, )); t_field_wise } /// Generates something like the following: /// /// ```rust,ignore /// struct MyParamsFieldWise(peace_params::ParamsSpecFieldless<MyParams>) /// ``` // TODO: Refactor this crate to not pass redundant information, or use a context object. #[allow(clippy::too_many_arguments)] fn t_field_wise_external( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, peace_resource_rt_path: &Path, params_ty: &Type, params_name: &Ident, t_field_wise_name: &Ident, t_partial_name: &Ident, ) -> proc_macro2::TokenStream { let mut t_field_wise = type_gen_external( ast, generics_split, params_ty, t_field_wise_name, &[ parse_quote! { #[doc="Specification of how to look up values for an item's parameters."] }, parse_quote!(#[derive(serde::Serialize, serde::Deserialize)]), ], ); t_field_wise.extend(impl_field_wise_spec_rt_for_field_wise_external( generics_split, peace_params_path, peace_resource_rt_path, params_name, t_field_wise_name, t_partial_name, )); t_field_wise.extend(impl_any_spec_rt_for_field_wise( ast, generics_split, peace_params_path, t_field_wise_name, )); t_field_wise }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/fields_map.rs
crate/params_derive/src/fields_map.rs
use syn::{Attribute, Field, Fields, FieldsNamed, FieldsUnnamed, Path, Type}; use crate::util::{field_spec_ty, is_phantom_data, is_serde_bound_attr}; /// Maps fields into different fields, wrapping them with the appropriate braces /// / parenthesis if necessary. pub fn fields_map<F>(fields: &Fields, f: F) -> Fields where F: Fn(&Field) -> proc_macro2::TokenStream, { let fields_mapped = fields.iter().map(|field| (field, f(field))); match fields { Fields::Named(_fields_named) => { let fields_mapped = fields_mapped.map(|(field, expr)| { let field_name = &field.ident; quote!(#field_name: #expr) }); let fields_named: FieldsNamed = parse_quote!({ #(#fields_mapped,)* }); Fields::from(fields_named) } Fields::Unnamed(_fields_unnamed) => { let fields_mapped = fields_mapped.map(|(_field, expr)| expr); let fields_unnamed: FieldsUnnamed = parse_quote!((#(#fields_mapped,)*)); Fields::from(fields_unnamed) } Fields::Unit => fields.clone(), } } pub fn fields_to_optional(fields: &mut Fields) { fields_each_map(fields, |field| { let field_ty = &field.ty; if is_phantom_data(field_ty) { field_ty.clone() } else { parse_quote!(Option<#field_ty>) } }) } /// Maps each field from `MyType` to `ValueSpec<MyType>`. /// /// If the type is marked with `#[value_spec(fieldless)]`, then it is wrapped /// as `ValueSpec<MyTypeWrapper>`. pub fn fields_to_value_spec(fields: &mut Fields, peace_params_path: &Path) { fields_each_map(fields, |field| { let field_ty = &field.ty; if is_phantom_data(field_ty) { field_ty.clone() } else { // For external types, we don't know if they implement `ValueSpec`, so we treat // fields with this attribute as `ParamsSpecFieldless`. Have tried to hold a // `Box<dyn ValueSpecRt>`, so it could delegate to either the `ValueSpec` or // `ParamsSpecFieldless`. However, it makes it hard to deserialize from a // serialized `ValueSpec` because we would have to generate a concrete type with // the `field_ty`, which may make it impossible to handle upgrades / evolving // params types. // // In #119, we tried using `ValueSpec` for recursive value spec resolution, but // it proved too difficult. syn::parse2(field_spec_ty(peace_params_path, field_ty)) .expect("Failed to parse field to value spec.") } }) } /// Maps each field from `MyType` to `Option<ValueSpec<MyType>>`. /// /// If the type is marked with `#[value_spec(fieldless)]`, then it is wrapped /// as `Option<ValueSpec<MyTypeWrapper>>`. /// /// Fieldless types -- stdlib types or types annotated with /// `#[value_spec(fieldless)]` -- are wrapped as: /// /// ```rust,ignore /// `Option<ParamsSpecFieldless<MyTypeWrapper>>`. /// ``` pub fn fields_to_optional_value_spec(fields: &mut Fields, peace_params_path: &Path) { fields_each_map(fields, |field| { field_to_optional_value_spec(field, peace_params_path) }) } /// Maps a field to `Option<ValueSpec<#field_ty>>`, `PhantomData` is returned as /// is. pub fn field_to_optional_value_spec(field: &Field, peace_params_path: &Path) -> Type { let field_ty = &field.ty; if is_phantom_data(field_ty) { field_ty.clone() } else { let field_spec_ty = field_spec_ty(peace_params_path, field_ty); parse_quote!(Option<#field_spec_ty>) } } fn fields_each_map<F>(fields: &mut Fields, f: F) where F: Fn(&Field) -> Type, { match fields { Fields::Named(fields_named) => { fields_named.named.iter_mut().for_each(|field| { field.ty = f(field); // Don't copy across most attributes. // The only attribute we copy across is `#[serde(bound = "..")]` field.attrs = field .attrs .drain(..) .filter(is_serde_bound_attr) .collect::<Vec<Attribute>>(); }); } Fields::Unnamed(fields_unnamed) => { fields_unnamed.unnamed.iter_mut().for_each(|field| { field.ty = f(field); // Don't copy across most attributes. // The only attribute we copy across is `#[serde(bound = "..")]` field.attrs = field .attrs .drain(..) .filter(is_serde_bound_attr) .collect::<Vec<Attribute>>(); }); } Fields::Unit => {} } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/spec_is_usable.rs
crate/params_derive/src/spec_is_usable.rs
use syn::{punctuated::Punctuated, DeriveInput, Fields, Ident, Path, Variant}; use crate::util::{fields_deconstruct, fields_stmt_map, variant_match_arm}; pub fn is_usable_body( ast: &DeriveInput, params_field_wise_name: &Ident, peace_params_path: &Path, ) -> proc_macro2::TokenStream { match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_is_usable(params_field_wise_name, fields, peace_params_path) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_is_usable(params_field_wise_name, variants, peace_params_path) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_is_usable(params_field_wise_name, &fields, peace_params_path) } } } /// Returns whether the fields within this struct all return `true` for /// `is_usable`. pub fn struct_fields_is_usable( params_field_wise_name: &Ident, fields: &Fields, peace_params_path: &Path, ) -> proc_macro2::TokenStream { let fields_is_usable = fields_is_usable(fields, peace_params_path); let fields_deconstructed = fields_deconstruct(fields); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_field_wise_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // let mut is_usable = true; // is_usable &= AnySpecRt::is_usable(field_1); // is_usable &= AnySpecRt::is_usable(field_2); // // is_usable // ``` quote! { let #params_field_wise_name { #(#fields_deconstructed),* } = self; let mut is_usable = true; #fields_is_usable is_usable } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(_0, _1, PhantomData,) = self; // // let mut is_usable = true; // is_usable &= AnySpecRt::is_usable(_0); // is_usable &= AnySpecRt::is_usable(_1); // // is_usable // ``` quote! { let #params_field_wise_name(#(#fields_deconstructed),*) = self; let mut is_usable = true; #fields_is_usable is_usable } } Fields::Unit => quote!(true), } } /// Returns whether the fields within this enum all return `true` for /// `is_usable`. pub fn variants_is_usable( params_field_wise_name: &Ident, variants: &Punctuated<Variant, Token![,]>, peace_params_path: &Path, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match self { // ValueSpec::Variant1 => true, // ValueSpec::Variant2(_0, _1, PhantomData) => { // let mut is_usable = true; // is_usable &= AnySpecRt::is_usable(_0); // is_usable &= AnySpecRt::is_usable(_1); // is_usable // } // ValueSpec::Variant3 { // field_1, // field_2, // marker: PhantomData, // } => { // let mut is_usable = true; // is_usable &= AnySpecRt::is_usable(field_1); // is_usable &= AnySpecRt::is_usable(field_2); // is_usable // } // } // ``` let variant_resolve_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let fields = &variant.fields; let fields_deconstructed = fields_deconstruct(fields); let variant_fields_is_usable = { let fields_is_usable = fields_is_usable(fields, peace_params_path); quote! { let mut is_usable = true; #fields_is_usable is_usable } }; tokens.extend(variant_match_arm( params_field_wise_name, variant, &fields_deconstructed, variant_fields_is_usable, )); tokens }); quote! { match self { #variant_resolve_arms } } } fn fields_is_usable(fields: &Fields, peace_params_path: &Path) -> proc_macro2::TokenStream { fields_stmt_map(fields, move |_field, field_name, _field_index| { quote! { is_usable &= #peace_params_path::AnySpecRt::is_usable(#field_name); } }) .fold( proc_macro2::TokenStream::new(), |mut tokens, next_tokens| { tokens.extend(next_tokens); tokens }, ) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/type_gen_external.rs
crate/params_derive/src/type_gen_external.rs
use syn::{Attribute, DeriveInput, Ident, ImplGenerics, Type, TypeGenerics, WhereClause}; use crate::util::is_serde_bound_attr; /// Generates a type based off an external `Value` type. /// /// A `MyValue` wrapped type will produce: /// /// ```rust,ignore /// pub struct Generated(Option<MyValue>); /// ``` /// /// This is meant to be used for external `ValuePartial` and maybe /// `ValueFieldWise`. /// /// # Parameters /// /// * `ast`: The `Value` type. /// * `generics_split`: Generics of the `Value` type. /// * `value_name`: Name of the params / value type. /// * `type_name`: Name of the type to generate. /// * `attrs`: Attributes to attach to the generated type. pub fn type_gen_external( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), value_ty: &Type, type_name: &Ident, attrs: &[Attribute], ) -> proc_macro2::TokenStream { let mut serde_bound_attrs = ast .attrs .iter() .filter(|attr| is_serde_bound_attr(attr)) .collect::<Vec<&Attribute>>(); let serde_bound_empty = parse_quote!(#[serde(bound = "")]); if serde_bound_attrs.is_empty() { serde_bound_attrs.push(&serde_bound_empty); } let (impl_generics, ty_generics, where_clause) = generics_split; let constructor_doc = format!("Returns a new `{type_name}`."); let mut generics_for_ref = ast.generics.clone(); generics_for_ref.params.insert(0, parse_quote!('generated)); let (impl_generics_for_ref, _type_generics, _where_clause) = generics_for_ref.split_for_impl(); let mut tokens = quote! { #(#attrs)* #(#serde_bound_attrs)* pub struct #type_name #ty_generics(Option<#value_ty>) #where_clause; impl #impl_generics #type_name #ty_generics #where_clause { #[doc = #constructor_doc] pub fn new(value: Option<#value_ty>) -> Self { Self(value) } pub fn into_inner(self) -> Option<#value_ty> { self.0 } } impl #impl_generics ::std::clone::Clone for #type_name #ty_generics #where_clause { fn clone(&self) -> Self { Self(self.0.clone()) } } impl #impl_generics ::std::fmt::Debug for #type_name #ty_generics #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { f.debug_tuple(stringify!(#type_name)) .field(&self.0) .finish() } } impl #impl_generics ::std::default::Default for #type_name #ty_generics #where_clause { fn default() -> Self { Self(None) } } impl #impl_generics ::std::ops::Deref for #type_name #ty_generics #where_clause { type Target = Option<#value_ty>; fn deref(&self) -> &Self::Target { &self.0 } } impl #impl_generics ::std::ops::DerefMut for #type_name #ty_generics #where_clause { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } // impl From<Value> for ValuePartial impl #impl_generics ::std::convert::From<#value_ty> for #type_name #ty_generics #where_clause { fn from(value: #value_ty) -> Self { Self::new(Some(value)) } } }; tokens.extend(quote! { // impl TryFrom<ValuePartial> for Value impl #impl_generics ::std::convert::TryFrom<#type_name #ty_generics> for #value_ty #where_clause { type Error = #type_name #ty_generics; fn try_from(generated: #type_name #ty_generics) -> Result<Self, Self::Error> { if let Some(value) = generated.0 { Ok(value) } else { Err(generated) } } } impl #impl_generics_for_ref ::std::convert::TryFrom<&'generated #type_name #ty_generics> for #value_ty #where_clause { type Error = &'generated #type_name #ty_generics; fn try_from(generated: &'generated #type_name #ty_generics) -> Result<Self, Self::Error> { if let Some(value) = generated.0.as_ref() { Ok(value.clone()) } else { Err(generated) } } } }); tokens }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_from_params_for_params_field_wise.rs
crate/params_derive/src/impl_from_params_for_params_field_wise.rs
use syn::{ punctuated::Punctuated, DeriveInput, Fields, Ident, ImplGenerics, Path, TypeGenerics, Variant, WhereClause, }; use crate::util::{ field_spec_ty_deconstruct, fields_deconstruct, is_phantom_data, tuple_ident_from_field_index, variant_match_arm, }; /// `impl From<Params> for ParamsFieldWise`, so that users can provide /// `params.into()` when building a cmd_ctx, instead of constructing a /// `ParamsFieldWise`. pub fn impl_from_params_for_params_field_wise( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, params_name: &Ident, params_field_wise_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let from_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_map_to_value( params_name, params_field_wise_name, fields, peace_params_path, ) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_map_to_value( params_name, params_field_wise_name, variants, peace_params_path, ) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_map_to_value( params_name, params_field_wise_name, &fields, peace_params_path, ) } }; quote! { impl #impl_generics From<#params_name #ty_generics> for #params_field_wise_name #ty_generics #where_clause { fn from(params: #params_name #ty_generics) -> Self { #from_body } } } } fn struct_fields_map_to_value( params_name: &Ident, params_field_wise_name: &Ident, fields: &Fields, peace_params_path: &Path, ) -> proc_macro2::TokenStream { let fields_deconstructed = fields_deconstruct(fields); let fields_map_to_value = fields_map_to_value(fields, peace_params_path); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_name { // field_1, // field_2, // marker: PhantomData, // } = params; // // #params_field_wise_name { // #fields_map_to_value // } // ``` quote! { let #params_name { #(#fields_deconstructed),* } = params; #params_field_wise_name { #fields_map_to_value } } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(#(#fields_deconstructed),*) = params; // // #params_field_wise_name(#fields_map_to_value) // ``` quote! { let #params_name(#(#fields_deconstructed),*) = params; #params_field_wise_name(#fields_map_to_value) } } Fields::Unit => quote!(#params_field_wise_name), } } fn variants_map_to_value( params_name: &Ident, params_field_wise_name: &Ident, variants: &Punctuated<Variant, Token![,]>, peace_params_path: &Path, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match params { // Params::Variant1 => Params::Variant1, // Params::Variant2(_0, _1, PhantomData) => { // Params::Variant2( // #peace_params_path::ParamsSpecFieldless::Value { value: _0 }, // #peace_params_path::ParamsSpecFieldless::Value { value: _1 }, // PhantomData, // // // or // // #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_0) }, // // #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_1) }, // ) // } // Params::Variant3 { field_1, field_2, marker: PhantomData } => { // Params::Variant3 { // field_1: #peace_params_path::ParamsSpecFieldless::Value { value: field_1 }, // field_2: #peace_params_path::ParamsSpecFieldless::Value { value: field_2 }, // marker: PhantomData, // // // or // // field_1: #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_0) }, // // field_2: #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_1) }, // } // } // } // ``` let variant_map_to_value_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let variant_fields = fields_deconstruct(&variant.fields); let variant_fields_map_to_value = variant_fields_map_to_value( params_field_wise_name, &variant.ident, &variant.fields, peace_params_path, ); tokens.extend(variant_match_arm( params_name, variant, &variant_fields, variant_fields_map_to_value, )); tokens }); quote! { match params { #variant_map_to_value_arms } } } fn variant_fields_map_to_value( params_field_wise_name: &Ident, variant_name: &Ident, fields: &Fields, peace_params_path: &Path, ) -> proc_macro2::TokenStream { let fields_map_to_value = fields_map_to_value(fields, peace_params_path); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // ParamsFieldWiseName { // #fields_map_to_value // } // ``` quote! { #params_field_wise_name::#variant_name { #fields_map_to_value } } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // ParamsFieldWiseName(#fields_map_to_value) // ``` quote! { #params_field_wise_name::#variant_name(#fields_map_to_value) } } Fields::Unit => quote!(Self::#variant_name), } } fn fields_map_to_value(fields: &Fields, peace_params_path: &Path) -> proc_macro2::TokenStream { match fields { Fields::Named(fields_named) => { // Generates: // // ```rust // field_1: #peace_params_path::ParamsSpecFieldless::Value { value: field_1 }, // field_2: #peace_params_path::ParamsSpecFieldless::Value { value: field_2 }, // marker: PhantomData, // // // or // // field_1: #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(field_1) }, // // field_2: #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(field_2) }, // ``` fields_named .named .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, field| { if let Some(field_name) = field.ident.as_ref() { if is_phantom_data(&field.ty) { tokens.extend(quote! { #field_name: std::marker::PhantomData, }); } else { let field_spec_ty_deconstruct = field_spec_ty_deconstruct(peace_params_path, field_name); tokens.extend(quote! { #field_name: #field_spec_ty_deconstruct, }); } } tokens }) } Fields::Unnamed(fields_unnamed) => { // Generates: // // ```rust // #peace_params_path::ParamsSpecFieldless::Value { value: _0 }, // #peace_params_path::ParamsSpecFieldless::Value { value: _1 }, // PhantomData, // // // or // // #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_0) }, // // #peace_params_path::ParamsSpecFieldless::Value { value: Wrapper(_1) }, // ``` fields_unnamed.unnamed.iter().enumerate().fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { let field_name = tuple_ident_from_field_index(field_index); if is_phantom_data(&field.ty) { tokens.extend(quote!(std::marker::PhantomData,)); } else { let field_spec_ty_deconstruct = field_spec_ty_deconstruct(peace_params_path, &field_name); tokens.extend(quote!(#field_spec_ty_deconstruct,)); } tokens }, ) } Fields::Unit => quote!(), } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_try_from_params_partial_for_params.rs
crate/params_derive/src/impl_try_from_params_partial_for_params.rs
use syn::{ punctuated::Punctuated, DeriveInput, Fields, Ident, ImplGenerics, TypeGenerics, Variant, WhereClause, }; use crate::util::{ fields_deconstruct, fields_deconstruct_some, is_phantom_data, tuple_ident_from_field_index, variant_match_arm, }; /// `impl TryFrom<ParamsPartial> for Params`, so that users can use /// `params_partial.try_into()` in `Item::try_state_*` without needing to /// deconstruct the `Params::Partial`. pub fn impl_try_from_params_partial_for_params( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), params_name: &Ident, params_partial_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let try_from_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_try_map_from_value( params_name, params_partial_name, fields, TryFromMode::Owned, ) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_try_map_from_value( params_name, params_partial_name, variants, TryFromMode::Owned, ) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_try_map_from_value( params_name, params_partial_name, &fields, TryFromMode::Owned, ) } }; let try_from_ref_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_try_map_from_value( params_name, params_partial_name, fields, TryFromMode::Ref, ) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_try_map_from_value( params_name, params_partial_name, variants, TryFromMode::Ref, ) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_try_map_from_value( params_name, params_partial_name, &fields, TryFromMode::Ref, ) } }; let mut generics_for_ref = ast.generics.clone(); generics_for_ref.params.insert(0, parse_quote!('partial)); let (impl_generics_for_ref, _type_generics, _where_clause) = generics_for_ref.split_for_impl(); quote! { impl #impl_generics ::std::convert::TryFrom<#params_partial_name #ty_generics> for #params_name #ty_generics #where_clause { type Error = #params_partial_name #ty_generics; fn try_from(params_partial: #params_partial_name #ty_generics) -> Result<Self, Self::Error> { #try_from_body } } impl #impl_generics_for_ref ::std::convert::TryFrom<&'partial #params_partial_name #ty_generics> for #params_name #ty_generics #where_clause { type Error = &'partial #params_partial_name #ty_generics; fn try_from(params_partial: &'partial #params_partial_name #ty_generics) -> Result<Self, Self::Error> { #try_from_ref_body } } } } fn struct_fields_try_map_from_value( params_name: &Ident, params_partial_name: &Ident, fields: &Fields, try_from_mode: TryFromMode, ) -> proc_macro2::TokenStream { let fields_deconstructed = fields_deconstruct(fields); let fields_deconstructed_some = fields_deconstruct_some(fields); let fields_to_owned = try_from_mode.fields_to_owned(fields); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // if let #params_partial_name { // field_1: Some(field_1), // field_2: Some(field_2), // marker: PhantomData, // } = params_partial { // #fields_to_owned // // Ok(#params_name { // field_1, // field_2, // marker: PhantomData, // }) // } else { // Err(params_partial) // } // ``` quote! { if let #params_partial_name { #(#fields_deconstructed_some),* } = params_partial { #fields_to_owned Ok(#params_name { #(#fields_deconstructed),* }) } else { Err(params_partial) } } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // if let #params_partial_name( // Some(field_1), // Some(field_2), // PhantomData, // ) = params_partial { // #fields_to_owned // // Ok(#params_name( // field_1, // field_2, // PhantomData, // )) // } else { // Err(params_partial) // } // ``` quote! { if let #params_partial_name( #(#fields_deconstructed_some),* ) = params_partial { #fields_to_owned Ok(#params_name(#(#fields_deconstructed),*)) } else { Err(params_partial) } } } Fields::Unit => quote!(Ok(#params_name)), } } fn variants_try_map_from_value( params_name: &Ident, params_partial_name: &Ident, variants: &Punctuated<Variant, Token![,]>, try_from_mode: TryFromMode, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match params_partial { // #params_partial_name::Variant1 => Ok(#params_name::Variant1), // #params_partial_name::Variant2(Some(_0), Some(_1), PhantomData) => { // #fields_to_owned // // Ok(#params_name::Variant2( // _0, // _1, // PhantomData, // )) // } // #params_partial_name::Variant3 { // field_1: Some(field_1), // field_2: Some(field_2), // marker: PhantomData, // } => { // #fields_to_owned // // Ok(#params_name::Variant3 { // field_1, // field_2, // marker: PhantomData, // }) // } // _ => Err(params_partial), // } // ``` let variant_try_map_from_value_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let variant_fields = fields_deconstruct_some(&variant.fields); let variant_fields_try_map_from_value = variant_fields_try_map_from_value( params_name, &variant.ident, &variant.fields, try_from_mode, ); tokens.extend(variant_match_arm( params_partial_name, variant, &variant_fields, variant_fields_try_map_from_value, )); tokens }); quote! { match params_partial { #variant_try_map_from_value_arms _ => Err(params_partial), } } } fn variant_fields_try_map_from_value( params_name: &Ident, variant_name: &Ident, fields: &Fields, try_from_mode: TryFromMode, ) -> proc_macro2::TokenStream { let fields_deconstructed = fields_deconstruct(fields); let fields_to_owned = try_from_mode.fields_to_owned(fields); match fields { Fields::Named(_fields_named) => { quote! { #fields_to_owned Ok(#params_name::#variant_name { #(#fields_deconstructed),* }) } } Fields::Unnamed(_fields_unnamed) => { quote! { #fields_to_owned Ok(#params_name::#variant_name(#(#fields_deconstructed),*)) } } Fields::Unit => quote!(Ok(Self::#variant_name)), } } /// Whether code is generated for an owned or borrowed `Params::Partial`. #[derive(Clone, Copy, Debug)] enum TryFromMode { /// `Params::Partial` is owned. Owned, /// `Params::Partial` is borrowed. Ref, } impl TryFromMode { /// Returns `to_owned()` statements for each field for a borrowed /// `Params::Partial`. /// /// Generates: /// /// ```rust /// // may need `to_vec()` or `to_string()` for `&[]` and `str`. /// let field_1 = ::std::borrow::ToOwned(field_1); /// let field_2 = ::std::borrow::ToOwned(field_2); /// ``` fn fields_to_owned(self, fields: &Fields) -> Option<proc_macro2::TokenStream> { match self { Self::Owned => None, Self::Ref => { let tokens = fields .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { if let Some(field_name) = field.ident.as_ref() { tokens.extend(quote! { let #field_name = ::std::borrow::ToOwned::to_owned(#field_name); }); } else { let field_name = tuple_ident_from_field_index(field_index); tokens.extend(quote! { let #field_name = ::std::borrow::ToOwned::to_owned(#field_name); }); } tokens }, ); Some(tokens) } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_field_wise_spec_rt_for_field_wise.rs
crate/params_derive/src/impl_field_wise_spec_rt_for_field_wise.rs
use proc_macro2::Span; use syn::{ punctuated::Punctuated, Data, DeriveInput, Field, Fields, Ident, ImplGenerics, LitInt, Path, TypeGenerics, Variant, WhereClause, }; use crate::util::{field_spec_ty_path, fields_deconstruct, is_phantom_data, variant_match_arm}; /// `impl FieldWiseSpecRt for ValueSpec`, so that Peace can resolve the params /// type as well as its values from the spec. pub fn impl_field_wise_spec_rt_for_field_wise( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, peace_resource_rt_path: &Path, params_name: &Ident, params_field_wise_name: &Ident, params_partial_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let resolve_body = match &ast.data { Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_resolve( params_field_wise_name, fields, peace_params_path, ResolveMode::Full { params_name }, ) } Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_resolve( params_field_wise_name, variants, peace_params_path, ResolveMode::Full { params_name }, ) } Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_resolve( params_field_wise_name, &fields, peace_params_path, ResolveMode::Full { params_name }, ) } }; let resolve_partial_body = match &ast.data { Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_resolve( params_field_wise_name, fields, peace_params_path, ResolveMode::Partial { params_partial_name, }, ) } Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_resolve( params_field_wise_name, variants, peace_params_path, ResolveMode::Partial { params_partial_name, }, ) } Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_resolve( params_field_wise_name, &fields, peace_params_path, ResolveMode::Partial { params_partial_name, }, ) } }; quote! { impl #impl_generics #peace_params_path::FieldWiseSpecRt for #params_field_wise_name #ty_generics #where_clause { type ValueType = #params_name #ty_generics; type Partial = #params_partial_name #ty_generics; fn resolve( &self, mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<#params_name #ty_generics, #peace_params_path::ParamsResolveError> { #resolve_body } fn resolve_partial( &self, mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<#params_partial_name #ty_generics, #peace_params_path::ParamsResolveError> { #resolve_partial_body } } } } fn struct_fields_resolve( params_field_wise_name: &Ident, fields: &Fields, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { let fields_resolution = fields_resolution(fields, peace_params_path, resolve_mode); let fields_deconstructed = fields_deconstruct(fields); let params_return_type_name = resolve_mode.params_return_type_name(); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_field_wise_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // #fields_resolution // // let params = #params_return_type_name { // field_1, // field_2, // marker: PhantomData, // }; // // Ok(params) // ``` quote! { let #params_field_wise_name { #(#fields_deconstructed),* } = self; #fields_resolution let params = #params_return_type_name { #(#fields_deconstructed),* }; Ok(params) } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(_0, _1, PhantomData,) = self; // // #fields_resolution // // let params = #params_return_type_name(_0, _1, PhantomData,); // Ok(params) // ``` quote! { let #params_field_wise_name(#(#fields_deconstructed),*) = self; #fields_resolution let params = #params_return_type_name(#(#fields_deconstructed),*); Ok(params) } } Fields::Unit => quote!(Ok(#params_return_type_name)), } } fn variants_resolve( params_field_wise_name: &Ident, variants: &Punctuated<Variant, Token![,]>, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match self { // ValueSpec::Variant1 => Ok(Params::Variant1), // ValueSpec::Variant2(_0, _1, PhantomData) => { // let _0 = ..?; // let _1 = ..?; // let params = Params::Variant2(_0, _1, PhantomData); // Ok(params) // } // ValueSpec::Variant3 { field_1, field_2, marker: PhantomData } => { // #variant_fields_resolve // } // } // ``` let variant_resolve_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let fields_deconstructed = fields_deconstruct(&variant.fields); let variant_fields_resolve = variant_fields_resolve( &variant.ident, &variant.fields, &fields_deconstructed, peace_params_path, resolve_mode, ); tokens.extend(variant_match_arm( params_field_wise_name, variant, &fields_deconstructed, variant_fields_resolve, )); tokens }); quote! { match self { #variant_resolve_arms } } } // Code gen, not user facing #[allow(clippy::too_many_arguments)] fn variant_fields_resolve( variant_name: &Ident, fields: &Fields, fields_deconstructed: &[proc_macro2::TokenStream], peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { let fields_resolution = fields_resolution(fields, peace_params_path, resolve_mode); let params_return_type_name = resolve_mode.params_return_type_name(); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // #fields_resolution // // let params = #params_return_type_name::Variant { // field_1, // field_2, // marker: PhantomData, // }; // // Ok(params) // ``` quote! { #fields_resolution let params = #params_return_type_name::#variant_name { #(#fields_deconstructed),* }; Ok(params) } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // #fields_resolution // // let params = #params_return_type_name::Variant(_0, _1, PhantomData,); // Ok(params) // ``` quote! { #fields_resolution let params = #params_return_type_name::#variant_name(#(#fields_deconstructed),*); Ok(params) } } Fields::Unit => quote!(Ok(#params_return_type_name::#variant_name)), } } fn fields_resolution( fields: &Fields, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { match fields { Fields::Named(fields_named) => { // Generates: // // ```rust // value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( // String::from(stringify!(field_1)), // String::from(#peace_params_path::tynm::type_name::<#field_ty>())), // ); // let field_1 = field_1.resolve(resources, value_resolution_ctx)?; // value_resolution_ctx.pop(); // ``` fields_named .named .iter() .filter(|field| !is_phantom_data(&field.ty)) .filter_map(|field| field.ident.as_ref().map(|field_name| (field, field_name))) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field, field_name)| { let field_ty = &field.ty; let resolve_method = resolve_mode.resolve_method(peace_params_path, field_name, field); tokens.extend(quote! { value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( String::from(stringify!(#field_name)), String::from(#peace_params_path::tynm::type_name::<#field_ty>())), ); #resolve_method value_resolution_ctx.pop(); }); tokens }, ) } Fields::Unnamed(fields_unnamed) => { // Generates: // // ```rust // value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( // String::from(stringify!(1)), // String::from(#peace_params_path::tynm::type_name::<#field_ty>())), // ); // let _1 = _1.resolve(resources, value_resolution_ctx)?; // value_resolution_ctx.pop(); // ``` fields_unnamed .unnamed .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { let field_ident = Ident::new(&format!("_{field_index}"), Span::call_site()); // Need to convert this to a `LitInt`, // because `quote` outputs the index as `0usize` instead of `0` let field_index = LitInt::new(&format!("{field_index}"), Span::call_site()); let field_ty = &field.ty; let resolve_method = resolve_mode.resolve_method(peace_params_path, &field_ident, field); tokens.extend(quote! { value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( String::from(stringify!(#field_index)), String::from(#peace_params_path::tynm::type_name::<#field_ty>())), ); #resolve_method value_resolution_ctx.pop(); }); tokens }, ) } Fields::Unit => proc_macro2::TokenStream::new(), } } /// Whether all `Params` values must be resolved. #[derive(Clone, Copy, Debug)] enum ResolveMode<'name> { /// Resolving all values for params. Full { params_name: &'name Ident }, /// Resolving whatever values are available. Partial { params_partial_name: &'name Ident }, } impl<'name> ResolveMode<'name> { /// Returns `params_name` for `Params` and `params_partial_name` for /// `Params::Partial`. fn params_return_type_name(self) -> &'name Ident { match self { Self::Full { params_name } => params_name, Self::Partial { params_partial_name, } => params_partial_name, } } // Returns `resolve` for `Full` resolution, and `resolve_partial` for `Partial` // resolution. fn resolve_method( self, peace_params_path: &Path, field_name: &Ident, field: &Field, ) -> proc_macro2::TokenStream { let field_ty = &field.ty; let field_spec_ty_path = field_spec_ty_path(peace_params_path, field_ty); match self { Self::Full { .. } => quote! { let #field_name = #field_spec_ty_path::resolve( #field_name, mapping_fn_reg, resources, value_resolution_ctx, )?; }, Self::Partial { .. } => quote! { let #field_name = #field_spec_ty_path::resolve_partial( #field_name, mapping_fn_reg, resources, value_resolution_ctx, )?; }, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/util.rs
crate/params_derive/src/util.rs
use proc_macro2::Span; use syn::{ meta::ParseNestedMeta, punctuated::Punctuated, AngleBracketedGenericArguments, Attribute, DeriveInput, Field, Fields, GenericArgument, GenericParam, Generics, Ident, LitInt, Path, PathArguments, PathSegment, ReturnType, Type, TypeGenerics, TypePath, Variant, WhereClause, WherePredicate, }; // Remember to update `params/src/std_impl.rs` when updating this. // // This can be replaced by `std::cell::OnceCell` when Rust 1.70.0 is released. static STD_LIB_TYPES: &[&str] = &[ "bool", "u8", "u16", "u32", "u64", "u128", "i8", "i16", "i32", "i64", "i128", "usize", "isize", "String", "PathBuf", #[cfg(not(target_arch = "wasm32"))] "OsString", "Option", "Vec", ]; /// Returns whether the type is annotated with `#[value_spec(fieldless)]`, /// which means its spec should be fieldless. /// /// This attribute must be: /// /// * attached to std library types defined outside the `peace_params` crate. /// * attached to each `Params`' field defined outside the item crate. pub fn is_fieldless_type(ast: &DeriveInput) -> bool { is_known_fieldless_std_lib_spec(&ast.ident) || is_tagged_fieldless(&ast.attrs) } /// Returns if the given `Type`'s spec should be fieldless. /// /// This applies to std library types, as well as non-`Path` types. fn is_known_fieldless_std_lib_spec(ty_name: &Ident) -> bool { STD_LIB_TYPES .iter() .any(|std_lib_type| ty_name == std_lib_type) } /// Returns whether any of the attributes contains `#[value_spec(fieldless)]`. /// /// This attribute should be: /// /// * attached to std library types defined outside the `peace_params` crate, if /// it isn't already covered by `STD_LIB_TYPES`. /// * attached to each field in `Params` that is defined outside the item crate. pub fn is_tagged_fieldless(attrs: &[Attribute]) -> bool { attrs.iter().any(|attr| { if attr.path().is_ident("value_spec") { let mut is_external = false; let _ = attr.parse_nested_meta(|parse_nested_meta| { is_external = parse_nested_meta.path.is_ident("fieldless"); Ok(()) }); is_external } else { false } }) } /// Returns whether the attribute is a `#[serde(bound = "..")]` attribute. pub fn is_serde_bound_attr(attr: &Attribute) -> bool { if attr.path().is_ident("serde") { let mut is_bound = false; let _ = attr.parse_nested_meta(|parse_nested_meta| { is_bound = parse_nested_meta.path.is_ident("bound"); Ok(()) }); is_bound } else { false } } /// Returns the `T: Serialize + DeserializeOwned` bounds to use for each type /// parameter. /// /// This will be either: /// /// * whatever is provided in a user specified `#[serde(bound = "..")]`, or /// * `T: Serialize + DeserializeOwned` if the bound has not been specified. pub fn serde_bounds_for_type_params(ast: &DeriveInput) -> Vec<WherePredicate> { let mut serde_bounds_for_type_params = ast.attrs.iter().map(serde_bounds).fold( None::<Vec<WherePredicate>>, |mut where_predicates_all, where_predicates_for_bound| { if let Some(where_predicates_all) = where_predicates_all.as_mut() { if let Some(where_predicates_for_bound) = where_predicates_for_bound { where_predicates_all.extend(where_predicates_for_bound); } } else if let Some(where_predicates_for_bound) = where_predicates_for_bound { where_predicates_all = Some(where_predicates_for_bound); } where_predicates_all }, ); if serde_bounds_for_type_params.is_none() { serde_bounds_for_type_params = Some( ast.generics .params .iter() .filter_map(|generic_param| match generic_param { GenericParam::Lifetime(_) => None, GenericParam::Type(type_param) => Some(type_param), GenericParam::Const(_) => None, }) .map(|type_param| { parse_quote! { #type_param: serde::Serialize + serde::de::DeserializeOwned } }) .collect::<Vec<WherePredicate>>(), ); } serde_bounds_for_type_params.unwrap_or_default() } /// Returns the where predicate within a `#[serde(bound = "WherePredicate")]` /// attribute. /// /// See [`serde_derive::internals::attr::parse_lit_into_where`][parse_lit_into_where]. /// /// [parse_lit_into_where]: https://github.com/serde-rs/serde/blob/3e4a23cbd064f983e0029404e69b1210d232f94f/serde_derive/src/internals/attr.rs#L1469 pub fn serde_bounds(attr: &Attribute) -> Option<Vec<WherePredicate>> { let mut where_predicates = None::<Vec<WherePredicate>>; if attr.path().is_ident("serde") { let _ = attr.parse_nested_meta(|parse_nested_meta| { if parse_nested_meta.path.is_ident("bound") { let string = match get_lit_str(&parse_nested_meta)? { Some(string) => string, None => return Ok(()), }; match string.parse_with(Punctuated::<WherePredicate, Token![,]>::parse_terminated) { Ok(predicates) => { if let Some(where_predicates) = where_predicates.as_mut() { where_predicates.extend(predicates); } else { where_predicates = Some(predicates.into_iter().collect::<Vec<WherePredicate>>()); } } Err(_error) => {} } } Ok(()) }); } where_predicates } fn get_lit_str(meta: &ParseNestedMeta) -> syn::Result<Option<syn::LitStr>> { let expr: syn::Expr = meta.value()?.parse()?; let mut value = &expr; while let syn::Expr::Group(e) = value { value = &e.expr; } if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = value { Ok(Some(lit.clone())) } else { Ok(None) } } /// Returns the value spec type for a value, e.g. `ParamsSpec<MyValue>` or /// `ParamsSpecFieldless<String>`. pub fn value_spec_ty( ast: &DeriveInput, ty_generics: &TypeGenerics, peace_params_path: &Path, impl_mode: ImplMode, ) -> proc_macro2::TokenStream { let value_name = &ast.ident; if is_fieldless_type(ast) || impl_mode == ImplMode::Fieldless { quote!(#peace_params_path::ParamsSpecFieldless<#value_name #ty_generics>) } else { quote!(#peace_params_path::ParamsSpec<#value_name #ty_generics>) } } /// Returns the value spec type for a value, e.g. `ParamsSpec::<MyValue>` or /// `ParamsSpecFieldless::<String>`. pub fn value_spec_ty_path( ast: &DeriveInput, ty_generics: &TypeGenerics, peace_params_path: &Path, impl_mode: ImplMode, ) -> proc_macro2::TokenStream { let value_name = &ast.ident; if is_fieldless_type(ast) || impl_mode == ImplMode::Fieldless { quote!(#peace_params_path::ParamsSpecFieldless::<#value_name #ty_generics>) } else { quote!(#peace_params_path::ParamsSpec::<#value_name #ty_generics>) } } /// Returns the type of a value spec field, e.g. `ParamsSpecFieldless<MyValue>`. pub fn field_spec_ty(peace_params_path: &Path, field_ty: &Type) -> proc_macro2::TokenStream { quote!(#peace_params_path::ValueSpec<#field_ty>) } /// Returns the type of a value spec field, e.g. /// `ParamsSpecFieldless::<MyValue>`. pub fn field_spec_ty_path(peace_params_path: &Path, field_ty: &Type) -> proc_macro2::TokenStream { quote!(#peace_params_path::ValueSpec::<#field_ty>) } /// Returns the type of a value spec field, e.g. /// `ParamsSpecFieldless::<MyValue>(#field_name)` or /// `ParamsSpecFieldless::<MyValue>(FieldTypeWrapper(#field_name))`. pub fn field_spec_ty_deconstruct( peace_params_path: &Path, field_name: &Ident, ) -> proc_macro2::TokenStream { quote!(#peace_params_path::ValueSpec::Value { value: #field_name }) } /// Returns whether the given field is a `PhantomData`. pub fn is_phantom_data(field_ty: &Type) -> bool { matches!(&field_ty, Type::Path(TypePath { path, .. }) if matches!(path.segments.last(), Some(segment) if segment.ident == "PhantomData")) } /// Returns idents as `field_name_partial`. pub fn field_name_partial(field_name: &Ident) -> Ident { format_ident!("{}_partial", field_name) } /// Returns tuple idents as `_n` where `n` is the index of the field. pub fn tuple_ident_from_field_index(field_index: usize) -> Ident { Ident::new(&format!("_{field_index}"), Span::call_site()) } /// Returns tuple idents as `_n` where `n` is the index of the field. pub fn tuple_index_from_field_index(field_index: usize) -> LitInt { // Need to convert this to a `LitInt`, // because `quote` outputs a usize index as `0usize` instead of `0` LitInt::new(&format!("{field_index}"), Span::call_site()) } /// Returns a comma separated list of deconstructed fields. /// /// Tuple fields are returned as `_n`, and marker fields are returned as /// `::std::marker::PhantomData`. pub fn fields_deconstruct(fields: &Fields) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain(fields, false) } /// Returns a comma separated list of deconstructed fields, with a `_partial` /// suffix. /// /// Named fields are returned as `field_name_partial`, whose type is /// `Option<T>`. /// /// Tuple fields are returned as `_n_partial`, and marker fields are returned as /// `::std::marker::PhantomData`. pub fn fields_deconstruct_partial(fields: &Fields) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain_map( fields, false, Some(|field_name| { let field_name_partial = field_name_partial(field_name); quote!(#field_name_partial) }), ) } /// Returns a comma separated list of deconstructed fields, deconstructed as /// `field: Some(field)`. /// /// Tuple fields are returned as `Some(_n)`, and marker fields are returned as /// `::std::marker::PhantomData`. pub fn fields_deconstruct_some(fields: &Fields) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain_map(fields, false, Some(|field_name| quote!(Some(#field_name)))) } /// Returns a comma separated list of deconstructed fields, deconstructed as /// `field: None`. /// /// Tuple fields are returned as `None`, and marker fields are returned as /// `::std::marker::PhantomData`. pub fn fields_deconstruct_none(fields: &Fields) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain_map(fields, false, Some(|_field_name| quote!(None))) } /// Returns a comma separated list of deconstructed fields, deconstructed as /// `field: field_other`. /// /// Tuple fields are returned as `_n_other`, and marker fields are returned as /// `::std::marker::PhantomData`. pub fn fields_deconstruct_rename_other(fields: &Fields) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain_map( fields, false, Some(|field_name| { let field_name_other = format_ident!("{}_other", field_name); quote!(#field_name_other) }), ) } pub fn fields_deconstruct_retain( fields: &Fields, retain_phantom_data: bool, ) -> Vec<proc_macro2::TokenStream> { fields_deconstruct_retain_map(fields, retain_phantom_data, None) } fn fields_deconstruct_retain_map( fields: &Fields, retain_phantom_data: bool, fn_ident_map: Option<fn(&Ident) -> proc_macro2::TokenStream>, ) -> Vec<proc_macro2::TokenStream> { fields .iter() .enumerate() .map(|(field_index, field)| { if !retain_phantom_data && is_phantom_data(&field.ty) { if let Some(field_ident) = field.ident.as_ref() { quote!(#field_ident: ::std::marker::PhantomData) } else { quote!(::std::marker::PhantomData) } } else if let Some(field_ident) = field.ident.as_ref() { if let Some(fn_ident_map) = fn_ident_map { let field_further_deconstructed = fn_ident_map(field_ident); quote!(#field_ident: #field_further_deconstructed) } else { quote!(#field_ident) } } else { let field_ident = tuple_ident_from_field_index(field_index); if let Some(fn_ident_map) = fn_ident_map { fn_ident_map(&field_ident) } else { quote!(#field_ident) } } }) .collect::<Vec<proc_macro2::TokenStream>>() } /// Returns the intersection of parent type arguments and variant field types. /// /// This is the part between the angle brackets -- `T1, T2, ..`. /// /// Note: This doesn't copy across any `WherePredicate`s. See /// `variant_generics_where_clause` below. pub fn variant_generics_intersect( parent_generics: &Generics, variant: &Variant, ) -> Vec<GenericParam> { let field_generics_maybe = variant .fields .iter() .flat_map(|field| field_generics_maybe(&field.ty)); field_generics_maybe .filter(|field_generic| { parent_generics .params .iter() .any(|parent_generic_param| field_generic == parent_generic_param) }) .collect::<Vec<GenericParam>>() } /// Returns the where clause to apply to an enum variant pub fn variant_generics_where_clause( parent_generics: &Generics, variant_generics: &[GenericParam], ) -> Option<WhereClause> { let filtered_predicates = parent_generics.where_clause.as_ref().map(|where_clause| { where_clause .predicates .iter() .filter(|where_predicate| match where_predicate { WherePredicate::Lifetime(predicate_lifetime) => { variant_generics .iter() .any(|variant_generic| match variant_generic { GenericParam::Lifetime(variant_generic_lifetime) => { variant_generic_lifetime.lifetime == predicate_lifetime.lifetime } GenericParam::Type(_) | GenericParam::Const(_) => false, }) } WherePredicate::Type(predicate_type) => { variant_generics .iter() .any(|variant_generic| match variant_generic { GenericParam::Type(variant_generic_type) => { if let Type::Path(type_path) = &predicate_type.bounded_ty { type_path.path.is_ident(&variant_generic_type.ident) } else { false } } GenericParam::Lifetime(_) | GenericParam::Const(_) => false, }) } _ => false, }) }); filtered_predicates.map(|filtered_predicates| { parse_quote! { where #(#filtered_predicates,)* } }) } /// Returns the simple types found in this type. /// /// * If the type has no type parameters, then itself it returned. /// * If the type has type parameters, then its type parameters are returned. /// * This is applied recursively. fn field_generics_maybe(ty: &Type) -> Vec<GenericParam> { match ty { Type::Array(type_array) => field_generics_maybe(&type_array.elem), Type::BareFn(bare_fn) => { let output_types = match &bare_fn.output { ReturnType::Default => Vec::new(), ReturnType::Type(_r_arrow, return_type) => field_generics_maybe(return_type), }; bare_fn .inputs .iter() .flat_map(|fn_arg| field_generics_maybe(&fn_arg.ty)) .chain(output_types) .collect::<Vec<GenericParam>>() } Type::Group(type_group) => field_generics_maybe(&type_group.elem), Type::ImplTrait(_) => { unreachable!("Cannot have impl trait in field type position.") } Type::Infer(_) => unreachable!("Cannot have inferred type `_` in field type position."), Type::Macro(_) => Vec::new(), Type::Never(_) => Vec::new(), Type::Paren(type_paren) => field_generics_maybe(&type_paren.elem), Type::Path(type_path) => { if let Some(segment) = type_path.path.segments.last() { if let PathArguments::AngleBracketed(inner_args) = &segment.arguments { if inner_args.args.is_empty() { if type_path.path.segments.len() == 1 { // Return this type if there's no leading double colon, because a // leading double colon means it cannot be a type parameter. vec![parse_quote!(#ty)] } else { Vec::new() } } else { // Recurse inner_args .args .iter() .flat_map(|generic_arg| { match generic_arg { GenericArgument::Type(generic_ty) => { field_generics_maybe(generic_ty) } GenericArgument::Lifetime(lifetime) => { vec![parse_quote!(#lifetime)] } // GenericArgument::Const(_) | // GenericArgument::AssocType(_) | // GenericArgument::AssocConst(_) | // GenericArgument::Constraint(_) | _ => Vec::new(), } }) .collect::<Vec<GenericParam>>() } } else if type_path.path.segments.len() == 1 { // Return this type if there's no leading double colon, because a // leading double colon means it cannot be a type parameter. vec![parse_quote!(#ty)] } else { Vec::new() } } else { unreachable!("Field type must have at least one segment"); } } Type::Ptr(type_ptr) => field_generics_maybe(&type_ptr.elem), Type::Reference(type_reference) => field_generics_maybe(&type_reference.elem), Type::Slice(type_slice) => field_generics_maybe(&type_slice.elem), // trait objects with associated type params are not a likely use case Type::TraitObject(_) => Vec::new(), Type::Tuple(type_tuple) => type_tuple .elems .iter() .flat_map(field_generics_maybe) .collect::<Vec<GenericParam>>(), // Type::Verbatim(_) | _ => Vec::new(), } } /// Returns `let field_name = #expr;` where `expr` is determined by the provided /// function. /// /// `PhantomData` fields are skipped. pub fn fields_vars_map<'f>( fields: &'f Fields, fn_expr: impl Fn(&Field, &Ident) -> proc_macro2::TokenStream + 'f, ) -> impl Iterator<Item = proc_macro2::TokenStream> + 'f { fields_stmt_map(fields, move |field, field_name, _field_index| { let expr = fn_expr(field, field_name); quote!(let #field_name = #expr;) }) } /// Returns `#stmt` for each field, where `stmt` is determined by the provided /// function. /// /// * The `&Ident` passed into the closure is `_0` for tuple fields. /// * The `LitInt` passed into the closure is `0` for the tuple index. /// /// `PhantomData` fields are skipped. pub fn fields_stmt_map<'f>( fields: &'f Fields, fn_stmt: impl Fn(&Field, &Ident, LitInt) -> proc_macro2::TokenStream + 'f, ) -> impl Iterator<Item = proc_macro2::TokenStream> + 'f { fields .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .map(move |(field_index, field)| { let field_lit_int = tuple_index_from_field_index(field_index); if let Some(field_ident) = field.ident.as_ref() { fn_stmt(field, field_ident, field_lit_int) } else { let field_ident = tuple_ident_from_field_index(field_index); fn_stmt(field, &field_ident, field_lit_int) } }) } /// Generates an enum variant match arm. /// /// # Parameters /// /// * `enum_name`: e.g. `MyParams` /// * `variant`: Variant to generate the match arm for. /// * `fields_deconstructed`: Deconstructed fields of the variant. See /// [`fields_deconstruct`]. /// * `match_arm_body`: Tokens to insert as the match arm body. pub fn variant_match_arm( enum_name: &Ident, variant: &Variant, fields_deconstructed: &[proc_macro2::TokenStream], match_arm_body: proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { let variant_name = &variant.ident; match &variant.fields { Fields::Named(_fields_named) => { quote! { #enum_name::#variant_name { #(#fields_deconstructed),* } => { #match_arm_body } } } Fields::Unnamed(_) => { quote! { #enum_name::#variant_name(#(#fields_deconstructed),*) => { #match_arm_body } } } Fields::Unit => { quote! { #enum_name::#variant_name => { #match_arm_body } } } } } /// Generates an enum variant match arm. /// /// # Parameters /// /// * `enum_name`: e.g. `MyParams` /// * `enum_partial_name`: e.g. `MyParamsPartial` /// * `variant`: Variant to generate the match arm for. /// * `match_arm_body`: Tokens to insert as the match arm body. pub fn variant_and_partial_match_arm( enum_name: &Ident, enum_partial_name: &Ident, variant: &Variant, match_arm_body: proc_macro2::TokenStream, ) -> proc_macro2::TokenStream { let variant_name = &variant.ident; let fields_deconstructed = fields_deconstruct(&variant.fields); let fields_deconstructed_partial = fields_deconstruct_partial(&variant.fields); match &variant.fields { Fields::Named(_fields_named) => { quote! { ( #enum_name::#variant_name { #(#fields_deconstructed),* }, #enum_partial_name::#variant_name { #(#fields_deconstructed_partial),* }, ) => { #match_arm_body } } } Fields::Unnamed(_) => { quote! { ( #enum_name::#variant_name(#(#fields_deconstructed),*), #enum_partial_name::#variant_name(#(#fields_deconstructed_partial),*), ) => { #match_arm_body } } } Fields::Unit => { quote! { ( #enum_name::#variant_name, #enum_partial_name::#variant_name ) => {} } } } } /// Returns the reference `&Field` for any `Field`. /// /// This includes special handling for the following types: /// /// * `Option`: returns `Option<&Field>`. /// * `PathBuf`: returns `&Path`. /// * `Vec<T>`: returns `&[T]`. /// * `String`: returns `&str`. pub fn field_ty_to_ref_ty(field_ty: &Type, field_var: &proc_macro2::TokenStream) -> RefTypeAndExpr { if let Some((type_path, inner_args)) = type_path_simple_and_args(field_ty) { let type_name = &type_path.ident; if type_name == "Option" { if let Some(inner_args) = inner_args { if inner_args.args.len() == 1 { if let Some(GenericArgument::Type(inner_type)) = inner_args.args.first() { if let Some((inner_type_path, _inner_args)) = type_path_simple_and_args(inner_type) { let inner_type_name = &inner_type_path.ident; if inner_type_name == "String" { return RefTypeAndExpr { ref_type: parse_quote!(Option<&str>), ref_mut_type: parse_quote!(Option<&mut str>), ref_expr: parse_quote!(self.#field_var.as_deref()), ref_mut_expr: parse_quote!(self.#field_var.as_deref_mut()), }; } else if inner_type_name == "PathBuf" { // It's more useful to return a `&mut PathBuf` instead of a `&mut // Path`, as `PathBuf` has `.push()`. return RefTypeAndExpr { ref_type: parse_quote!(Option<&Path>), ref_mut_type: parse_quote!(Option<&mut PathBuf>), ref_expr: parse_quote!(self.#field_var.as_deref()), ref_mut_expr: parse_quote!(self.#field_var.as_mut()), }; } } return RefTypeAndExpr { ref_type: parse_quote!(Option<&#inner_type>), ref_mut_type: parse_quote!(Option<&mut #inner_type>), ref_expr: parse_quote!(self.#field_var.as_ref()), ref_mut_expr: parse_quote!(self.#field_var.as_mut()), }; } } } } else if type_name == "PathBuf" { return RefTypeAndExpr { ref_type: parse_quote!(&::std::path::Path), ref_mut_type: parse_quote!(&mut ::std::path::PathBuf), ref_expr: parse_quote!(self.#field_var.as_str()), ref_mut_expr: parse_quote!(self.#field_var.as_mut_str()), }; } else if type_name == "String" { return RefTypeAndExpr { ref_type: parse_quote!(&str), ref_mut_type: parse_quote!(&mut str), ref_expr: parse_quote!(self.#field_var.as_str()), ref_mut_expr: parse_quote!(self.#field_var.as_mut_str()), }; } } else if let Type::Reference(_) = field_ty { return RefTypeAndExpr { ref_type: parse_quote!(#field_ty), // no `&` prefix ref_mut_type: parse_quote!(&mut #field_ty), ref_expr: parse_quote!(&self.#field_var), ref_mut_expr: parse_quote!(&mut self.#field_var), }; } // By default, return `&#field_ty`. RefTypeAndExpr { ref_type: parse_quote!(&#field_ty), ref_mut_type: parse_quote!(&mut #field_ty), ref_expr: parse_quote!(&self.#field_var), ref_mut_expr: parse_quote!(&mut self.#field_var), } } pub fn type_path_simple_and_args( ty: &Type, ) -> Option<(&PathSegment, Option<&AngleBracketedGenericArguments>)> { if let Type::Path(type_path) = ty { if let Some(segment) = type_path.path.segments.last() { let arguments = if let PathArguments::AngleBracketed(inner_args) = &segment.arguments { Some(inner_args) } else { None }; return Some((segment, arguments)); } } None } /// Type of reference to return, and the expression to obtain it from the /// original object. pub struct RefTypeAndExpr { /// e.g. `&Field`, `&str` pub ref_type: Type, /// e.g. `&mut Field`, `&mut str` pub ref_mut_type: Type, /// e.g. `&field`, `field.as_ref()`, `field.as_deref()` pub ref_expr: proc_macro2::TokenStream, /// e.g. `&mut field`, `field.as_mut()` pub ref_mut_expr: proc_macro2::TokenStream, } /// Whether to implement a fieldwise or fieldless spec. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ImplMode { /// Fields of the value type are known and accessible. Fieldwise, /// Fields of the value type are unknown or inaccessible. Fieldless, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_field_wise_builder.rs
crate/params_derive/src/impl_field_wise_builder.rs
use proc_macro2::Span; use quote::ToTokens; use syn::{ Data, DataEnum, DeriveInput, Fields, Ident, ImplGenerics, Path, Type, TypeGenerics, WhereClause, }; use crate::{ field_wise_enum_builder_ctx::FieldWiseEnumBuilderCtx, fields_map::{field_to_optional_value_spec, fields_map, fields_to_optional_value_spec}, impl_default, type_gen::TypeGen, util::{ field_spec_ty_deconstruct, field_spec_ty_path, fields_deconstruct, fields_vars_map, is_phantom_data, tuple_ident_from_field_index, tuple_index_from_field_index, value_spec_ty, value_spec_ty_path, variant_generics_intersect, variant_generics_where_clause, ImplMode, }, }; /// `impl MyParamsFieldWiseBuilder`, so that Peace can resolve the params /// type as well as its values from the spec. pub fn impl_field_wise_builder( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, value_field_wise_name: &Ident, value_field_wise_builder_name: &Ident, impl_mode: ImplMode, field_wise_enum_builder_ctx: &FieldWiseEnumBuilderCtx, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; // enum builder should only expose builder methods for the variant it is in, // which means it needs a type state parameter for its variant. match &ast.data { Data::Struct(data_struct) => { let field_wise_builder = TypeGen::gen_from_value_type( ast, generics_split, value_field_wise_builder_name, |fields| fields_to_optional_value_spec(fields, peace_params_path), &[parse_quote! { #[doc="\ Builder for specification of how to look up the values for an item's \n\ parameters.\ "] }], false, ); // Note: struct builder has getters / setters generated in // `TypeGen::gen_from_value_type`. let impl_default = impl_default(ast, generics_split, value_field_wise_builder_name); let fields = &data_struct.fields; let builder_field_methods = builder_field_methods(fields, peace_params_path, None); let build_method_body = build_method_body( ast, ty_generics, peace_params_path, BuildMode::Struct { value_field_wise_name, }, fields, impl_mode, ); let value_spec_ty = value_spec_ty(ast, ty_generics, peace_params_path, impl_mode); quote! { #field_wise_builder #impl_default impl #impl_generics #value_field_wise_builder_name #ty_generics #where_clause { #builder_field_methods pub fn build(self) -> #value_spec_ty { #build_method_body } } } } Data::Enum(data_enum) => impl_enum_builder( ast, generics_split, peace_params_path, value_field_wise_name, value_field_wise_builder_name, field_wise_enum_builder_ctx, impl_mode, data_enum, ), Data::Union(_data_union) => quote!(), } } /// From a given enum: /// /// ```rust,ignore /// pub enum EnumParams<T1, T2> { /// Variant1 { /// field_1: T1, /// }, /// Variant2(T2), /// Variant3 /// } /// ``` /// /// Generates a builder like the following: /// /// ```rust,ignore /// pub struct EnumParamsBuilder<VariantSelection, T1, T2> { /// variant_selection: VariantSelection, /// marker: PhantomData<(T1, T2)>, /// } /// /// impl Default for EnumParamsBuilder<EnumParamsBuilderVariantNone> { /// fn default() -> Self { /// Self { variant_selection: EnumParamsBuilderVariantNone, } /// } /// } /// /// pub struct EnumParamsBuilderVariantNone; /// /// pub struct EnumParamsVariant1Builder<T1> { /// field_1: Option<T1>, /// } /// /// pub struct EnumParamsVariant2Builder<T2>(Option<T2>); /// ``` #[allow(clippy::too_many_arguments)] fn impl_enum_builder( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, value_field_wise_name: &Ident, value_field_wise_builder_name: &Ident, field_wise_enum_builder_ctx: &FieldWiseEnumBuilderCtx, impl_mode: ImplMode, data_enum: &DataEnum, ) -> proc_macro2::TokenStream { let variant_selection_ident = &Ident::new("variant_selection", Span::call_site()); let enum_builder_generics = &field_wise_enum_builder_ctx.generics; let enum_params_variant_none = &field_wise_enum_builder_ctx.variant_none; let ty_generics_idents = &field_wise_enum_builder_ctx.ty_generics_idents; let type_params_with_variant_none = &field_wise_enum_builder_ctx.type_params_with_variant_none; let (impl_generics, ty_generics, _where_clause) = generics_split; let (builder_impl_generics, builder_ty_generics, builder_where_clause) = enum_builder_generics.split_for_impl(); let value_spec_ty = value_spec_ty(ast, ty_generics, peace_params_path, impl_mode); let variant_selection_struct_tokenses = data_enum .variants .iter() .map(|variant| { let variant_name = &variant.ident; let fields = &variant.fields; let variant_name_snake_case = Ident::new( &format!("{}", heck::AsSnakeCase(format!("{variant_name}"))), Span::call_site(), ); let variant_selection_name = &format_ident!("{}Variant{}", value_field_wise_builder_name, variant_name); let variant_selection_ty_params = variant_generics_intersect(&ast.generics, variant); let variant_selection_ty_params_angle_bracketed = if variant_selection_ty_params.is_empty() { quote!() } else { quote!(<#(#variant_selection_ty_params,)*>) }; let variant_generics_where_clause = variant_generics_where_clause( &ast.generics, &variant_selection_ty_params ); let variant_selection_struct: DeriveInput = { let variant_selection_struct_fields = fields_map(fields, |field| { field_to_optional_value_spec(field, peace_params_path).to_token_stream() }); if matches!(&variant_selection_struct_fields, Fields::Named(_)) { parse_quote! { #[derive(Debug)] pub struct #variant_selection_name #variant_selection_ty_params_angle_bracketed #variant_generics_where_clause #variant_selection_struct_fields } } else { parse_quote! { #[derive(Debug)] pub struct #variant_selection_name #variant_selection_ty_params_angle_bracketed #variant_selection_struct_fields #variant_generics_where_clause; } } }; let variant_selection_generics_split = variant_selection_struct.generics.split_for_impl(); let impl_default = impl_default( &variant_selection_struct, &variant_selection_generics_split, variant_selection_name, ); let impl_builder_fns = { let builder_field_methods = builder_field_methods(fields, peace_params_path, None); let ( variant_selection_impl_generics, variant_selection_ty_generics, variant_selection_where_clause, ) = &variant_selection_generics_split; quote! { impl #variant_selection_impl_generics #variant_selection_name #variant_selection_ty_generics #variant_selection_where_clause { #builder_field_methods } } }; // The enum builder, with this variant selection selected as its first type param. let value_field_wise_builder_with_variant_selected = quote! { #value_field_wise_builder_name< #variant_selection_name #variant_selection_ty_params_angle_bracketed, #ty_generics_idents > }; let variant_builder_fn = quote! { pub fn #variant_name_snake_case(self) -> #value_field_wise_builder_with_variant_selected { #value_field_wise_builder_name { #variant_selection_ident: #variant_selection_name::default(), marker: ::std::marker::PhantomData, } } }; let proxy_impl_builder_fns = { let builder_field_methods = builder_field_methods( fields, peace_params_path, Some(variant_selection_ident), ); let build_method_body = build_method_body( ast, ty_generics, peace_params_path, BuildMode::Enum { value_field_wise_name, variant_name, variant_selection_name, variant_selection_ident, }, fields, impl_mode, ); // Note: We use `impl_generics` instead of `builder_impl_generics` // because we don't need the `VariantSelection` type parameter. quote! { impl #impl_generics #value_field_wise_builder_with_variant_selected #builder_where_clause { #builder_field_methods pub fn build(self) -> #value_spec_ty { #build_method_body } } } }; VariantSelectionStructTokens { struct_declaration: variant_selection_struct, impl_default, impl_builder_fns, variant_builder_fn, proxy_impl_builder_fns, } }) .collect::<Vec<VariantSelectionStructTokens>>(); let variant_selection_structs_and_impls = variant_selection_struct_tokenses .iter() .map(|variant_selection_struct_tokens| { let VariantSelectionStructTokens { struct_declaration, impl_default, impl_builder_fns, variant_builder_fn: _, proxy_impl_builder_fns, } = variant_selection_struct_tokens; quote! { #struct_declaration #impl_default #impl_builder_fns #proxy_impl_builder_fns } }); let variant_builder_fns = variant_selection_struct_tokenses .iter() .map(|variant_selection_struct_tokens| &variant_selection_struct_tokens.variant_builder_fn); let marker_type: Type = if ast.generics.params.is_empty() { parse_quote!(::std::marker::PhantomData<()>) } else { parse_quote!(::std::marker::PhantomData<(#ty_generics_idents)>) }; quote! { pub struct #value_field_wise_builder_name #builder_ty_generics { #variant_selection_ident: VariantSelection, marker: #marker_type, } impl #impl_generics ::std::default::Default for #value_field_wise_builder_name #type_params_with_variant_none #builder_where_clause { fn default() -> Self { #value_field_wise_builder_name { #variant_selection_ident: #enum_params_variant_none, marker: ::std::marker::PhantomData, } } } impl #builder_impl_generics #value_field_wise_builder_name #builder_ty_generics #builder_where_clause { #(#variant_builder_fns)* } // VariantSelections #[derive(Clone, Copy, Debug)] pub struct #enum_params_variant_none; #(#variant_selection_structs_and_impls)* } } /// Returns `with_field(mut self, value_spec: ValueSpec<FieldType>) -> Self` for /// all non-`PhantomData` fields. fn builder_field_methods( fields: &Fields, peace_params_path: &Path, proxy_field: Option<&Ident>, ) -> proc_macro2::TokenStream { let proxy_call = proxy_field.map(|proxy_field| quote!(.#proxy_field)); let fields_as_params = fields .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .map(|(field_index, field)| { let field_ty = &field.ty; let (self_field_name, field_name) = if let Some(field_ident) = field.ident.as_ref() { let self_field_name = field_ident.to_token_stream(); let field_name = field_ident.clone(); (self_field_name, field_name) } else { let self_field_name = tuple_index_from_field_index(field_index).to_token_stream(); let field_name = tuple_ident_from_field_index(field_index); (self_field_name, field_name) }; let field_spec_ty_path = field_spec_ty_path(peace_params_path, field_ty); let with_field_name = Ident::new(&format!("with_{self_field_name}"), Span::call_site()); let with_field_name_in_memory = Ident::new( &format!("with_{self_field_name}_in_memory"), Span::call_site(), ); let with_field_name_from_mapping_fn = Ident::new( &format!("with_{self_field_name}_from_mapping_fn"), Span::call_site(), ); let field_spec_ty_deconstruct = field_spec_ty_deconstruct(peace_params_path, &field_name); // Specifies how to determine the value of this field. // // # Example // // ```rust,ignore // let params_spec = FileDownloadParams::field_wise() // .with_src(Url::parse("https://../web_app.tar")) // direct value // .with_dest_from_mapping_fn(|workspace_dir: &WorkspaceDir| { // workspace.dir.join("web_app.tar") // }) // .build(); // // let mut cmd_ctx = // .. // .with_item_params::<_>(item_id, params_spec) // .await?; // ``` quote! { pub fn #with_field_name(mut self, #field_name: #field_ty) -> Self { self #proxy_call.#self_field_name = Some(#field_spec_ty_deconstruct); self } pub fn #with_field_name_in_memory(mut self) -> Self { self #proxy_call.#self_field_name = Some(#field_spec_ty_path::InMemory); self } pub fn #with_field_name_from_mapping_fn<MFns>(mut self, mapping_fn: MFns) -> Self where MFns: #peace_params_path::MappingFns, { self #proxy_call.#self_field_name = Some(#field_spec_ty_path::MappingFn { field_name: Some(String::from(stringify!(#field_name))), mapping_fn_id: mapping_fn.id(), }); self } } }) .collect::<Vec<proc_macro2::TokenStream>>(); quote! { #(#fields_as_params)* } } fn build_method_body( parent_ast: &DeriveInput, ty_generics: &TypeGenerics, peace_params_path: &Path, build_mode: BuildMode<'_>, fields: &Fields, impl_mode: ImplMode, ) -> proc_macro2::TokenStream { let value_spec_ty_path = value_spec_ty_path(parent_ast, ty_generics, peace_params_path, impl_mode); let fields_deconstruct = fields_deconstruct(fields); // let field_name = field_name.unwrap_or(ValueSpec::<FieldTy>::Stored); let fields_unwrap_to_value_spec_fieldless = fields_vars_map(fields, |field, field_name| { let field_ty = &field.ty; let field_spec_ty_path = field_spec_ty_path(peace_params_path, field_ty); quote! { #field_name.unwrap_or(#field_spec_ty_path::Stored) } }); let (deconstructed_type, deconstructed_object) = match build_mode { BuildMode::Struct { .. } => (quote!(Self), quote!(self)), BuildMode::Enum { variant_selection_name, variant_selection_ident, .. } => ( quote!(#variant_selection_name), quote!(self.#variant_selection_ident), ), }; let value_field_wise_type_or_variant = match build_mode { BuildMode::Struct { value_field_wise_name, } => quote!(#value_field_wise_name), BuildMode::Enum { value_field_wise_name, variant_name, variant_selection_name: _, variant_selection_ident: _, } => quote!(#value_field_wise_name::#variant_name), }; match fields { Fields::Named(_) => { quote! { let #deconstructed_type { #(#fields_deconstruct),* } = #deconstructed_object; #(#fields_unwrap_to_value_spec_fieldless)* let field_wise_spec = #value_field_wise_type_or_variant { #(#fields_deconstruct),* }; #value_spec_ty_path::FieldWise { field_wise_spec } } } Fields::Unnamed(_) => { quote! { let #deconstructed_type(#(#fields_deconstruct),*) = #deconstructed_object; #(#fields_unwrap_to_value_spec_fieldless)* let field_wise_spec = #value_field_wise_type_or_variant(#(#fields_deconstruct),*); #value_spec_ty_path::FieldWise { field_wise_spec } } } Fields::Unit => quote!(#value_spec_ty_path::FieldWise { field_wise_spec: #value_field_wise_type_or_variant, }), } } struct VariantSelectionStructTokens { /// AST of the variant selection struct. struct_declaration: DeriveInput, /// impl Default for `VariantSelectionStruct` impl_default: Option<proc_macro2::TokenStream>, /// Functions on the variant builder itself impl_builder_fns: proc_macro2::TokenStream, /// Function to return the variant builder, from the enum builder. variant_builder_fn: proc_macro2::TokenStream, /// Builder functions for the enum to proxy to the variant selection /// builder. proxy_impl_builder_fns: proc_macro2::TokenStream, } enum BuildMode<'name> { Struct { /// Name of the FieldWise type to build. value_field_wise_name: &'name Ident, }, Enum { /// Name of the FieldWise type to build. value_field_wise_name: &'name Ident, /// Variant within the type to build. variant_name: &'name Ident, /// Name of the variant selection type within the enum builder. variant_selection_name: &'name Ident, /// Name of the variant selection field within the enum builder. variant_selection_ident: &'name Ident, }, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_value_spec_rt_for_field_wise.rs
crate/params_derive/src/impl_value_spec_rt_for_field_wise.rs
use proc_macro2::Span; use syn::{ punctuated::Punctuated, DeriveInput, Field, Fields, Ident, ImplGenerics, LitInt, Path, TypeGenerics, Variant, WhereClause, }; use crate::util::{field_spec_ty, fields_deconstruct, is_phantom_data, variant_match_arm}; /// `impl ValueSpecRt for ValueSpec`, so that Peace can resolve the params type /// as well as its values from the spec. pub fn impl_value_spec_rt_for_field_wise( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, peace_resource_rt_path: &Path, params_name: &Ident, params_field_wise_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let resolve_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_resolve( params_name, params_field_wise_name, fields, peace_params_path, ResolveMode::Resolve, ) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_resolve( params_name, params_field_wise_name, variants, peace_params_path, ResolveMode::Resolve, ) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_resolve( params_name, params_field_wise_name, &fields, peace_params_path, ResolveMode::Resolve, ) } }; let try_resolve_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_resolve( params_name, params_field_wise_name, fields, peace_params_path, ResolveMode::TryResolve, ) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_resolve( params_name, params_field_wise_name, variants, peace_params_path, ResolveMode::TryResolve, ) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_resolve( params_name, params_field_wise_name, &fields, peace_params_path, ResolveMode::TryResolve, ) } }; quote! { impl #impl_generics #peace_params_path::ValueSpecRt for #params_field_wise_name #ty_generics #where_clause { type ValueType = #params_name #ty_generics; fn resolve( &self, mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<#params_name #ty_generics, #peace_params_path::ParamsResolveError> { #resolve_body } fn try_resolve( &self, mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<Option<#params_name #ty_generics>, #peace_params_path::ParamsResolveError> { #try_resolve_body } } } } fn struct_fields_resolve( params_name: &Ident, params_field_wise_name: &Ident, fields: &Fields, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { let fields_resolution = fields_resolution(fields, peace_params_path, resolve_mode); let fields_deconstructed = fields_deconstruct(fields); let return_expr = resolve_mode.return_expr(); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_field_wise_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // #fields_resolution // // let params = #params_name { // field_1, // field_2, // marker: PhantomData, // }; // // Ok(params) // or Ok(Some(params)) // ``` quote! { let #params_field_wise_name { #(#fields_deconstructed),* } = self; #fields_resolution let params = #params_name { #(#fields_deconstructed),* }; #return_expr } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_name(_0, _1, PhantomData,) = self; // // #fields_resolution // // let params = #params_name(_0, _1, PhantomData,); // Ok(params) // or Ok(Some(params)) // ``` quote! { let #params_field_wise_name(#(#fields_deconstructed),*) = self; #fields_resolution let params = #params_name(#(#fields_deconstructed),*); #return_expr } } Fields::Unit => quote! { let params = #params_name; #return_expr }, } } fn variants_resolve( params_name: &Ident, params_field_wise_name: &Ident, variants: &Punctuated<Variant, Token![,]>, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match self { // ValueSpec::Variant1 => Ok(Params::Variant1), // ValueSpec::Variant2(_0, _1, PhantomData) => { // let _0 = ..?; // let _1 = ..?; // let params = Params::Variant2(_0, _1, PhantomData); // Ok(params) // or Ok(Some(params)) // } // ValueSpec::Variant3 { field_1, field_2, marker: PhantomData } => { // #variant_fields_resolve // Ok(params) // or Ok(Some(params)) // } // } // ``` let variant_resolve_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let fields_deconstructed = fields_deconstruct(&variant.fields); let variant_fields_resolve = variant_fields_resolve( params_name, &variant.ident, &variant.fields, &fields_deconstructed, peace_params_path, resolve_mode, ); tokens.extend(variant_match_arm( params_field_wise_name, variant, &fields_deconstructed, variant_fields_resolve, )); tokens }); quote! { match self { #variant_resolve_arms } } } #[allow(clippy::too_many_arguments)] // Code gen, not user facing fn variant_fields_resolve( params_name: &Ident, variant_name: &Ident, fields: &Fields, fields_deconstructed: &[proc_macro2::TokenStream], peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { let fields_resolution = fields_resolution(fields, peace_params_path, resolve_mode); let return_expr = resolve_mode.return_expr(); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // #fields_resolution // // let params = #params_name::Variant { // field_1, // field_2, // marker: PhantomData, // }; // // Ok(params) // or Ok(Some(params)) // ``` quote! { #fields_resolution let params = #params_name::#variant_name { #(#fields_deconstructed),* }; #return_expr } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // #fields_resolution // // let params = #params_name::Variant(_0, _1, PhantomData,); // Ok(params) // or Ok(Some(params)) // ``` quote! { #fields_resolution let params = #params_name::#variant_name(#(#fields_deconstructed),*); #return_expr } } Fields::Unit => quote! { let params = #params_name::#variant_name; #return_expr }, } } fn fields_resolution( fields: &Fields, peace_params_path: &Path, resolve_mode: ResolveMode, ) -> proc_macro2::TokenStream { match fields { Fields::Named(fields_named) => { // Generates: // // ```rust // value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( // String::from(stringify!(field_1)), // String::from(#peace_params_path::tynm::type_name::<#field_ty>())), // ); // let field_1 = field_1.resolve(resources, value_resolution_ctx)?; // value_resolution_ctx.pop(); // ``` fields_named .named .iter() .filter(|field| !is_phantom_data(&field.ty)) .filter_map(|field| field.ident.as_ref().map(|field_name| (field, field_name))) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field, field_name)| { let field_ty = &field.ty; let resolve_value = resolve_mode.resolve_value(peace_params_path, field_name, field); tokens.extend(quote! { value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( String::from(stringify!(#field_name)), String::from(#peace_params_path::tynm::type_name::<#field_ty>())), ); #resolve_value value_resolution_ctx.pop(); }); tokens }, ) } Fields::Unnamed(fields_unnamed) => { // Generates: // // ```rust // value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( // String::from(stringify!(1)), // String::from(#peace_params_path::tynm::type_name::<#field_ty>())), // ); // let _1 = _1.resolve(resources, value_resolution_ctx)?; // value_resolution_ctx.pop(); // ``` fields_unnamed .unnamed .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { let field_ident = Ident::new(&format!("_{field_index}"), Span::call_site()); // Need to convert this to a `LitInt`, // because `quote` outputs the index as `0usize` instead of `0` let field_index = LitInt::new(&format!("{field_index}"), Span::call_site()); let field_ty = &field.ty; let resolve_value = resolve_mode.resolve_value(peace_params_path, &field_ident, field); tokens.extend(quote! { value_resolution_ctx.push(#peace_params_path::FieldNameAndType::new( String::from(stringify!(#field_index)), String::from(#peace_params_path::tynm::type_name::<#field_ty>())), ); #resolve_value value_resolution_ctx.pop(); }); tokens }, ) } Fields::Unit => proc_macro2::TokenStream::new(), } } /// Whether all `Params` values must be resolved. #[derive(Clone, Copy, Debug)] enum ResolveMode { /// Resolving all values for params. Resolve, /// Resolving whatever values are available. TryResolve, } impl ResolveMode { // Returns `resolve` for `Full` resolution, and `try_resolve` for `Partial` // resolution. fn resolve_value( self, peace_params_path: &Path, field_name: &Ident, field: &Field, ) -> proc_macro2::TokenStream { let field_spec_ty = field_spec_ty(peace_params_path, &field.ty); match self { Self::Resolve => quote! { let #field_name = <#field_spec_ty as #peace_params_path::ValueSpecRt> ::resolve(#field_name, mapping_fn_reg, resources, value_resolution_ctx)?.into(); }, Self::TryResolve => quote! { let #field_name = <#field_spec_ty as #peace_params_path::ValueSpecRt> ::try_resolve(#field_name, mapping_fn_reg, resources, value_resolution_ctx)? .map(::std::convert::TryFrom::try_from) .and_then(::std::result::Result::ok); let Some(#field_name) = #field_name else { return Ok(None); }; }, } } fn return_expr(self) -> proc_macro2::TokenStream { match self { Self::Resolve => quote! { Ok(params) }, Self::TryResolve => quote! { Ok(Some(params)) }, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/type_gen.rs
crate/params_derive/src/type_gen.rs
use proc_macro2::Span; use quote::ToTokens; use syn::{ punctuated::Punctuated, Attribute, DeriveInput, Fields, Ident, ImplGenerics, TypeGenerics, Variant, Visibility, WhereClause, }; use crate::util::{ field_ty_to_ref_ty, fields_deconstruct, fields_deconstruct_retain, is_phantom_data, is_serde_bound_attr, tuple_ident_from_field_index, tuple_index_from_field_index, variant_match_arm, RefTypeAndExpr, }; pub struct TypeGen; impl TypeGen { /// Generates a type based off the `Params` / `Value` type. /// /// # Parameters /// /// * `ast`: The `Params` type. /// * `generics_split`: Generics of the `Params` type. /// * `type_name`: Name of the type to generate. /// * `fields_map`: Transformation function to apply to the type of the /// fields. /// * `attrs_to_add`: Attributes to attach to the generated type. pub fn gen_from_value_type<F>( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), type_name: &Ident, fields_map: F, attrs_to_add: &[Attribute], generated_type_is_serializable: bool, ) -> proc_macro2::TokenStream where F: Fn(&mut Fields), { let (impl_generics, ty_generics, where_clause) = generics_split; let serde_bound_empty = parse_quote!(#[serde(bound = "")]); let serde_bound_attrs = if generated_type_is_serializable { let mut serde_bound_attrs = ast .attrs .iter() .filter(|attr| is_serde_bound_attr(attr)) .collect::<Vec<&Attribute>>(); if serde_bound_attrs.is_empty() { serde_bound_attrs.push(&serde_bound_empty); } serde_bound_attrs } else { Vec::new() }; match &ast.data { syn::Data::Struct(data_struct) => { let mut fields = data_struct.fields.clone(); fields_map(&mut fields); let struct_definition = if matches!(&fields, Fields::Unnamed(_) | Fields::Unit) { quote! { pub struct #type_name #ty_generics #fields #where_clause; } } else { quote! { pub struct #type_name #ty_generics #where_clause #fields } }; let struct_constructor = Self::struct_constructor(type_name, &fields); let struct_fields_clone = Self::struct_fields_clone(type_name, &fields); let struct_fields_debug = Self::struct_fields_debug(type_name, &fields); let struct_getters_and_mut_getters = Self::struct_getters_and_mut_getters(&fields); quote! { #(#attrs_to_add)* #(#serde_bound_attrs)* #struct_definition impl #impl_generics #type_name #ty_generics #where_clause { #struct_constructor #struct_getters_and_mut_getters } impl #impl_generics ::std::clone::Clone for #type_name #ty_generics #where_clause { fn clone(&self) -> Self { #struct_fields_clone } } impl #impl_generics ::std::fmt::Debug for #type_name #ty_generics #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { #struct_fields_debug } } } } syn::Data::Enum(data_enum) => { let mut variants = data_enum.variants.clone(); variants.iter_mut().for_each(|variant| { fields_map(&mut variant.fields); }); let variants_clone = Self::variants_clone(&variants); let variants_debug = Self::variants_debug(&variants); quote! { #(#attrs_to_add)* #(#serde_bound_attrs)* pub enum #type_name #ty_generics #where_clause { #variants } impl #impl_generics ::std::clone::Clone for #type_name #ty_generics #where_clause { fn clone(&self) -> Self { #variants_clone } } impl #impl_generics ::std::fmt::Debug for #type_name #ty_generics #where_clause { fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { #variants_debug } } } } syn::Data::Union(data_union) => { let mut fields = Fields::from(data_union.fields.clone()); fields_map(&mut fields); quote! { #(#attrs_to_add)* #(#serde_bound_attrs)* pub union #type_name #ty_generics #where_clause #fields } } } } /// Returns tokens for a constructor `Struct::new(..)` if any fields are /// non-pub, or there are phantom data fields. pub fn struct_constructor( type_name: &Ident, fields: &Fields, ) -> Option<proc_macro2::TokenStream> { let constructor_needed = fields.iter().any(|field| { is_phantom_data(&field.ty) || matches!(field.vis, Visibility::Restricted(_) | Visibility::Inherited) }); if constructor_needed { let constructor_doc = format!("Returns a new `{type_name}`."); let fields_deconstructed = fields_deconstruct(fields); let fields_as_params = fields .iter() .enumerate() .filter(|(_field_index, field)| !is_phantom_data(&field.ty)) .map(|(field_index, field)| { let field_name = if let Some(field_ident) = field.ident.as_ref() { quote!(#field_ident) } else { let field_ident = tuple_ident_from_field_index(field_index); quote!(#field_ident) }; let field_ty = &field.ty; quote!(#field_name: #field_ty) }) .collect::<Vec<proc_macro2::TokenStream>>(); let constructor = match fields { Fields::Named(_fields_named) => quote! { Self { #(#fields_deconstructed),* } }, Fields::Unnamed(_fields_unnamed) => quote! { Self(#(#fields_deconstructed),*) }, Fields::Unit => unreachable!("Guarded by `constructor_needed`."), }; Some(quote! { #[doc = #constructor_doc] pub fn new(#(#fields_as_params),*) -> Self { #constructor } }) } else { None } } /// Returns `field(&self) -> &Field` and `field_mut(&mut self) -> &mut /// Field` for any fields that are non-pub. /// /// This includes special handling for the following types: /// /// * `Option`: returns `Option<&Field>`. /// * `PathBuf`: returns `&Path`. /// * `Vec<T>`: returns `&[T]`. /// * `String`: returns `&str`. pub fn struct_getters_and_mut_getters(fields: &Fields) -> proc_macro2::TokenStream { let fields_as_params = fields .iter() .enumerate() .filter(|(_field_index, field)| { !is_phantom_data(&field.ty) && matches!(field.vis, Visibility::Restricted(_) | Visibility::Inherited) }) .map(|(field_index, field)| { let (self_field_name, field_name) = if let Some(field_ident) = field.ident.as_ref() { let self_field_name = field_ident.to_token_stream(); let field_name = self_field_name.clone(); (self_field_name, field_name) } else { let self_field_name = tuple_index_from_field_index(field_index).to_token_stream(); let field_name = tuple_ident_from_field_index(field_index).to_token_stream(); (self_field_name, field_name) }; let field_name_mut = Ident::new(&format!("{field_name}_mut"), Span::call_site()); let RefTypeAndExpr { ref_type, ref_mut_type, ref_expr, ref_mut_expr, } = field_ty_to_ref_ty(&field.ty, &self_field_name); quote! { pub fn #field_name(&self) -> #ref_type { #ref_expr } pub fn #field_name_mut(&mut self) -> #ref_mut_type { #ref_mut_expr } } }) .collect::<Vec<proc_macro2::TokenStream>>(); quote! { #(#fields_as_params)* } } pub fn struct_fields_clone(type_name: &Ident, fields: &Fields) -> proc_macro2::TokenStream { match fields { Fields::Named(fields_named) => { // Generates: // // #type_name { // field_1: self.field_1.clone(), // field_2: self.field_2.clone(), // marker: PhantomData, // } let fields_clone = fields_named.named.iter().fold( proc_macro2::TokenStream::new(), |mut tokens, field| { if let Some(field_name) = field.ident.as_ref() { if is_phantom_data(&field.ty) { tokens.extend(quote! { #field_name: std::marker::PhantomData, }); } else { tokens.extend(quote! { #field_name: self.#field_name.clone(), }); } } tokens }, ); quote! { #type_name { #fields_clone } } } Fields::Unnamed(fields_unnamed) => { // Generates: // // #type_name(self.0.clone(), self.1.clone(), PhantomData) let fields_clone = fields_unnamed.unnamed.iter().enumerate().fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { let field_index = tuple_index_from_field_index(field_index); if is_phantom_data(&field.ty) { tokens.extend(quote!(std::marker::PhantomData,)); } else { tokens.extend(quote!(self.#field_index.clone(),)); } tokens }, ); quote! { #type_name(#fields_clone) } } Fields::Unit => quote!(#type_name), } } pub fn variants_clone(variants: &Punctuated<Variant, Token![,]>) -> proc_macro2::TokenStream { // Generates: // // match self { // Self::Variant1 => Self::Variant1, // Self::Variant2(_0, _1, PhantomData) => { // Self::Variant2(_0.clone(), _1.clone(), PhantomData) // } // Self::Variant3 { field_1, field_2, marker: PhantomData } => { // Self::Variant3 { // field_1: field_1.clone(), // field_2: field_2.clone(), // marker: PhantomData, // } // } // } let self_ident = Ident::new("Self", Span::call_site()); let variant_clone_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let variant_fields = fields_deconstruct(&variant.fields); let variant_fields_clone = Self::variant_fields_clone(&variant.ident, &variant.fields); tokens.extend(variant_match_arm( &self_ident, variant, &variant_fields, variant_fields_clone, )); tokens }); quote! { match self { #variant_clone_arms } } } pub fn variant_fields_clone(variant_name: &Ident, fields: &Fields) -> proc_macro2::TokenStream { match fields { Fields::Named(fields_named) => { // Generates: // // Self { // field_1: field_1.clone(), // field_2: field_2.clone(), // marker: PhantomData, // } let fields_clone = fields_named.named.iter().fold( proc_macro2::TokenStream::new(), |mut tokens, field| { if let Some(field_name) = field.ident.as_ref() { if is_phantom_data(&field.ty) { tokens.extend(quote! { #field_name: std::marker::PhantomData, }); } else { tokens.extend(quote! { #field_name: #field_name.clone(), }); } } tokens }, ); quote! { Self::#variant_name { #fields_clone } } } Fields::Unnamed(fields_unnamed) => { // Generates: // // Self(_0.clone(), _1.clone(), PhantomData) let fields_clone = fields_unnamed .unnamed .iter() .enumerate() .map(|(field_index, field)| (tuple_ident_from_field_index(field_index), field)) .fold( proc_macro2::TokenStream::new(), |mut tokens, (field_index, field)| { if is_phantom_data(&field.ty) { tokens.extend(quote!(std::marker::PhantomData,)); } else { tokens.extend(quote!(#field_index.clone(),)); } tokens }, ); quote! { Self::#variant_name(#fields_clone) } } Fields::Unit => quote!(Self::#variant_name), } } pub fn variants_debug(variants: &Punctuated<Variant, Token![,]>) -> proc_macro2::TokenStream { // Generates: // // match self { // Self::Variant1 => f.debug_struct("Variant1").finish(), // Self::Variant2 => f.debug_tuple("Variant2").finish(), // Self::Variant3 { .. } => f.debug_struct("Variant3").field(..).finish(), // } let self_ident = Ident::new("Self", Span::call_site()); let variant_debug_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { // This differs from `crate::util::fields_deconstruct` in that // this retains `PhantomData` fields. let variant_fields = fields_deconstruct_retain(&variant.fields, true); let variant_fields_debug = Self::fields_debug(&variant.ident, &variant.fields); tokens.extend(variant_match_arm( &self_ident, variant, &variant_fields, variant_fields_debug, )); tokens }); quote! { match self { #variant_debug_arms } } } pub fn struct_fields_debug(type_name: &Ident, fields: &Fields) -> proc_macro2::TokenStream { let fields_debug = Self::fields_debug(type_name, fields); let fields_deconstructed = fields_deconstruct_retain(fields, true); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #type_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // #fields_debug // ``` quote! { let #type_name { #(#fields_deconstructed),* } = self; #fields_debug } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #type_name(_0, _1, PhantomData,) = self; // // #fields_debug // ``` quote! { let #type_name(#(#fields_deconstructed),*) = self; #fields_debug } } Fields::Unit => fields_debug, } } pub fn fields_debug(type_name: &Ident, fields: &Fields) -> proc_macro2::TokenStream { let type_name = &type_name.to_string(); match fields { Fields::Named(fields_named) => { // Generates: // // let mut debug_struct = f.debug_struct(#type_name); // debug_struct.field("field_0", &field_0); // debug_struct.field("field_1", &field_1); // debug_struct.finish() let tokens = quote! { let mut debug_struct = f.debug_struct(#type_name); }; let mut tokens = fields_named.named.iter().fold(tokens, |mut tokens, field| { if let Some(field_name) = field.ident.as_ref() { let field_name_str = &field_name.to_string(); tokens.extend(quote! { debug_struct.field(#field_name_str, &#field_name); }); } tokens }); tokens.extend(quote!(debug_struct.finish())); tokens } Fields::Unnamed(fields_unnamed) => { // Generates: // // let mut debug_tuple = f.debug_tuple(#type_name); // debug_tuple.field(&_0); // debug_tuple.field(&_1); // debug_tuple.finish() let tokens = quote! { let mut debug_tuple = f.debug_tuple(#type_name); }; let mut tokens = (0..fields_unnamed.unnamed.len()) .map(tuple_ident_from_field_index) .fold(tokens, |mut tokens, field_index| { tokens.extend(quote! { debug_tuple.field(&#field_index); }); tokens }); tokens.extend(quote!(debug_tuple.finish())); tokens } Fields::Unit => quote!(f.debug_struct(#type_name).finish()), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_field_wise_spec_rt_for_field_wise_external.rs
crate/params_derive/src/impl_field_wise_spec_rt_for_field_wise_external.rs
use syn::{Ident, ImplGenerics, Path, TypeGenerics, WhereClause}; /// `impl FieldWiseSpecRt for ValueSpec`, so that Peace can resolve the params /// type as well as its values from the spec. pub fn impl_field_wise_spec_rt_for_field_wise_external( generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, peace_resource_rt_path: &Path, params_name: &Ident, params_field_wise_name: &Ident, params_partial_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; quote! { impl #impl_generics #peace_params_path::FieldWiseSpecRt for #params_field_wise_name #ty_generics #where_clause { type ValueType = #params_name #ty_generics; type Partial = #params_partial_name #ty_generics; fn resolve( &self, _mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<#params_name #ty_generics, #peace_params_path::ParamsResolveError> { if let Some(params) = self.0.as_ref() { Ok(params.clone()) } else { match resources.try_borrow::<#params_name #ty_generics>() { Ok(t) => Ok((&*t).clone()), Err(borrow_fail) => match borrow_fail { #peace_resource_rt_path::BorrowFail::ValueNotFound => { Err(#peace_params_path::ParamsResolveError::InMemory { value_resolution_ctx: value_resolution_ctx.clone(), }) } #peace_resource_rt_path::BorrowFail::BorrowConflictImm | #peace_resource_rt_path::BorrowFail::BorrowConflictMut => { Err(#peace_params_path::ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx: value_resolution_ctx.clone(), }) } }, } } } fn resolve_partial( &self, _mapping_fn_reg: &#peace_params_path::MappingFnReg, resources: &#peace_resource_rt_path::Resources<#peace_resource_rt_path::resources::ts::SetUp>, value_resolution_ctx: &mut #peace_params_path::ValueResolutionCtx, ) -> Result<#params_partial_name #ty_generics, #peace_params_path::ParamsResolveError> { if let Some(params) = self.0.as_ref() { Ok(params.clone().into()) } else { match resources.try_borrow::<#params_name #ty_generics>() { Ok(t) => Ok((&*t).clone().into()), Err(borrow_fail) => match borrow_fail { #peace_resource_rt_path::BorrowFail::ValueNotFound => { Err(#peace_params_path::ParamsResolveError::InMemory { value_resolution_ctx: value_resolution_ctx.clone(), }) } #peace_resource_rt_path::BorrowFail::BorrowConflictImm | #peace_resource_rt_path::BorrowFail::BorrowConflictMut => { Err(#peace_params_path::ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx: value_resolution_ctx.clone(), }) } }, } } } } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_any_spec_rt_for_field_wise.rs
crate/params_derive/src/impl_any_spec_rt_for_field_wise.rs
use syn::{DeriveInput, Ident, ImplGenerics, Path, TypeGenerics, WhereClause}; use crate::{spec_is_usable::is_usable_body, spec_merge::spec_merge}; /// `impl AnySpecRt for ValueSpec`, so that Peace can tell if a spec is usable, /// and merge provided and stored params together. pub fn impl_any_spec_rt_for_field_wise( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, params_field_wise_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let is_usable_body = is_usable_body(ast, params_field_wise_name, peace_params_path); let spec_merge = spec_merge(ast, params_field_wise_name, peace_params_path); quote! { impl #impl_generics #peace_params_path::AnySpecRt for #params_field_wise_name #ty_generics #where_clause { fn is_usable(&self) -> bool { #is_usable_body } #spec_merge } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/impl_params_merge_ext_for_params.rs
crate/params_derive/src/impl_params_merge_ext_for_params.rs
use syn::{ punctuated::Punctuated, DeriveInput, Fields, Ident, ImplGenerics, Path, TypeGenerics, Variant, WhereClause, }; use crate::util::{ field_name_partial, fields_deconstruct, fields_deconstruct_partial, is_phantom_data, tuple_ident_from_field_index, variant_and_partial_match_arm, }; /// `impl ParamsMergeExt for Params`, so that the framework can run /// `params_example.merge(params_partial_current)` in `Item::try_state_*` /// without needing to deconstruct the `Params::Partial`. pub fn impl_params_merge_ext_for_params( ast: &DeriveInput, generics_split: &(ImplGenerics, TypeGenerics, Option<&WhereClause>), peace_params_path: &Path, params_name: &Ident, params_partial_name: &Ident, ) -> proc_macro2::TokenStream { let (impl_generics, ty_generics, where_clause) = generics_split; let params_merge_body = match &ast.data { syn::Data::Struct(data_struct) => { let fields = &data_struct.fields; struct_fields_merge_partial(params_name, params_partial_name, fields) } syn::Data::Enum(data_enum) => { let variants = &data_enum.variants; variants_merge_partial(params_name, params_partial_name, variants) } syn::Data::Union(data_union) => { let fields = Fields::from(data_union.fields.clone()); struct_fields_merge_partial(params_name, params_partial_name, &fields) } }; let mut generics_for_ref = ast.generics.clone(); generics_for_ref.params.insert(0, parse_quote!('partial)); quote! { impl #impl_generics #peace_params_path::ParamsMergeExt for #params_name #ty_generics #where_clause { fn merge(&mut self, params_partial: #params_partial_name #ty_generics) { #params_merge_body } } } } fn struct_fields_merge_partial( params_name: &Ident, params_partial_name: &Ident, fields: &Fields, ) -> proc_macro2::TokenStream { let fields_deconstructed = fields_deconstruct(fields); let fields_deconstructed_partial = fields_deconstruct_partial(fields); let fields_merge_partial = fields_merge_partial(fields); match fields { Fields::Named(_fields_named) => { // Generates: // // ```rust // let #params_partial_name { // field_1, // field_2, // marker: PhantomData, // } = self; // // let #params_partial_name { // field_1: field_1_partial, // field_2: field_2_partial, // marker: PhantomData, // } = params_partial; // // if let Some(field_1_partial) = field_1_partial { // *field_1 = field_1_partial; // } // if let Some(field_2_partial) = field_2_partial { // *field_2 = field_2_partial; // } // ``` quote! { let #params_name { #(#fields_deconstructed),* } = self; let #params_partial_name { #(#fields_deconstructed_partial),* } = params_partial; #fields_merge_partial } } Fields::Unnamed(_fields_unnamed) => { // Generates: // // ```rust // let #params_partial_name( // _0, // _1, // PhantomData, // ) = self; // // let #params_partial_name( // _0_partial, // _1_partial, // PhantomData, // ) = params_partial; // // if let Some(_0_partial) = _0_partial { // *_0 = _0_partial; // } // if let Some(_1_partial) = _1_partial { // *_1 = _1_partial; // } // ``` quote! { let #params_name(#(#fields_deconstructed),*) = self; let #params_partial_name(#(#fields_deconstructed_partial),*) = params_partial; #fields_merge_partial } } Fields::Unit => proc_macro2::TokenStream::new(), } } fn variants_merge_partial( params_name: &Ident, params_partial_name: &Ident, variants: &Punctuated<Variant, Token![,]>, ) -> proc_macro2::TokenStream { // Generates: // // ```rust // match (self, params_partial) { // ( // #params_name::Variant1, // #params_partial_name::Variant1 // ) => {} // ( // #params_name::Variant2(_0, _1, PhantomData), // #params_partial_name::Variant2(_0_partial, _1_partial, PhantomData), // ) => { // if let Some(_0_partial) = _0_partial { // *_0 = _0_partial; // } // if let Some(_1_partial) = _1_partial { // *_1 = _1_partial; // } // } // ( // #params_name::Variant3 { // field_1, // field_2, // marker: PhantomData, // }, // #params_partial_name::Variant3 { // field_1: field_1_partial, // field_2: field_2_partial, // marker: PhantomData, // }, // ) => { // if let Some(field_1_partial) = field_1_partial { // *field_1 = field_1_partial; // } // if let Some(field_2_partial) = field_2_partial { // *field_2 = field_2_partial; // } // } // _ => {} // Merging different variants is not supported. // } // ``` let variant_merge_partial_arms = variants .iter() .fold(proc_macro2::TokenStream::new(), |mut tokens, variant| { let fields_merge_partial = fields_merge_partial(&variant.fields); tokens.extend(variant_and_partial_match_arm( params_name, params_partial_name, variant, fields_merge_partial, )); tokens }); quote! { match (self, params_partial) { #variant_merge_partial_arms _ => {} // Merging different variants is not supported. } } } fn fields_merge_partial(fields: &Fields) -> proc_macro2::TokenStream { fields .iter() .filter(|field| !is_phantom_data(&field.ty)) .enumerate() .map(|(field_index, field)| { if let Some(field_ident) = field.ident.as_ref() { let field_name_partial = field_name_partial(field_ident); quote! { if let Some(#field_name_partial) = #field_name_partial { *#field_ident = #field_name_partial; } } } else { let field_ident = tuple_ident_from_field_index(field_index); let field_name_partial = field_name_partial(&field_ident); quote! { if let Some(#field_name_partial) = #field_name_partial { *#field_ident = #field_name_partial; } } } }) .collect::<proc_macro2::TokenStream>() }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/params_derive/src/field_wise_enum_builder_ctx.rs
crate/params_derive/src/field_wise_enum_builder_ctx.rs
use syn::{Generics, Ident}; #[derive(Clone, Debug)] pub struct FieldWiseEnumBuilderCtx { /// The `EnumParams`' generics with `VariantSelection` inserted beforehand. pub generics: Generics, /// Type parameter struct name when no variant has been selected. pub variant_none: Ident, /// Type parameters without the angle brackets: `T1, T2`. pub ty_generics_idents: proc_macro2::TokenStream, /// `<#enum_params_variant_selection_none, #ty_generics_idents>` pub type_params_with_variant_none: proc_macro2::TokenStream, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/value_traits/src/lib.rs
crate/value_traits/src/lib.rs
//! Trait bounds for value types for the Peace framework. pub use crate::app_error::AppError; mod app_error;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/value_traits/src/app_error.rs
crate/value_traits/src/app_error.rs
use std::fmt::Debug; /// Bounds that the application error type must satisfy. pub trait AppError: Debug + std::error::Error + Send + Sync + Unpin + 'static {} impl<T> AppError for T where T: Debug + std::error::Error + Send + Sync + Unpin + 'static {}
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/lib.rs
crate/item_interaction_model/src/lib.rs
//! Data types for resource interactions for the Peace framework. // Re-exports pub use url::{self, Host, Url}; // TODO: Remove this when we have refactored where progress types live. #[cfg(feature = "output_progress")] pub use peace_progress_model::ItemLocationState; pub use crate::{ item_interaction::{ ItemInteraction, ItemInteractionPull, ItemInteractionPush, ItemInteractionWithin, }, item_interactions_current::ItemInteractionsCurrent, item_interactions_current_or_example::ItemInteractionsCurrentOrExample, item_interactions_example::ItemInteractionsExample, item_location::ItemLocation, item_location_ancestors::ItemLocationAncestors, item_location_tree::ItemLocationTree, item_location_type::ItemLocationType, item_locations_combined::ItemLocationsCombined, }; #[cfg(feature = "item_locations_and_interactions")] pub use crate::item_locations_and_interactions::ItemLocationsAndInteractions; #[cfg(feature = "output_progress")] pub use crate::{ // TODO: uncomment when we have refactored where progress types live. // item_location_state::ItemLocationState, item_location_state_in_progress::ItemLocationStateInProgress, }; mod item_interaction; mod item_interactions_current; mod item_interactions_current_or_example; mod item_interactions_example; mod item_location; mod item_location_ancestors; mod item_location_tree; mod item_location_type; mod item_locations_combined; // TODO: uncomment when we have refactored where progress types live. // #[cfg(feature = "output_progress")] // mod item_location_state; #[cfg(feature = "output_progress")] mod item_location_state_in_progress; #[cfg(feature = "item_locations_and_interactions")] mod item_locations_and_interactions;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_location_ancestors.rs
crate/item_interaction_model/src/item_location_ancestors.rs
use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; use crate::ItemLocation; /// An [`ItemLocation`] and its ancestors. /// /// The list of [`ItemLocation`]s within this container starts with the /// outermost known ancestor, gradually moving closer to the innermost /// `ItemLocation`. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemLocationAncestors(Vec<ItemLocation>); impl ItemLocationAncestors { /// Returns a new [`ItemLocationAncestors`] with the given ancestry. pub fn new(ancestors: Vec<ItemLocation>) -> Self { Self(ancestors) } /// Returns the underlying `Vec<ItemLocation>`. pub fn into_inner(self) -> Vec<ItemLocation> { self.0 } } impl Deref for ItemLocationAncestors { type Target = Vec<ItemLocation>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ItemLocationAncestors { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<ItemLocation> for ItemLocationAncestors { fn from(item_location: ItemLocation) -> Self { Self(vec![item_location]) } } impl From<Vec<ItemLocation>> for ItemLocationAncestors { fn from(ancestors: Vec<ItemLocation>) -> Self { Self(ancestors) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interactions_current.rs
crate/item_interaction_model/src/item_interactions_current.rs
use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; use crate::ItemInteraction; /// [`ItemInteraction`]s constructed from parameters derived from fully known /// state. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInteractionsCurrent(Vec<ItemInteraction>); impl ItemInteractionsCurrent { /// Returns a new `ItemInteractionsCurrent` map. pub fn new() -> Self { Self::default() } /// Returns a new `ItemInteractionsCurrent` map with the given preallocated /// capacity. pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) } /// Returns the underlying map. pub fn into_inner(self) -> Vec<ItemInteraction> { self.0 } } impl Deref for ItemInteractionsCurrent { type Target = Vec<ItemInteraction>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ItemInteractionsCurrent { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<Vec<ItemInteraction>> for ItemInteractionsCurrent { fn from(inner: Vec<ItemInteraction>) -> Self { Self(inner) } } impl FromIterator<ItemInteraction> for ItemInteractionsCurrent { fn from_iter<I: IntoIterator<Item = ItemInteraction>>(iter: I) -> Self { Self(Vec::from_iter(iter)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_location_tree.rs
crate/item_interaction_model/src/item_location_tree.rs
use serde::{Deserialize, Serialize}; use crate::ItemLocation; /// An [`ItemLocation`] and its children. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemLocationTree { /// This [`ItemLocation`]. pub item_location: ItemLocation, /// The children of this [`ItemLocation`]. pub children: Vec<ItemLocationTree>, } impl ItemLocationTree { /// Returns a new [`ItemLocationTree`]. pub fn new(item_location: ItemLocation, children: Vec<ItemLocationTree>) -> Self { Self { item_location, children, } } /// Returns this [`ItemLocation`]. pub fn item_location(&self) -> &ItemLocation { &self.item_location } /// Returns the children of this [`ItemLocation`]. pub fn children(&self) -> &[ItemLocationTree] { &self.children } /// Returns the total number of [`ItemLocation`]s within this tree, /// including itself. pub fn item_location_count(&self) -> usize { 1 + self .children .iter() .map(ItemLocationTree::item_location_count) .sum::<usize>() } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_location_type.rs
crate/item_interaction_model/src/item_location_type.rs
use serde::{Deserialize, Serialize}; /// The type of resource location. /// /// This affects how the [`ItemLocation`] is rendered. /// /// [`ItemLocation`]: crate::ItemLocation #[derive(Clone, Copy, Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Deserialize, Serialize)] pub enum ItemLocationType { /// Rendered with dashed lines. /// /// Suitable for concepts like: /// /// * Cloud provider /// * Network / subnet Group, /// Rendered with solid lines. /// /// Suitable for concepts like: /// /// * Localhost /// * Server Host, /// Rendered with solid lines. /// /// Suitable for concepts like: /// /// * File path /// * URL Path, }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interactions_example.rs
crate/item_interaction_model/src/item_interactions_example.rs
use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; use crate::ItemInteraction; /// [`ItemInteraction`]s constructed from parameters derived from at least some /// example state. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInteractionsExample(Vec<ItemInteraction>); impl ItemInteractionsExample { /// Returns a new `ItemInteractionsExample` map. pub fn new() -> Self { Self::default() } /// Returns a new `ItemInteractionsExample` map with the given preallocated /// capacity. pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) } /// Returns the underlying map. pub fn into_inner(self) -> Vec<ItemInteraction> { self.0 } } impl Deref for ItemInteractionsExample { type Target = Vec<ItemInteraction>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ItemInteractionsExample { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<Vec<ItemInteraction>> for ItemInteractionsExample { fn from(inner: Vec<ItemInteraction>) -> Self { Self(inner) } } impl FromIterator<ItemInteraction> for ItemInteractionsExample { fn from_iter<I: IntoIterator<Item = ItemInteraction>>(iter: I) -> Self { Self(Vec::from_iter(iter)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interaction.rs
crate/item_interaction_model/src/item_interaction.rs
use serde::{Deserialize, Serialize}; mod item_interaction_pull; mod item_interaction_push; mod item_interaction_within; pub use self::{ item_interaction_pull::ItemInteractionPull, item_interaction_push::ItemInteractionPush, item_interaction_within::ItemInteractionWithin, }; /// Represents the resources that are read from / written to. /// /// This is used on an outcome diagram to highlight the resources that are being /// accessed. For example, a file is read from the user's computer, and uploaded /// / written to a file server. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ItemInteraction { /// Represents a location-to-location push interaction. /// /// This can represent a file transfer from one host to another. Push(ItemInteractionPush), /// Represents a location-to-location pull interaction. /// /// This can represent a file download from a server. Pull(ItemInteractionPull), /// Represents a resource interaction that happens within a location. /// /// This can represent application installation / startup happening on a /// server. Within(ItemInteractionWithin), } impl From<ItemInteractionPush> for ItemInteraction { fn from(item_interaction_push: ItemInteractionPush) -> Self { Self::Push(item_interaction_push) } } impl From<ItemInteractionPull> for ItemInteraction { fn from(item_interaction_pull: ItemInteractionPull) -> Self { Self::Pull(item_interaction_pull) } } impl From<ItemInteractionWithin> for ItemInteraction { fn from(item_interaction_within: ItemInteractionWithin) -> Self { Self::Within(item_interaction_within) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interactions_current_or_example.rs
crate/item_interaction_model/src/item_interactions_current_or_example.rs
use serde::{Deserialize, Serialize}; use crate::{ItemInteractionsCurrent, ItemInteractionsExample}; /// [`ItemInteraction`]s constructed from parameters derived from at least some /// example state. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ItemInteractionsCurrentOrExample { /// [`ItemInteraction`]s constructed from parameters derived from fully /// known state. Current(ItemInteractionsCurrent), /// [`ItemInteraction`]s constructed from parameters derived from at least /// some example state. Example(ItemInteractionsExample), } impl From<ItemInteractionsCurrent> for ItemInteractionsCurrentOrExample { fn from(item_interactions_current: ItemInteractionsCurrent) -> Self { Self::Current(item_interactions_current) } } impl From<ItemInteractionsExample> for ItemInteractionsCurrentOrExample { fn from(item_interactions_example: ItemInteractionsExample) -> Self { Self::Example(item_interactions_example) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_locations_combined.rs
crate/item_interaction_model/src/item_locations_combined.rs
use std::ops::{Deref, DerefMut}; use serde::{Deserialize, Serialize}; use crate::ItemLocationTree; /// All [`ItemLocation`]s from all items merged and deduplicated. #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemLocationsCombined(Vec<ItemLocationTree>); impl ItemLocationsCombined { /// Returns a new `ItemLocationsCombined`. pub fn new() -> Self { Self::default() } /// Returns a new `ItemLocationsCombined` map with the given preallocated /// capacity. pub fn with_capacity(capacity: usize) -> Self { Self(Vec::with_capacity(capacity)) } /// Returns the underlying map. pub fn into_inner(self) -> Vec<ItemLocationTree> { self.0 } } impl Deref for ItemLocationsCombined { type Target = Vec<ItemLocationTree>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for ItemLocationsCombined { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<Vec<ItemLocationTree>> for ItemLocationsCombined { fn from(inner: Vec<ItemLocationTree>) -> Self { Self(inner) } } impl FromIterator<ItemLocationTree> for ItemLocationsCombined { fn from_iter<I: IntoIterator<Item = ItemLocationTree>>(iter: I) -> Self { Self(Vec::from_iter(iter)) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_location.rs
crate/item_interaction_model/src/item_location.rs
use std::path::Path; use serde::{Deserialize, Serialize}; use url::Url; use crate::ItemLocationType; /// One layer of where a resource is located. /// /// These will be merged into the same node based on their variant and name. /// /// For example, if two different items provide the following /// `ItemLocation`s: /// /// Item 1: /// /// 1. `ItemLocation::Group("cloud")` /// 2. `ItemLocation::Host("app.domain.com")` /// 3. `ItemLocation::Path("/path/to/a_file")` /// /// Item 2: /// /// 1. `ItemLocation::Host("app.domain.com")` /// 2. `ItemLocation::Path("/path/to/another_file")` /// /// Then the resultant node hierarchy will be: /// /// ```yaml /// cloud: /// app.domain.com: /// "/path/to/a_file": {} /// "/path/to/another_file": {} /// ``` /// /// # Implementors /// /// Item implementors should endeavour to use the same name for each /// `ItemLocation`, as that is how the Peace framework determines if two /// `ItemLocation`s are the same. /// /// # Design /// /// When designing this, another design that was considered is using an enum /// like the following: /// /// ```rust,ignore /// #[derive(Debug)] /// enum ItemLocation { /// Host(ItemLocationHost), /// Url(Url), /// } /// /// struct ItemLocationHost { /// host: Host<String>, /// port: Option<u16>, /// } /// /// impl ItemLocation { /// fn from_url(url: &Url) -> Self { /// Self::Url(url.clone()) /// } /// } /// /// impl From<&Url> for ItemLocationHost { /// type Error = (); /// /// fn from(url: &Url) -> Result<Self, ()> { /// url.host() /// .map(|host| { /// let host = host.to_owned(); /// let port = url.map(Url::port_or_known_default); /// Self { host, port } /// }) /// .ok_or(()) /// } /// } /// ``` /// /// However, the purpose of `ItemLocation` is primarily for rendering, and /// providing accurate variants for each kind of resource location causes /// additional burden on: /// /// * framework maintainers to maintain those variants /// * item implementors to select the correct variant for accuracy /// * item implementors to select a variant consistent with other item /// implementors /// /// A less accurate model with a limited number of [`ItemLocationType`]s /// balances the modelling accuracy, rendering, and maintenance burden. #[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)] pub struct ItemLocation { /// The type of the resource location. pub r#type: ItemLocationType, /// The name of the resource location. pub name: String, } impl ItemLocation { /// The string used for an unknown host. pub const HOST_UNKNOWN: &'static str = "unknown"; /// The string used for localhost. pub const LOCALHOST: &'static str = "💻 localhost"; /// Returns a new `ItemLocation`. /// /// See also: /// /// * [`ItemLocation::group`] /// * [`ItemLocation::host`] /// * [`ItemLocation::localhost`] /// * [`ItemLocation::path`] pub fn new(r#type: ItemLocationType, name: String) -> Self { Self { r#type, name } } /// Returns `ItemLocation::new(name, ItemLocationType::Group)`. pub fn group(name: String) -> Self { Self { r#type: ItemLocationType::Group, name, } } /// Returns `ItemLocation::new(name, ItemLocationType::Host)`. pub fn host(name: String) -> Self { Self { r#type: ItemLocationType::Host, name, } } /// Returns `ItemLocation::new("unknown".to_string(), /// ItemLocationType::Host)`. pub fn host_unknown() -> Self { Self { r#type: ItemLocationType::Host, name: Self::HOST_UNKNOWN.to_string(), } } /// Returns `ItemLocation::new(name, ItemLocationType::Host)`. /// /// This is "lossy" in the sense that if the URL doesn't have a [`Host`], /// this will return localhost, as URLs without a host may be unix sockets, /// or data URLs. /// /// [`Host`]: url::Host pub fn host_from_url(url: &Url) -> Self { url.host_str() .map(|host_str| Self { r#type: ItemLocationType::Host, name: format!("🌐 {host_str}"), }) .unwrap_or_else(Self::localhost) } /// Returns `ItemLocation::host("localhost".to_string())`. pub fn localhost() -> Self { Self { r#type: ItemLocationType::Host, name: Self::LOCALHOST.to_string(), } } /// Returns `ItemLocation::new(name, ItemLocationType::Path)`. /// /// See also [`ItemLocation::path_lossy`]. /// /// [`ItemLocation::path_lossy`]: Self::path_lossy pub fn path(name: String) -> Self { Self { r#type: ItemLocationType::Path, name, } } /// Returns `ItemLocation::new(name, ItemLocationType::Path)`, using the /// lossy conversion from the given path. pub fn path_lossy(name: &Path) -> Self { Self { // For some reason, calling `to_string_lossy()` on the path itself doesn't return the // replacement character, and breaks the // `item_interaction_model::item_location::path_lossy` test. // // The rust source code on 1.80.0 stable uses `String::from_utf8_lossy` internally: // <https://doc.rust-lang.org/src/std/sys/os_str/bytes.rs.html#271> // // ```rust // name.to_string_lossy().to_string() // ``` name: String::from_utf8_lossy(name.as_os_str().as_encoded_bytes()).to_string(), r#type: ItemLocationType::Path, } } /// Returns the name of the resource location. pub fn name(&self) -> &str { &self.name } /// Returns the type of the resource location. pub fn r#type(&self) -> ItemLocationType { self.r#type } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_location_state_in_progress.rs
crate/item_interaction_model/src/item_location_state_in_progress.rs
use peace_progress_model::{CmdBlockItemInteractionType, ProgressComplete, ProgressStatus}; use serde::{Deserialize, Serialize}; use crate::ItemLocationState; /// Represents the state of an [`ItemLocation`]. /// /// This affects how the [`ItemLocation`] is rendered. /// /// This is analogous to [`ItemLocationState`], with added variants for when the /// state is being determined. /// /// [`ItemLocation`]: crate::ItemLocation #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize, Serialize)] pub enum ItemLocationStateInProgress { /// [`ItemLocation`] does not exist. /// /// This means it should be rendered invisible / low opacity. /// /// [`ItemLocation`]: crate::ItemLocation NotExists, /// [`ItemLocation`] should not exist, but does. /// /// This means it should be rendered red outlined with full opacity. /// /// [`ItemLocation`]: crate::ItemLocation NotExistsError, /// [`ItemLocation`] may or may not exist, and we are in the process of /// determining that. /// /// This means it should be rendered pulsing / mid opacity. /// /// [`ItemLocation`]: crate::ItemLocation DiscoverInProgress, /// [`ItemLocation`] may or may not exist, and we failed to discover that. /// /// This means it should be rendered red / mid opacity. /// /// [`ItemLocation`]: crate::ItemLocation DiscoverError, /// [`ItemLocation`] is being created. /// /// This means it should be rendered with full opacity and blue animated /// outlines. /// /// [`ItemLocation`]: crate::ItemLocation CreateInProgress, /// [`ItemLocation`] is being modified. /// /// This means it should be rendered with full opacity and blue animated /// outlines. /// /// [`ItemLocation`]: crate::ItemLocation ModificationInProgress, /// [`ItemLocation`] exists. /// /// This means it should be rendered with full opacity. /// /// [`ItemLocation`]: crate::ItemLocation ExistsOk, /// [`ItemLocation`] exists, but is in an erroneous state. /// /// This means it should be rendered with full opacity with a red shape /// colour. /// /// [`ItemLocation`]: crate::ItemLocation ExistsError, } impl ItemLocationStateInProgress { #[rustfmt::skip] pub fn from( cmd_block_item_interaction_type: CmdBlockItemInteractionType, item_location_state: ItemLocationState, progress_status: ProgressStatus, ) -> Self { match ( cmd_block_item_interaction_type, item_location_state, progress_status, ) { (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Initialized) => Self::NotExists, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Interrupted) => Self::NotExists, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::ExecPending) => Self::NotExists, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Queued) => Self::NotExists, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Running) => Self::CreateInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::RunningStalled) => Self::CreateInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::UserPending) => Self::CreateInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Complete(ProgressComplete::Success)) => Self::NotExists, (CmdBlockItemInteractionType::Write, ItemLocationState::NotExists, ProgressStatus::Complete(ProgressComplete::Fail)) => Self::NotExistsError, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Initialized) => Self::ExistsOk, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Interrupted) => Self::ExistsOk, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::ExecPending) => Self::ExistsOk, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Queued) => Self::ExistsOk, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Running) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::RunningStalled) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::UserPending) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Complete(ProgressComplete::Success)) => Self::ExistsOk, (CmdBlockItemInteractionType::Write, ItemLocationState::Exists, ProgressStatus::Complete(ProgressComplete::Fail)) => Self::ExistsError, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Initialized) => Self::NotExists, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Interrupted) => Self::NotExists, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::ExecPending) => Self::NotExists, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Queued) => Self::NotExists, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Running) => Self::DiscoverInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::RunningStalled) => Self::DiscoverInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::UserPending) => Self::DiscoverInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Complete(ProgressComplete::Success)) => Self::NotExists, (CmdBlockItemInteractionType::Read, ItemLocationState::NotExists, ProgressStatus::Complete(ProgressComplete::Fail)) => Self::DiscoverError, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Initialized) => Self::ExistsOk, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Interrupted) => Self::ExistsOk, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::ExecPending) => Self::ExistsOk, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Queued) => Self::ExistsOk, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Running) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::RunningStalled) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::UserPending) => Self::ModificationInProgress, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Complete(ProgressComplete::Success)) => Self::ExistsOk, (CmdBlockItemInteractionType::Read, ItemLocationState::Exists, ProgressStatus::Complete(ProgressComplete::Fail)) => Self::ExistsError, (CmdBlockItemInteractionType::Local, ItemLocationState::NotExists, _) => Self::NotExists, (CmdBlockItemInteractionType::Local, ItemLocationState::Exists, _) => Self::ExistsOk, } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_locations_and_interactions.rs
crate/item_interaction_model/src/item_locations_and_interactions.rs
use indexmap::IndexMap; use peace_item_model::ItemId; use serde::{Deserialize, Serialize}; use crate::{ItemInteraction, ItemLocationTree}; #[cfg(feature = "output_progress")] use std::collections::{HashMap, HashSet}; #[cfg(feature = "output_progress")] use crate::ItemLocation; /// Merged [`ItemLocation`]s and [`ItemInteraction`]s from all items. /// /// [`ItemLocation`]: crate::ItemLocation #[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemLocationsAndInteractions { /// Hierarchical storage of [`ItemLocation`]s. /// /// [`ItemLocation`]: crate::ItemLocation pub item_location_trees: Vec<ItemLocationTree>, /// The [`ItemInteraction`]s from each item. pub item_to_item_interactions: IndexMap<ItemId, Vec<ItemInteraction>>, /// Number of `ItemLocation`s from all merged [`ItemInteraction`]s. /// /// [`ItemLocation`]: crate::ItemLocation pub item_location_count: usize, /// Map that tracks the items that referred to each item location. #[cfg(feature = "output_progress")] pub item_location_to_item_id_sets: HashMap<ItemLocation, HashSet<ItemId>>, } impl ItemLocationsAndInteractions { /// Returns a new `ItemLocationsAndInteractions` container. pub fn new( item_location_trees: Vec<ItemLocationTree>, item_to_item_interactions: IndexMap<ItemId, Vec<ItemInteraction>>, item_location_count: usize, #[cfg(feature = "output_progress")] item_location_to_item_id_sets: HashMap< ItemLocation, HashSet<ItemId>, >, ) -> Self { Self { item_location_trees, item_to_item_interactions, item_location_count, #[cfg(feature = "output_progress")] item_location_to_item_id_sets, } } /// Returns the hierarchical storage of [`ItemLocation`]s. /// /// [`ItemLocation`]: crate::ItemLocation pub fn item_location_trees(&self) -> &[ItemLocationTree] { &self.item_location_trees } /// Returns the [`ItemInteraction`]s from each item. pub fn item_to_item_interactions(&self) -> &IndexMap<ItemId, Vec<ItemInteraction>> { &self.item_to_item_interactions } /// Returns the number of `ItemLocation`s from all merged /// [`ItemInteraction`]s. /// /// [`ItemLocation`]: crate::ItemLocation pub fn item_location_count(&self) -> usize { self.item_location_count } /// Returns the map that tracks the items that referred to each item /// location. #[cfg(feature = "output_progress")] pub fn item_location_to_item_id_sets(&self) -> &HashMap<ItemLocation, HashSet<ItemId>> { &self.item_location_to_item_id_sets } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interaction/item_interaction_pull.rs
crate/item_interaction_model/src/item_interaction/item_interaction_pull.rs
use serde::{Deserialize, Serialize}; use crate::{ItemLocation, ItemLocationAncestors}; /// Represents a location-to-location pull interaction. /// /// This can represent a file download from a server. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInteractionPull { /// Where the interaction begins from. /// /// Example: /// /// 1. `ItemLocation::localhost()` /// 2. `ItemLocation::new("/path/to/file", ItemLocationType::Path)` pub location_client: ItemLocationAncestors, /// Where the interaction goes to. /// /// Example: /// /// 1. `ItemLocation::new("app.domain.com", ItemLocationType::Host)` /// 2. `ItemLocation::new("http://app.domain.com/resource", /// ItemLocationType::Path)` pub location_server: ItemLocationAncestors, } impl ItemInteractionPull { /// Returns a new `ItemInteractionPull`. pub fn new( location_client: ItemLocationAncestors, location_server: ItemLocationAncestors, ) -> Self { Self { location_client, location_server, } } /// Returns where the interaction begins from. /// /// Example: /// /// 1. `ItemLocation::localhost()` /// 2. `ItemLocation::new("/path/to/file", ItemLocationType::Path)` pub fn location_client(&self) -> &[ItemLocation] { &self.location_client } /// Returns where the interaction goes to. /// /// Example: /// /// 1. `ItemLocation::new("app.domain.com", ItemLocationType::Host)` /// 2. `ItemLocation::new("http://app.domain.com/resource", /// ItemLocationType::Path)` pub fn location_server(&self) -> &[ItemLocation] { &self.location_server } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interaction/item_interaction_within.rs
crate/item_interaction_model/src/item_interaction/item_interaction_within.rs
use serde::{Deserialize, Serialize}; use crate::{ItemLocation, ItemLocationAncestors}; /// Represents a resource interaction that happens within a location. /// /// This can represent application installation / startup happening on a /// server. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInteractionWithin { /// Where the interaction is happening. /// /// Example: /// /// 1. `ItemLocation::Server { address, port: None }` pub location: ItemLocationAncestors, } impl ItemInteractionWithin { /// Returns a new `ItemInteractionWithin`. pub fn new(location: ItemLocationAncestors) -> Self { Self { location } } /// Returns where the interaction is happening. pub fn location(&self) -> &[ItemLocation] { &self.location } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_interaction_model/src/item_interaction/item_interaction_push.rs
crate/item_interaction_model/src/item_interaction/item_interaction_push.rs
use serde::{Deserialize, Serialize}; use crate::{ItemLocation, ItemLocationAncestors}; /// Represents a location-to-location push interaction. /// /// This can represent a file transfer from one host to another. #[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemInteractionPush { /// Where the interaction begins from. /// /// Example: /// /// 1. `ItemLocation::localhost()` /// 2. `ItemLocation::new("/path/to/file", ItemLocationType::Path)` pub location_from: ItemLocationAncestors, /// Where the interaction goes to. /// /// Example: /// /// 1. `ItemLocation::new("app.domain.com", ItemLocationType::Host)` /// 2. `ItemLocation::new("http://app.domain.com/resource", /// ItemLocationType::Path)` pub location_to: ItemLocationAncestors, } impl ItemInteractionPush { /// Returns a new `ItemInteractionPush`. pub fn new(location_from: ItemLocationAncestors, location_to: ItemLocationAncestors) -> Self { Self { location_from, location_to, } } /// Returns where the interaction begins from. /// /// Example: /// /// 1. `ItemLocation::localhost()` /// 2. `ItemLocation::new("/path/to/file", ItemLocationType::Path)` pub fn location_from(&self) -> &[ItemLocation] { &self.location_from } /// Returns where the interaction goes to. /// /// Example: /// /// 1. `ItemLocation::new("app.domain.com", ItemLocationType::Host)` /// 2. `ItemLocation::new("http://app.domain.com/resource", /// ItemLocationType::Path)` pub fn location_to(&self) -> &[ItemLocation] { &self.location_to } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_model/src/lib.rs
crate/item_model/src/lib.rs
//! Serializable data model for items for the Peace framework. pub use peace_static_check_macros::item_id; pub use crate::item_id::{ItemId, ItemIdInvalidFmt}; mod item_id;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/crate/item_model/src/item_id.rs
crate/item_model/src/item_id.rs
use std::borrow::Cow; use serde::{Deserialize, Serialize}; /// Unique identifier for an [`Item`], `Cow<'static, str>` newtype. /// /// Must begin with a letter or underscore, and contain only letters, numbers, /// and underscores. /// /// # Examples /// /// The following are all examples of valid `ItemId`s: /// /// ```rust /// # use peace_item_model::{item_id, ItemId}; /// # /// let _snake = item_id!("snake_case"); /// let _camel = item_id!("camelCase"); /// let _pascal = item_id!("PascalCase"); /// ``` /// /// # Design Note /// /// TODO: Experiment with upgrades. /// /// For backward compatibility and migrating items from old IDs to new IDs, e.g. /// when they were deployed with an old version of the automation software, /// there needs to be a way to: /// /// * Read state using the old ID. /// * Either clean up that state, or migrate that state into an Item with the /// new ID. /// /// [`Item`]: https://docs.rs/peace_cfg/latest/peace_cfg/trait.Item.html #[derive(Clone, Debug, Hash, PartialEq, Eq, Deserialize, Serialize)] pub struct ItemId(Cow<'static, str>); peace_core::id_newtype!(ItemId, ItemIdInvalidFmt, item_id, code_inline);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_rt.rs
workspace_tests/src/cmd_rt.rs
mod cmd_execution;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/lib.rs
workspace_tests/src/lib.rs
#![cfg_attr(coverage_nightly, feature(coverage_attribute))] #![cfg(test)] pub(crate) use crate::{ fn_invocation::FnInvocation, fn_name::fn_name_short, fn_tracker_output::FnTrackerOutput, fn_tracker_presenter::FnTrackerPresenter, no_op_output::NoOpOutput, peace_test_error::PeaceTestError, vec_copy_item::{ VecA, VecB, VecCopyDiff, VecCopyError, VecCopyItem, VecCopyItemWrapper, VecCopyState, }, }; pub(crate) mod mock_item; // `peace` test modules mod cfg; mod cli; mod cmd_ctx; mod cmd_model; mod cmd_rt; mod data; mod diff; mod flow_model; mod fmt; #[cfg(feature = "item_interactions")] mod item_interaction_model; mod item_model; mod params; mod profile_model; #[cfg(feature = "output_progress")] mod progress_model; mod resource_rt; mod rt; mod rt_model; mod state_rt; #[cfg(feature = "webi")] mod webi; // `peace_items` test modules #[cfg(feature = "items")] mod items; // `workspace_tests` support code mod fn_invocation; mod fn_name; mod fn_tracker_output; mod fn_tracker_presenter; mod no_op_output; mod peace_cmd_ctx_types; mod peace_test_error; mod test_support; mod vec_copy_item;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/vec_copy_item.rs
workspace_tests/src/vec_copy_item.rs
use std::{ fmt, ops::{Deref, DerefMut}, }; use diff::{Diff, VecDiff, VecDiffType}; use peace::{ cfg::{async_trait, ApplyCheck, FnCtx, Item}, data::{ accessors::{RMaybe, W}, Data, }, item_model::{item_id, ItemId}, params::Params, resource_rt::{resources::ts::Empty, states::StatesCurrentStored, Resources}, rt_model::ItemWrapper, }; #[cfg(feature = "output_progress")] use peace::{ item_interaction_model::ItemLocationState, progress_model::{ProgressLimit, ProgressMsgUpdate}, }; use serde::{Deserialize, Serialize}; /// Type alias for `ItemWrapper` with all of VecCopyItem's parameters. pub type VecCopyItemWrapper = ItemWrapper<VecCopyItem, VecCopyError>; /// Copies bytes from `VecA` to `VecB`. #[derive(Clone, Debug)] pub struct VecCopyItem { /// ID of the item. id: ItemId, } impl VecCopyItem { pub const ID_DEFAULT: &'static ItemId = &item_id!("vec_copy"); pub fn new(id: ItemId) -> Self { Self { id } } async fn state_current_internal( fn_ctx: FnCtx<'_>, data: VecCopyData<'_>, ) -> Result<VecCopyState, VecCopyError> { #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; let vec_copy_state = VecCopyState::from(data.dest().0.clone()); #[cfg(feature = "output_progress")] { if let Ok(len) = u64::try_from(vec_copy_state.len()) { fn_ctx.progress_sender.inc(len, ProgressMsgUpdate::NoChange); } } Ok(vec_copy_state) } async fn state_goal_internal( fn_ctx: FnCtx<'_>, vec_a: &[u8], ) -> Result<VecCopyState, VecCopyError> { #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; let vec_copy_state = VecCopyState::from(vec_a.to_vec()); #[cfg(feature = "output_progress")] { if let Ok(len) = u64::try_from(vec_copy_state.len()) { fn_ctx.progress_sender.inc(len, ProgressMsgUpdate::NoChange); } } Ok(vec_copy_state) } } impl Default for VecCopyItem { fn default() -> Self { Self::new(Self::ID_DEFAULT.clone()) } } #[async_trait(?Send)] impl Item for VecCopyItem { type Data<'exec> = VecCopyData<'exec>; type Error = VecCopyError; type Params<'exec> = VecA; type State = VecCopyState; type StateDiff = VecCopyDiff; fn id(&self) -> &ItemId { &self.id } #[cfg(feature = "item_state_example")] fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State { VecCopyState(params.0.clone()) } async fn try_state_current( fn_ctx: FnCtx<'_>, _params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, VecCopyError> { Self::state_current_internal(fn_ctx, data).await.map(Some) } async fn state_current( fn_ctx: FnCtx<'_>, _params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, VecCopyError> { Self::state_current_internal(fn_ctx, data).await } async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, ) -> Result<Option<Self::State>, VecCopyError> { if let Some(vec_a) = params_partial.0.as_ref() { Self::state_goal_internal(fn_ctx, vec_a).await.map(Some) } else { Ok(None) } } async fn state_goal( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, _data: Self::Data<'_>, ) -> Result<Self::State, VecCopyError> { Self::state_goal_internal(fn_ctx, params.0.as_ref()).await } async fn state_diff( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: VecCopyData<'_>, state_current: &VecCopyState, state_goal: &VecCopyState, ) -> Result<Self::StateDiff, VecCopyError> { Ok(VecCopyDiff::from(state_current.diff(state_goal))) } async fn state_clean( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: Self::Data<'_>, ) -> Result<Self::State, VecCopyError> { Ok(VecCopyState::new()) } async fn apply_check( _params: &Self::Params<'_>, _data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<ApplyCheck, Self::Error> { let apply_check = if diff.0 .0.is_empty() { ApplyCheck::ExecNotRequired } else { #[cfg(not(feature = "output_progress"))] { let _state_current = state_current; let _state_target = state_target; ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let progress_limit = TryInto::<u64>::try_into(state_current.len() + state_target.len()) .map(ProgressLimit::Bytes) .unwrap_or(ProgressLimit::Unknown); ApplyCheck::ExecRequired { progress_limit } } }; Ok(apply_check) } async fn apply_dry( _fn_ctx: FnCtx<'_>, _params: &Self::Params<'_>, _data: Self::Data<'_>, _state_current: &Self::State, state_target: &Self::State, _diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { // Would replace vec_b's contents with vec_a's Ok(state_target.clone()) } async fn apply( fn_ctx: FnCtx<'_>, _params: &Self::Params<'_>, mut data: Self::Data<'_>, _state_current: &Self::State, state_target: &Self::State, _diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { let dest = data.dest_mut(); dest.0.clear(); dest.0.extend_from_slice(state_target.as_slice()); #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; #[cfg(feature = "output_progress")] if let Ok(n) = state_target.len().try_into() { fn_ctx.progress_sender().inc(n, ProgressMsgUpdate::NoChange); } Ok(state_target.clone()) } async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), VecCopyError> { let vec_b = { let states_current_stored = <RMaybe<'_, StatesCurrentStored> as Data>::borrow(Self::ID_DEFAULT, resources); let vec_copy_state_current_stored: Option<&'_ VecCopyState> = states_current_stored .as_ref() .and_then(|states_current_stored| states_current_stored.get(self.id())); if let Some(vec_copy_state) = vec_copy_state_current_stored { VecB(vec_copy_state.to_vec()) } else { VecB::default() } }; resources.insert(vec_b); Ok(()) } #[cfg(feature = "item_interactions")] fn interactions( _params: &Self::Params<'_>, _data: Self::Data<'_>, ) -> Vec<peace::item_interaction_model::ItemInteraction> { use peace::item_interaction_model::{ItemInteractionPush, ItemLocation}; let item_interaction = ItemInteractionPush::new( vec![ ItemLocation::localhost(), ItemLocation::path("Vec A".to_string()), ] .into(), vec![ ItemLocation::localhost(), ItemLocation::path("Vec B".to_string()), ] .into(), ) .into(); vec![item_interaction] } } #[cfg(feature = "error_reporting")] use peace::miette; /// Error while executing a VecCopy. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum VecCopyError { /// A `peace` runtime error occurred. #[error("A `peace` runtime error occurred.")] PeaceRtError( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace::rt_model::Error, ), } #[derive(Data, Debug)] pub struct VecCopyData<'exec> { /// Destination `Vec` to write to. dest: W<'exec, VecB>, } impl VecCopyData<'_> { pub fn dest(&self) -> &VecB { &self.dest } pub fn dest_mut(&mut self) -> &mut VecB { &mut self.dest } } #[derive(Clone, Debug, Default, Params, PartialEq, Eq, Serialize, Deserialize)] pub struct VecA(pub Vec<u8>); #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct VecB(pub Vec<u8>); #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VecCopyState(Vec<u8>); impl VecCopyState { /// Returns an empty `VecCopyState`. pub fn new() -> Self { Self(Vec::new()) } } impl From<Vec<u8>> for VecCopyState { fn from(v: Vec<u8>) -> Self { Self(v) } } impl Deref for VecCopyState { type Target = Vec<u8>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for VecCopyState { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for VecCopyState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{:?}", self.0) } } impl Default for VecCopyState { fn default() -> Self { Self::new() } } #[cfg(feature = "output_progress")] impl<'state> From<&'state VecCopyState> for ItemLocationState { fn from(_vec_copy_state: &'state VecCopyState) -> ItemLocationState { ItemLocationState::Exists } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VecCopyDiff(VecDiff<u8>); impl From<VecDiff<u8>> for VecCopyDiff { fn from(v: VecDiff<u8>) -> Self { Self(v) } } impl Deref for VecCopyDiff { type Target = VecDiff<u8>; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for VecCopyDiff { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for VecCopyDiff { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[")?; self.0 .0 .iter() .try_for_each(|vec_diff_type| match vec_diff_type { VecDiffType::Removed { index, len } => { let index_end = index + len; write!(f, "(-){index}..{index_end}, ") } VecDiffType::Altered { index, changes } => { write!(f, "(~){index};")?; changes.iter().try_for_each(|value| write!(f, "{value}, ")) } VecDiffType::Inserted { index, changes } => { write!(f, "(+){index};")?; changes.iter().try_for_each(|value| write!(f, "{value}, ")) } })?; write!(f, "]") } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/items.rs
workspace_tests/src/items.rs
mod sh_cmd_item; mod tar_x_item;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/profile_model.rs
workspace_tests/src/profile_model.rs
mod profile; mod profile_invalid_fmt;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_interaction_model.rs
workspace_tests/src/item_interaction_model.rs
mod item_interaction; mod item_location;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/peace_cmd_ctx_types.rs
workspace_tests/src/peace_cmd_ctx_types.rs
pub use self::{ test_cct_fn_tracker_output::TestCctFnTrackerOutput, test_cct_no_op_output::TestCctNoOpOutput, }; mod test_cct_fn_tracker_output; mod test_cct_no_op_output;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/diff.rs
workspace_tests/src/diff.rs
mod changeable; mod equality; mod maybe_eq; mod tracked;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params.rs
workspace_tests/src/params.rs
mod any_spec_rt; mod any_spec_rt_boxed; mod derive; mod field_name_and_type; mod mapping_fn_impl; mod params_spec; mod params_spec_fieldless; mod params_specs; mod value_resolution_ctx; mod value_resolution_mode; mod value_spec;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/progress_model.rs
workspace_tests/src/progress_model.rs
mod progress_complete; mod progress_delta; mod progress_limit; mod progress_sender; mod progress_status; mod progress_tracker; mod progress_update; mod progress_update_and_id;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_ctx.rs
workspace_tests/src/cmd_ctx.rs
use peace::{ cmd_ctx::type_reg::untagged::TypeReg, enum_iterator::Sequence, params::ParamsKey, profile_model::Profile, }; use serde::{Deserialize, Serialize}; mod cmd_ctx_mpnf; mod cmd_ctx_mpnf_params; mod cmd_ctx_mpsf; mod cmd_ctx_mpsf_params; mod cmd_ctx_npnf; mod cmd_ctx_npnf_params; mod cmd_ctx_spnf; mod cmd_ctx_spnf_params; mod cmd_ctx_spsf; mod cmd_ctx_spsf_params; /// Keys for workspace parameters. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] #[serde(rename_all = "snake_case")] pub enum WorkspaceParamsKey { Profile, StringParam, U8Param, } impl ParamsKey for WorkspaceParamsKey { fn register_value_type(self, type_reg: &mut TypeReg<Self>) { match self { Self::Profile => type_reg.register::<Profile>(self), Self::StringParam => type_reg.register::<String>(self), Self::U8Param => type_reg.register::<u8>(self), } } } /// Keys for profile parameters. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] #[serde(rename_all = "snake_case")] pub enum ProfileParamsKey { U32Param, U64Param, I64Param, } impl ParamsKey for ProfileParamsKey { fn register_value_type(self, type_reg: &mut TypeReg<Self>) { match self { Self::U32Param => type_reg.register::<u32>(self), Self::U64Param => type_reg.register::<u64>(self), Self::I64Param => type_reg.register::<i64>(self), } } } /// Keys for flow parameters. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] #[serde(rename_all = "snake_case")] pub enum FlowParamsKey { BoolParam, U16Param, I16Param, } impl ParamsKey for FlowParamsKey { fn register_value_type(self, type_reg: &mut TypeReg<Self>) { match self { Self::BoolParam => type_reg.register::<bool>(self), Self::U16Param => type_reg.register::<u16>(self), Self::I16Param => type_reg.register::<i16>(self), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/mock_item.rs
workspace_tests/src/mock_item.rs
use std::{ fmt, fmt::Debug, marker::PhantomData, ops::{Deref, DerefMut}, }; use peace::{ cfg::{async_trait, ApplyCheck, FnCtx, Item}, data::{ accessors::{RMaybe, R, W}, Data, }, item_model::{item_id, ItemId}, params::Params, resource_rt::{resources::ts::Empty, states::StatesCurrentStored, Resources}, }; #[cfg(feature = "output_progress")] use peace::{ item_interaction_model::ItemLocationState, progress_model::{ProgressLimit, ProgressMsgUpdate}, }; use serde::{Deserialize, Serialize}; /// Copies a number from `MockSrc` to `MockDest`. /// /// This also allows each item function to be overridden. #[derive(Clone, Debug)] pub struct MockItem<Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { /// ID of the item. id: ItemId, /// Marker. mock_fns: MockFns<Id>, } type FnTryState<Id> = fn( FnCtx<'_>, &<MockSrc as Params>::Partial, MockData<'_, Id>, ) -> Result<Option<MockState>, MockItemError>; type FnStateClean<Id> = fn(&<MockSrc as Params>::Partial, MockData<'_, Id>) -> Result<MockState, MockItemError>; type FnState<Id> = fn(FnCtx<'_>, &MockSrc, MockData<'_, Id>) -> Result<MockState, MockItemError>; type FnApplyCheck<Id> = fn( &MockSrc, MockData<'_, Id>, &MockState, &MockState, &MockDiff, ) -> Result<ApplyCheck, MockItemError>; type FnApply<Id> = fn( FnCtx<'_>, &MockSrc, MockData<'_, Id>, &MockState, &MockState, &MockDiff, ) -> Result<MockState, MockItemError>; /// Copies bytes from `MockSrc` to `MockDest`. #[derive(Clone, Debug, Default)] pub struct MockFns<Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { /// Override for `state_clean` function. state_clean: Option<FnStateClean<Id>>, /// Override for `try_state_current` function. try_state_current: Option<FnTryState<Id>>, /// Override for `state_current` function. state_current: Option<FnState<Id>>, /// Override for `try_state_goal` function. try_state_goal: Option<FnTryState<Id>>, /// Override for `state_goal` function. state_goal: Option<FnState<Id>>, /// Override for `apply_check` function. apply_check: Option<FnApplyCheck<Id>>, /// Override for `apply_dry` function. apply_dry: Option<FnApply<Id>>, /// Override for `apply` function. apply: Option<FnApply<Id>>, /// Marker. marker: PhantomData<Id>, } impl<Id> MockItem<Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { pub const ID_DEFAULT: &'static ItemId = &item_id!("mock"); pub fn new(id: ItemId) -> Self { Self { id, mock_fns: MockFns::<Id>::default(), } } pub fn with_state_clean(mut self, f: FnStateClean<Id>) -> Self { self.mock_fns.state_clean = Some(f); self } pub fn with_try_state_current(mut self, f: FnTryState<Id>) -> Self { self.mock_fns.try_state_current = Some(f); self } pub fn with_state_current(mut self, f: FnState<Id>) -> Self { self.mock_fns.state_current = Some(f); self } pub fn with_try_state_goal(mut self, f: FnTryState<Id>) -> Self { self.mock_fns.try_state_goal = Some(f); self } pub fn with_state_goal(mut self, f: FnState<Id>) -> Self { self.mock_fns.state_goal = Some(f); self } pub fn with_apply_check(mut self, f: FnApplyCheck<Id>) -> Self { self.mock_fns.apply_check = Some(f); self } pub fn with_apply_dry(mut self, f: FnApply<Id>) -> Self { self.mock_fns.apply_dry = Some(f); self } pub fn with_apply(mut self, f: FnApply<Id>) -> Self { self.mock_fns.apply = Some(f); self } async fn state_current_internal( fn_ctx: FnCtx<'_>, data: MockData<'_, Id>, ) -> Result<MockState, MockItemError> { #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; let mock_state = MockState(data.dest().0); #[cfg(feature = "output_progress")] { let n = u64::from(mock_state.0); fn_ctx.progress_sender.inc(n, ProgressMsgUpdate::NoChange); } Ok(mock_state) } async fn state_goal_internal( fn_ctx: FnCtx<'_>, mock_src: &u8, ) -> Result<MockState, MockItemError> { #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; let mock_state = MockState(*mock_src); #[cfg(feature = "output_progress")] { let n = u64::from(mock_state.0); fn_ctx.progress_sender.inc(n, ProgressMsgUpdate::NoChange); } Ok(mock_state) } } impl<Id> Default for MockItem<Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { fn default() -> Self { Self::new(Self::ID_DEFAULT.clone()) } } #[async_trait(?Send)] impl<Id> Item for MockItem<Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { type Data<'exec> = MockData<'exec, Id>; type Error = MockItemError; type Params<'exec> = MockSrc; type State = MockState; type StateDiff = MockDiff; fn id(&self) -> &ItemId { &self.id } #[cfg(feature = "item_state_example")] fn state_example(params: &Self::Params<'_>, _data: Self::Data<'_>) -> Self::State { MockState(params.0) } async fn state_clean( params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Self::State, MockItemError> { if let Some(state_clean) = data.mock_fns().state_clean.as_ref() { state_clean(params_partial, data) } else { Ok(MockState::new()) } } async fn try_state_current( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, MockItemError> { if let Some(try_state_current) = data.mock_fns().try_state_current.as_ref() { try_state_current(fn_ctx, params_partial, data) } else { Self::state_current_internal(fn_ctx, data).await.map(Some) } } async fn state_current( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, MockItemError> { if let Some(state_current) = data.mock_fns().state_current.as_ref() { state_current(fn_ctx, params, data) } else { Self::state_current_internal(fn_ctx, data).await } } async fn try_state_goal( fn_ctx: FnCtx<'_>, params_partial: &<Self::Params<'_> as Params>::Partial, data: Self::Data<'_>, ) -> Result<Option<Self::State>, MockItemError> { if let Some(try_state_goal) = data.mock_fns().try_state_goal.as_ref() { try_state_goal(fn_ctx, params_partial, data) } else if let Some(mock_src) = params_partial.0.as_ref() { Self::state_goal_internal(fn_ctx, mock_src).await.map(Some) } else { Ok(None) } } async fn state_goal( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, ) -> Result<Self::State, MockItemError> { if let Some(state_goal) = data.mock_fns().state_goal.as_ref() { state_goal(fn_ctx, params, data) } else { Self::state_goal_internal(fn_ctx, &params.0).await } } async fn state_diff( _params_partial: &<Self::Params<'_> as Params>::Partial, _data: MockData<'_, Id>, state_current: &MockState, state_goal: &MockState, ) -> Result<Self::StateDiff, MockItemError> { Ok(MockDiff( i16::from(state_goal.0) - i16::from(state_current.0), )) } async fn apply_check( params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<ApplyCheck, Self::Error> { if let Some(apply_check) = data.mock_fns().apply_check.as_ref() { apply_check(params, data, state_current, state_target, diff) } else { let apply_check = if diff.0 == 0 { ApplyCheck::ExecNotRequired } else { #[cfg(not(feature = "output_progress"))] { let _state_current = state_current; let _state_target = state_target; ApplyCheck::ExecRequired } #[cfg(feature = "output_progress")] { let progress_limit = { let byte_count = u64::from(state_current.0 + state_target.0); ProgressLimit::Bytes(byte_count) }; ApplyCheck::ExecRequired { progress_limit } } }; Ok(apply_check) } } async fn apply_dry( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { if let Some(apply_dry) = data.mock_fns().apply_dry.as_ref() { apply_dry(fn_ctx, params, data, state_current, state_target, diff) } else { // Would replace mock_dest's contents with mock_src's Ok(state_target.clone()) } } async fn apply( fn_ctx: FnCtx<'_>, params: &Self::Params<'_>, mut data: Self::Data<'_>, state_current: &Self::State, state_target: &Self::State, diff: &Self::StateDiff, ) -> Result<Self::State, Self::Error> { if let Some(apply) = data.mock_fns().apply.as_ref() { apply(fn_ctx, params, data, state_current, state_target, diff) } else { let dest = data.dest_mut(); dest.0 = state_target.0; #[cfg(not(feature = "output_progress"))] let _fn_ctx = fn_ctx; #[cfg(feature = "output_progress")] { let n = state_target.0.into(); fn_ctx.progress_sender().inc(n, ProgressMsgUpdate::NoChange); } Ok(state_target.clone()) } } async fn setup(&self, resources: &mut Resources<Empty>) -> Result<(), MockItemError> { resources.insert(self.mock_fns.clone()); let mock_dest = { let states_current_stored = <RMaybe<'_, StatesCurrentStored> as Data>::borrow(Self::ID_DEFAULT, resources); let mock_state_current_stored: Option<&'_ MockState> = states_current_stored .as_ref() .and_then(|states_current_stored| states_current_stored.get(self.id())); if let Some(mock_state) = mock_state_current_stored { MockDest(mock_state.0) } else { MockDest::default() } }; resources.insert(mock_dest); Ok(()) } #[cfg(feature = "item_interactions")] fn interactions( _params: &Self::Params<'_>, _data: Self::Data<'_>, ) -> Vec<peace::item_interaction_model::ItemInteraction> { use peace::item_interaction_model::{ItemInteractionWithin, ItemLocation}; vec![ItemInteractionWithin::new(vec![ItemLocation::localhost()].into()).into()] } } #[cfg(feature = "error_reporting")] use peace::miette; /// Error while executing a Mock. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum MockItemError { /// A synthetic error. #[error("Synthetic error: {}.", _0)] Synthetic(String), /// A `peace` runtime error occurred. #[error("A `peace` runtime error occurred.")] PeaceRtError( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace::rt_model::Error, ), } #[derive(Data, Debug)] pub struct MockData<'exec, Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { /// Mock functions for this item. mock_fns: R<'exec, MockFns<Id>>, /// Destination `Vec` to write to. dest: W<'exec, MockDest>, } impl<Id> MockData<'_, Id> where Id: Clone + Debug + Default + Send + Sync + 'static, { pub fn mock_fns(&self) -> &MockFns<Id> { &self.mock_fns } pub fn dest(&self) -> &MockDest { &self.dest } pub fn dest_mut(&mut self) -> &mut MockDest { &mut self.dest } } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Params)] pub struct MockSrc(pub u8); impl Deref for MockSrc { type Target = u8; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for MockSrc { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for MockSrc { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct MockDest(pub u8); impl Deref for MockDest { type Target = u8; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for MockDest { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for MockDest { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct MockState(pub u8); impl MockState { /// Returns an empty `MockState`. pub fn new() -> Self { Self(0) } } impl Deref for MockState { type Target = u8; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for MockState { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for MockState { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[cfg(feature = "output_progress")] impl<'state> From<&'state MockState> for ItemLocationState { fn from(_mock_state: &'state MockState) -> ItemLocationState { ItemLocationState::Exists } } #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] pub struct MockDiff(pub i16); impl Deref for MockDiff { type Target = i16; fn deref(&self) -> &Self::Target { &self.0 } } impl DerefMut for MockDiff { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl fmt::Display for MockDiff { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[cfg(test)] mod tests { use crate::mock_item::{MockDest, MockDiff, MockItem, MockSrc, MockState}; #[test] fn clone() { let _mock_item = Clone::clone(&MockItem::<()>::default()); let _mock_src = Clone::clone(&MockSrc::default()); let _mock_dest = Clone::clone(&MockDest::default()); let _mock_state = Clone::clone(&MockState::default()); let _mock_diff = Clone::clone(&MockDiff::default()); } #[test] fn deref() { let mock_src = MockSrc::default(); let mock_dest = MockDest::default(); let mock_state = MockState::default(); let mock_diff = MockDiff::default(); assert_eq!(0, *mock_src); assert_eq!(0, *mock_dest); assert_eq!(0, *mock_state); assert_eq!(0, *mock_diff); } #[test] fn deref_mut() { let mut mock_src = MockSrc::default(); let mut mock_dest = MockDest::default(); let mut mock_state = MockState::default(); let mut mock_diff = MockDiff::default(); *mock_src = 1; *mock_dest = 1; *mock_state = 1; *mock_diff = 1; assert_eq!(1, *mock_src); assert_eq!(1, *mock_dest); assert_eq!(1, *mock_state); assert_eq!(1, *mock_diff); } #[test] fn display() { let mock_src = MockSrc::default(); let mock_dest = MockDest::default(); let mock_state = MockState::default(); let mock_diff = MockDiff::default(); assert_eq!("0", format!("{mock_src}")); assert_eq!("0", format!("{mock_dest}")); assert_eq!("0", format!("{mock_state}")); assert_eq!("0", format!("{mock_diff}")); } #[test] fn debug() { let mock_item = MockItem::<()>::default(); let mock_src = MockSrc::default(); let mock_dest = MockDest::default(); let mock_state = MockState::default(); let mock_diff = MockDiff::default(); assert_eq!( "MockItem { \ id: ItemId(\"mock\"), \ mock_fns: MockFns { \ state_clean: None, \ try_state_current: None, \ state_current: None, \ try_state_goal: None, \ state_goal: None, \ apply_check: None, \ apply_dry: None, \ apply: None, \ marker: PhantomData<()> \ } \ }", format!("{mock_item:?}") ); assert_eq!("MockSrc(0)", format!("{mock_src:?}")); assert_eq!("MockDest(0)", format!("{mock_dest:?}")); assert_eq!("MockState(0)", format!("{mock_state:?}")); assert_eq!("MockDiff(0)", format!("{mock_diff:?}")); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cli.rs
workspace_tests/src/cli.rs
mod output;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/no_op_output.rs
workspace_tests/src/no_op_output.rs
use std::convert::Infallible; use peace::{cfg::async_trait, fmt::Presentable, rt_model::output::OutputWrite}; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace::{ item_interaction_model::ItemLocationState, item_model::ItemId, progress_model::{CmdBlockItemInteractionType, ProgressTracker, ProgressUpdateAndId}, rt_model::CmdProgressTracker, }; } } /// An `OutputWrite` implementation that does nothing. #[derive(Debug)] pub struct NoOpOutput; #[async_trait(?Send)] impl OutputWrite for NoOpOutput { type Error = Infallible; #[cfg(feature = "output_progress")] async fn progress_begin(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} #[cfg(feature = "output_progress")] async fn cmd_block_start( &mut self, _cmd_block_item_interaction_type: CmdBlockItemInteractionType, ) { } #[cfg(feature = "output_progress")] async fn item_location_state( &mut self, _item_id: ItemId, _item_location_state: ItemLocationState, ) { } #[cfg(feature = "output_progress")] async fn progress_update( &mut self, _progress_tracker: &ProgressTracker, _progress_update_and_id: &ProgressUpdateAndId, ) { } #[cfg(feature = "output_progress")] async fn progress_end(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} async fn present<P>(&mut self, _presentable: P) -> Result<(), Self::Error> where P: Presentable, { Ok(()) } #[cfg(not(feature = "error_reporting"))] async fn write_err<E>(&mut self, _error: &E) -> Result<(), Self::Error> where E: std::error::Error, { Ok(()) } #[cfg(feature = "error_reporting")] async fn write_err<E>(&mut self, _error: &E) -> Result<(), Self::Error> where E: miette::Diagnostic, { Ok(()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/rt.rs
workspace_tests/src/rt.rs
mod cmd_blocks; mod cmds;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fn_tracker_presenter.rs
workspace_tests/src/fn_tracker_presenter.rs
use peace::fmt::{async_trait, presentable::HeadingLevel, Presentable, Presenter}; use crate::{fn_name::fn_name_short, FnInvocation}; /// Tracks `Presenter` function calls. /// /// Formats `Presentable` data as markdown on the CLI. #[derive(Debug, Default, PartialEq, Eq)] pub struct FnTrackerPresenter { /// List of function invocations. fn_invocations: Vec<FnInvocation>, } impl FnTrackerPresenter { /// Returns a new `FnTrackerPresenter`. pub fn new() -> Self { Self::default() } /// Returns the recorded function invocations. pub fn fn_invocations(&self) -> &[FnInvocation] { self.fn_invocations.as_ref() } } #[async_trait(?Send)] impl Presenter<'static> for FnTrackerPresenter { type Error = std::io::Error; async fn heading<P>( &mut self, heading_level: HeadingLevel, _presentable: &P, ) -> Result<(), Self::Error> where P: Presentable + ?Sized, { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{heading_level:?}")), None], )); Ok(()) } async fn id(&mut self, id: &str) -> Result<(), Self::Error> { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{id:?}"))], )); Ok(()) } async fn name(&mut self, name: &str) -> Result<(), Self::Error> { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{name:?}"))], )); Ok(()) } async fn text(&mut self, text: &str) -> Result<(), Self::Error> { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{text:?}"))], )); Ok(()) } async fn bold<P>(&mut self, _presentable: &P) -> Result<(), Self::Error> where P: Presentable + ?Sized, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None])); Ok(()) } async fn tag(&mut self, tag: &str) -> Result<(), Self::Error> { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{tag:?}"))], )); Ok(()) } async fn code_inline(&mut self, code: &str) -> Result<(), Self::Error> { self.fn_invocations.push(FnInvocation::new( fn_name_short!(), vec![Some(format!("{code:?}"))], )); Ok(()) } async fn list_numbered<'f, P, I>(&mut self, _iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None])); Ok(()) } async fn list_numbered_with<'f, P, I, T, F>( &mut self, _iter: I, _f: F, ) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None, None])); Ok(()) } async fn list_numbered_aligned<'f, P0, P1, I>(&mut self, _iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None])); Ok(()) } async fn list_numbered_aligned_with<'f, P0, P1, I, T, F>( &mut self, _iter: I, _f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1), { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None, None])); Ok(()) } async fn list_bulleted<'f, P, I>(&mut self, _iter: I) -> Result<(), Self::Error> where P: Presentable + ?Sized + 'f, I: IntoIterator<Item = &'f P>, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None])); Ok(()) } async fn list_bulleted_with<'f, P, I, T, F>( &mut self, _iter: I, _f: F, ) -> Result<(), Self::Error> where P: Presentable, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> P, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None, None])); Ok(()) } async fn list_bulleted_aligned<'f, P0, P1, I>(&mut self, _iter: I) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = &'f (P0, P1)>, { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None])); Ok(()) } async fn list_bulleted_aligned_with<'f, P0, P1, I, T, F>( &mut self, _iter: I, _f: F, ) -> Result<(), Self::Error> where P0: Presentable + 'f, P1: Presentable + 'f, I: IntoIterator<Item = T>, T: 'f, F: Fn(T) -> &'f (P0, P1), { self.fn_invocations .push(FnInvocation::new(fn_name_short!(), vec![None, None])); Ok(()) } } #[tokio::test] async fn coverage() -> Result<(), std::io::Error> { let mut fn_tracker_presenter = FnTrackerPresenter::new(); fn_tracker_presenter .heading(HeadingLevel::Level1, "") .await?; fn_tracker_presenter.id("the_id").await?; fn_tracker_presenter.name("the_name").await?; fn_tracker_presenter.text("the_text").await?; fn_tracker_presenter.bold("").await?; fn_tracker_presenter.tag("the_tag").await?; fn_tracker_presenter.code_inline("the_code_inline").await?; fn_tracker_presenter .list_numbered(std::iter::once("abc")) .await?; fn_tracker_presenter .list_numbered_with(std::iter::once("abc"), std::convert::identity) .await?; fn_tracker_presenter .list_numbered_aligned(std::iter::once(&("abc", "def"))) .await?; fn_tracker_presenter .list_numbered_aligned_with(std::iter::once(&("abc", "def")), std::convert::identity) .await?; fn_tracker_presenter .list_bulleted(std::iter::once("abc")) .await?; fn_tracker_presenter .list_bulleted_with(std::iter::once("abc"), std::convert::identity) .await?; fn_tracker_presenter .list_bulleted_aligned(std::iter::once(&("abc", "def"))) .await?; fn_tracker_presenter .list_bulleted_aligned_with(std::iter::once(&("abc", "def")), std::convert::identity) .await?; [ FnInvocation::new("heading", vec![Some(String::from("Level1")), None]), FnInvocation::new("id", vec![Some(String::from("\"the_id\""))]), FnInvocation::new("name", vec![Some(String::from("\"the_name\""))]), FnInvocation::new("text", vec![Some(String::from("\"the_text\""))]), FnInvocation::new("bold", vec![None]), FnInvocation::new("tag", vec![Some(String::from("\"the_tag\""))]), FnInvocation::new( "code_inline", vec![Some(String::from("\"the_code_inline\""))], ), FnInvocation::new("list_numbered", vec![None]), FnInvocation::new("list_numbered_with", vec![None, None]), FnInvocation::new("list_numbered_aligned", vec![None]), FnInvocation::new("list_numbered_aligned_with", vec![None, None]), FnInvocation::new("list_bulleted", vec![None]), FnInvocation::new("list_bulleted_with", vec![None, None]), FnInvocation::new("list_bulleted_aligned", vec![None]), FnInvocation::new("list_bulleted_aligned_with", vec![None, None]), ] .into_iter() .zip(fn_tracker_presenter.fn_invocations().iter()) .for_each(|(expected, actual)| assert_eq!(&expected, actual)); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/item_model.rs
workspace_tests/src/item_model.rs
mod item_id; mod item_id_invalid_fmt;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fn_name.rs
workspace_tests/src/fn_name.rs
/// Returns the simple name of the function this macro is called in. macro_rules! fn_name_short { () => {{ fn f() {} fn type_name_of<T>(_: T) -> &'static str { std::any::type_name::<T>() } let name = type_name_of(f); let full_name = &name[..name.len() - 3]; // Trim away wrapping closure name if this is enclosed in one. match full_name.rfind("::{{closure}}") { Some(pos) => { let full_name = &full_name[..pos]; // Find and cut the rest of the path match full_name[..full_name.len()].rfind(':') { Some(pos) => &full_name[pos + 1..], None => full_name, } } None => { // Find and cut the rest of the path match full_name.rfind(':') { Some(pos) => &full_name[pos + 1..full_name.len()], None => full_name, } } } }}; } pub(crate) use fn_name_short;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model.rs
workspace_tests/src/cmd_model.rs
mod cmd_block_outcome; mod cmd_execution_error; mod cmd_outcome; mod item_stream_outcome;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/test_support.rs
workspace_tests/src/test_support.rs
use futures::stream::{self, StreamExt, TryStreamExt}; use peace::{ cfg::AppName, flow_model::FlowId, params::ParamsSpecs, profile_model::Profile, resource_rt::{ internal::{FlowParamsFile, ProfileParamsFile, WorkspaceParamsFile}, paths::{FlowDir, ParamsSpecsFile, ProfileDir}, resources::ts::SetUp, Resources, }, rt_model::{ params::{FlowParams, ProfileParams, WorkspaceParams}, Error, ParamsSpecsSerializer, Storage, Workspace, WorkspaceSpec, }, }; use crate::cmd_ctx::{FlowParamsKey, ProfileParamsKey, WorkspaceParamsKey}; pub(crate) async fn workspace( tempdir: &tempfile::TempDir, app_name: AppName, ) -> Result<Workspace, Box<dyn std::error::Error>> { let workspace = { let workspace_spec = WorkspaceSpec::Path(tempdir.path().to_path_buf()); Workspace::new(app_name, workspace_spec)? }; let peace_app_dir = workspace.dirs().peace_app_dir(); tokio::fs::create_dir_all(peace_app_dir).await?; Ok(workspace) } /// Returns a workspace with profile directories already created within it. pub(crate) async fn workspace_with( tempdir: &tempfile::TempDir, app_name: AppName, profiles_existing: &[Profile], flow_id: Option<&FlowId>, ) -> Result<Workspace, Box<dyn std::error::Error>> { let workspace = { let workspace_spec = WorkspaceSpec::Path(tempdir.path().to_path_buf()); Workspace::new(app_name, workspace_spec)? }; let peace_app_dir = workspace.dirs().peace_app_dir(); tokio::fs::create_dir_all(peace_app_dir).await?; let workspace_params_file = WorkspaceParamsFile::from(peace_app_dir); let mut workspace_params = WorkspaceParams::new(); workspace_params.insert(WorkspaceParamsKey::Profile, profiles_existing[0].clone()); workspace_params.insert( WorkspaceParamsKey::StringParam, String::from("ws_param_1_value"), ); workspace_params.insert(WorkspaceParamsKey::U8Param, 1u8); Storage .serialized_write( crate::fn_name_short!().to_string(), &workspace_params_file, &workspace_params, Error::WorkspaceParamsSerialize, ) .await?; let profile_dirs = profiles_existing .iter() .map(|profile| ProfileDir::from((peace_app_dir, profile))); stream::iter(profile_dirs) .map(Result::<_, Box<dyn std::error::Error>>::Ok) .try_for_each(|profile_dir| async move { tokio::fs::create_dir_all(&profile_dir).await?; let profile_params_file = ProfileParamsFile::from(&profile_dir); let mut profile_params = ProfileParams::new(); profile_params.insert(ProfileParamsKey::U32Param, 1u32); profile_params.insert(ProfileParamsKey::U64Param, 2u64); Storage .serialized_write( crate::fn_name_short!().to_string(), &profile_params_file, &profile_params, Error::ProfileParamsSerialize, ) .await?; if let Some(flow_id) = flow_id { let flow_dir = FlowDir::from((&profile_dir, flow_id)); tokio::fs::create_dir_all(&flow_dir).await?; let flow_params_file = FlowParamsFile::from(&flow_dir); let mut flow_params = FlowParams::new(); flow_params.insert(FlowParamsKey::BoolParam, true); flow_params.insert(FlowParamsKey::U16Param, 456u16); let storage = Storage; storage .serialized_write( crate::fn_name_short!().to_string(), &flow_params_file, &flow_params, Error::FlowParamsSerialize, ) .await?; // Empty item params specs. let params_specs = ParamsSpecs::new(); let params_specs_file = ParamsSpecsFile::from(&flow_dir); ParamsSpecsSerializer::<peace::rt_model::Error>::serialize( &storage, &params_specs, &params_specs_file, ) .await?; } Ok(()) }) .await?; Ok(workspace) } pub(crate) async fn assert_workspace_params( resources: &Resources<SetUp>, ) -> Result<(), std::io::Error> { let workspace_params_file = resources.borrow::<WorkspaceParamsFile>(); let res_ws_param_1 = resources.borrow::<String>(); assert!(workspace_params_file.exists()); assert_eq!( "profile: test_profile\n\ string_param: ws_param_1_value\n", tokio::fs::read_to_string(&*workspace_params_file).await? ); assert_eq!("ws_param_1_value", res_ws_param_1.as_str()); Ok(()) } pub(crate) async fn assert_profile_params( resources: &Resources<SetUp>, ) -> Result<(), std::io::Error> { let profile_params_file = resources.borrow::<ProfileParamsFile>(); let res_profile_param_0 = resources.borrow::<u32>(); let res_profile_param_1 = resources.borrow::<u64>(); assert!(profile_params_file.exists()); assert_eq!( "u32_param: 1\n\ u64_param: 2\n", tokio::fs::read_to_string(&*profile_params_file).await? ); assert_eq!(1u32, *res_profile_param_0); assert_eq!(2u64, *res_profile_param_1); Ok(()) } pub(crate) async fn assert_flow_params(resources: &Resources<SetUp>) -> Result<(), std::io::Error> { let flow_params_file = resources.borrow::<FlowParamsFile>(); let res_flow_param_0 = resources.borrow::<bool>(); let res_flow_param_1 = resources.borrow::<u16>(); assert!(flow_params_file.exists()); assert_eq!( "bool_param: true\n\ u16_param: 456\n", tokio::fs::read_to_string(&*flow_params_file).await? ); assert!(*res_flow_param_0); assert_eq!(456u16, *res_flow_param_1); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/flow_model.rs
workspace_tests/src/flow_model.rs
mod flow_id; mod flow_id_invalid_fmt; mod flow_info; mod flow_spec_info; mod item_info; mod item_spec_info;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fn_invocation.rs
workspace_tests/src/fn_invocation.rs
/// Information about a function invocation. #[derive(Debug, PartialEq, Eq)] pub struct FnInvocation { /// Simple name of the function invoked. name: &'static str, /// Debug values of arguments to the function. /// /// A `None` means that that arguments to the function is not tracked, /// possibly because it does not implement `Debug`. args: Vec<Option<String>>, } impl FnInvocation { /// Returns a new `FnInvocation`. pub fn new(name: &'static str, args: Vec<Option<String>>) -> Self { Self { name, args } } // Currently we only use the `PartialEq` implementation to read the values. // /// Returns the simple name of the invoked function. // pub fn name(&self) -> &str { // self.name // } // /// Returns the argument debug strings. // pub fn args(&self) -> &[Option<String>] { // self.args.as_ref() // } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/resource_rt.rs
workspace_tests/src/resource_rt.rs
mod dir; mod internal; mod resources; mod state_diffs; mod states;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/webi.rs
workspace_tests/src/webi.rs
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/peace_test_error.rs
workspace_tests/src/peace_test_error.rs
use std::convert::Infallible; #[cfg(feature = "error_reporting")] use peace::miette; /// Error while running a workspace test. /// /// Error type for tests that need an error for their item graphs and /// command contexts. #[cfg_attr(feature = "error_reporting", derive(peace::miette::Diagnostic))] #[derive(Debug, thiserror::Error)] pub enum PeaceTestError { /// Flow ID is invalid. #[error("Flow ID is invalid.")] FlowIdInvalidFmt( #[source] #[from] peace::flow_model::FlowIdInvalidFmt<'static>, ), /// Failed to initialize tempdir. #[error("Failed to initialize tempdir.")] TempDir( #[source] #[from] std::io::Error, ), /// A VecCopy item error occurred. #[error("A VecCopy item error occurred.")] VecCopy( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::VecCopyError, ), /// A Mock item error occurred. #[error("A Mock item error occurred.")] Mock( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] crate::mock_item::MockItemError, ), /// A Blank item error occurred. #[error("A Blank item error occurred.")] Blank( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace_items::blank::BlankError, ), /// A `peace` runtime error occurred. #[error("A `peace` runtime error occurred.")] PeaceRt( #[cfg_attr(feature = "error_reporting", diagnostic_source)] #[source] #[from] peace::rt_model::Error, ), } impl From<Infallible> for PeaceTestError { fn from(_infallible: Infallible) -> Self { unreachable!("By definition the `Infallible` error can never be reached."); } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/data.rs
workspace_tests/src/data.rs
mod derive; mod marker; mod r_maybe; mod w_maybe;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cfg.rs
workspace_tests/src/cfg.rs
mod app_name; mod apply_check; mod state; mod stored;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/state_rt.rs
workspace_tests/src/state_rt.rs
mod states_serializer;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fmt.rs
workspace_tests/src/fmt.rs
use peace::{ cli::output::{CliColorizeOpt, CliOutput, CliOutputBuilder}, cli_model::OutputFormat, }; mod either; mod presentable; /// Returns a new `CliOutput` with `OutputFormat::Text`. fn cli_output(colorize: CliColorizeOpt) -> CliOutput<Vec<u8>> { CliOutputBuilder::new_with_writer(Vec::new()) .with_outcome_format(OutputFormat::Text) .with_colorize(colorize) .build() }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/fn_tracker_output.rs
workspace_tests/src/fn_tracker_output.rs
use peace::{ cfg::async_trait, fmt::Presentable, rt_model::{self, output::OutputWrite}, }; use crate::FnInvocation; cfg_if::cfg_if! { if #[cfg(feature = "output_progress")] { use peace::{ item_interaction_model::ItemLocationState, item_model::ItemId, progress_model::{CmdBlockItemInteractionType, ProgressTracker, ProgressUpdateAndId}, rt_model::CmdProgressTracker, }; } } /// An `OutputWrite` implementation that tracks function invocations. #[derive(Debug, Default, PartialEq, Eq)] pub struct FnTrackerOutput { /// List of function invocations. fn_invocations: Vec<FnInvocation>, } impl FnTrackerOutput { /// Returns a new `FnTrackerOutput`. pub fn new() -> Self { Self::default() } /// Returns the recorded function invocations. pub fn fn_invocations(&self) -> &[FnInvocation] { self.fn_invocations.as_ref() } } #[async_trait(?Send)] impl OutputWrite for FnTrackerOutput { type Error = rt_model::Error; #[cfg(feature = "output_progress")] async fn progress_begin(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} #[cfg(feature = "output_progress")] async fn cmd_block_start( &mut self, _cmd_block_item_interaction_type: CmdBlockItemInteractionType, ) { } #[cfg(feature = "output_progress")] async fn item_location_state( &mut self, _item_id: ItemId, _item_location_state: ItemLocationState, ) { } #[cfg(feature = "output_progress")] async fn progress_update( &mut self, _progress_tracker: &ProgressTracker, _progress_update_and_id: &ProgressUpdateAndId, ) { } #[cfg(feature = "output_progress")] async fn progress_end(&mut self, _cmd_progress_tracker: &CmdProgressTracker) {} async fn present<P>(&mut self, presentable: P) -> Result<(), Self::Error> where P: Presentable, { let presentable_serialized = serde_yaml::to_string(&presentable).map_err(rt_model::Error::PresentableSerialize)?; self.fn_invocations.push(FnInvocation::new( "present", vec![Some(presentable_serialized)], )); Ok(()) } #[cfg(not(feature = "error_reporting"))] async fn write_err<E>(&mut self, error: &E) -> Result<(), Self::Error> where E: std::error::Error, { self.fn_invocations.push(FnInvocation::new( "write_err", vec![Some(format!("{error:?}"))], )); Ok(()) } #[cfg(feature = "error_reporting")] async fn write_err<E>(&mut self, error: &E) -> Result<(), Self::Error> where E: miette::Diagnostic, { self.fn_invocations.push(FnInvocation::new( "write_err", vec![Some(format!("{error:?}"))], )); Ok(()) } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/rt_model.rs
workspace_tests/src/rt_model.rs
#[cfg(feature = "error_reporting")] mod error; #[cfg(feature = "output_in_memory")] mod in_memory_text_output; mod item_boxed; mod item_graph; mod item_graph_builder; mod item_wrapper; mod native; mod outcomes; mod params; mod storage; mod workspace_dirs_builder;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/any_spec_rt.rs
workspace_tests/src/params/any_spec_rt.rs
use peace::params::{AnySpecRt, AnySpecRtBoxed, ParamsSpec}; use crate::mock_item::MockSrc; #[test] fn is_usable_returns_true_for_deserialized_mapping_fn() -> Result<(), serde_yaml::Error> { let params_spec: ParamsSpec<MockSrc> = serde_yaml::from_str( r#"!MappingFn field_name: !Some "field_name" mapping_fn_id: "mapping_fn_id" "#, )?; assert!(AnySpecRt::is_usable(&Box::new(params_spec))); Ok(()) } #[test] fn is_usable_returns_true_for_usable_params_spec() { let params_spec: ParamsSpec<MockSrc> = ParamsSpec::<MockSrc>::InMemory; assert!(AnySpecRt::is_usable(&params_spec)); } #[test] fn merge_delegates_to_underlying_type() { let mut params_spec_a = Box::new(ParamsSpec::<MockSrc>::Stored); let params_spec_b = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::InMemory); AnySpecRt::merge(&mut params_spec_a, &*params_spec_b); assert!(matches!(&*params_spec_a, ParamsSpec::<MockSrc>::InMemory)); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/value_resolution_mode.rs
workspace_tests/src/params/value_resolution_mode.rs
use peace::params::ValueResolutionMode; #[test] fn serialize() -> Result<(), serde_yaml::Error> { assert_eq!( "Current\n", serde_yaml::to_string(&ValueResolutionMode::Current)? ); Ok(()) } #[test] fn deserialize() -> Result<(), serde_yaml::Error> { assert_eq!( ValueResolutionMode::Current, serde_yaml::from_str("Current")? ); Ok(()) }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/params_spec.rs
workspace_tests/src/params/params_spec.rs
use peace::{ enum_iterator::Sequence, item_model::item_id, params::{ AnySpecRt, AnySpecRtBoxed, FieldNameAndType, FieldWiseSpecRt, FromFunc, MappingFn, MappingFnId, MappingFnImpl, MappingFnReg, MappingFns, Params, ParamsResolveError, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, ValueSpecRt, }, resource_rt::{resources::ts::SetUp, Resources}, }; use serde::{Deserialize, Serialize}; use crate::{ mock_item::{MockSrc, MockSrcFieldWise}, vec_copy_item::{VecA, VecAFieldWise}, }; #[test] fn clone() { let _params_spec = ParamsSpec::<MockSrc>::Value { value: MockSrc(1) }.clone(); } #[test] fn debug() { assert_eq!("Stored", format!("{:?}", ParamsSpec::<MockSrc>::Stored)); assert_eq!( "Value { value: MockSrc(1) }", format!("{:?}", ParamsSpec::<MockSrc>::Value { value: MockSrc(1) }) ); assert_eq!("InMemory", format!("{:?}", ParamsSpec::<MockSrc>::InMemory)); assert_eq!( "MappingFn { \ field_name: Some(\"field\"), \ mapping_fn_id: MappingFnId(\"MockSrcFromU8\") \ }", format!( "{:?}", ParamsSpec::<MockSrc>::mapping_fn( Some(String::from("field")), TestMappingFns::MockSrcFromU8 ) ) ); assert_eq!( "FieldWise { field_wise_spec: MockSrcFieldWise(Stored) }", format!("{:?}", <MockSrc as Params>::field_wise_spec().build()) ); } #[test] fn serialize_stored() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = <VecA as Params>::Spec::Stored; assert_eq!( r#"Stored "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_value() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = VecA(vec![1u8]).into(); assert_eq!( r#"!Value value: - 1 "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_in_memory() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = <VecA as Params>::Spec::InMemory; assert_eq!( r#"InMemory "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_mapping_fn() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = ParamsSpec::<VecA>::mapping_fn(None, TestMappingFns::MockSrcFromU8); assert_eq!( r#"!MappingFn field_name: null mapping_fn_id: MockSrcFromU8 "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_field_wise_stored() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = VecA::field_wise_spec().build(); assert_eq!( r#"!FieldWise field_wise_spec: Stored "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_field_wise_value() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = VecA::field_wise_spec().with_0(vec![1u8]).build(); assert_eq!( r#"!FieldWise field_wise_spec: !Value value: - 1 "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_field_wise_in_memory() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = VecA::field_wise_spec().with_0_in_memory().build(); assert_eq!( r#"!FieldWise field_wise_spec: InMemory "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn serialize_field_wise_mapping_fn() -> Result<(), serde_yaml::Error> { let vec_a_spec: <VecA as Params>::Spec = VecA::field_wise_spec() .with_0_from_mapping_fn(TestMappingFns::VecU8FromBoolAndU16) .build(); assert_eq!( r#"!FieldWise field_wise_spec: !MappingFn field_name: _0 mapping_fn_id: VecU8FromBoolAndU16 "#, serde_yaml::to_string(&vec_a_spec)?, ); Ok(()) } #[test] fn deserialize_stored() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"Stored "# )?, ParamsSpec::<VecA>::Stored )); Ok(()) } #[test] fn deserialize_value() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"!Value value: - 1 "# )?, ParamsSpec::<VecA>::Value { value: VecA(vec_u8) } if vec_u8 == [1u8] )); Ok(()) } #[test] fn deserialize_in_memory() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"InMemory "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!(&deserialized, ParamsSpec::<VecA>::InMemory), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_from_mapping_fn() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"!MappingFn field_name: serialized_field_name mapping_fn_id: VecU8FromBoolAndU16 "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ParamsSpec::<VecA>::MappingFn { field_name: Some(field_name), mapping_fn_id, } if field_name == "serialized_field_name" && mapping_fn_id == &TestMappingFns::VecU8FromBoolAndU16.id() ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_field_wise_value() -> Result<(), Box<dyn std::error::Error>> { let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("deserialize_field_wise"), tynm::type_name::<VecA>(), ); let mapping_fn_reg = MappingFnReg::new(); let deserialized = serde_yaml::from_str( r#"!FieldWise field_wise_spec: !Value value: - 1 "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ParamsSpec::<VecA>::FieldWise { field_wise_spec: field_wise_spec @ VecAFieldWise(ValueSpec::<Vec<u8>>::Value { value, }) } if value == &[1u8] && FieldWiseSpecRt::resolve( field_wise_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx ) .expect("expected value to be resolved.") == VecA(vec![1u8]) ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_field_wise_in_memory() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"!FieldWise field_wise_spec: InMemory "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ParamsSpec::<VecA>::FieldWise { field_wise_spec: VecAFieldWise(ValueSpec::<Vec<u8>>::InMemory) } ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_field_wise_mapping_fn() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"!FieldWise field_wise_spec: !MappingFn field_name: serialized_field_name mapping_fn_id: VecU8FromBoolAndU16 "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ParamsSpec::<VecA>::FieldWise { field_wise_spec: VecAFieldWise(ValueSpec::<Vec<u8>>::MappingFn { field_name: Some(field_name), mapping_fn_id, }) } if field_name == "serialized_field_name" && mapping_fn_id == &TestMappingFns::VecU8FromBoolAndU16.id() ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn is_usable_returns_false_for_stored() { assert!(!ParamsSpec::<VecA>::Stored.is_usable()); } #[test] fn is_usable_returns_true_for_value_and_in_memory() { assert!(ParamsSpec::<VecA>::Value { value: VecA::default() } .is_usable()); assert!(ParamsSpec::<VecA>::InMemory.is_usable()); } #[test] fn is_usable_returns_true_when_mapping_fn_is_some() { assert!(ParamsSpec::<VecA>::MappingFn { field_name: None, mapping_fn_id: TestMappingFns::VecU8FromBoolAndU16.id() } .is_usable()); } #[test] fn is_usable_returns_true_for_deserialized_mapping_fn() -> Result<(), serde_yaml::Error> { let params_spec: ParamsSpec<VecA> = serde_yaml::from_str( r#"!MappingFn field_name: null mapping_fn_id: VecU8FromBoolAndU16 "#, )?; assert!(params_spec.is_usable()); Ok(()) } #[test] fn is_usable_returns_true_when_field_wise_is_usable() -> Result<(), serde_yaml::Error> { let params_spec: ParamsSpec<VecA> = serde_yaml::from_str( r#"!FieldWise field_wise_spec: InMemory "#, )?; assert!(params_spec.is_usable()); Ok(()) } #[test] fn is_usable_returns_true_when_field_wise_with_mapping_fn_is_deserialized( ) -> Result<(), serde_yaml::Error> { let params_spec: ParamsSpec<VecA> = serde_yaml::from_str( r#"!FieldWise field_wise_spec: !MappingFn field_name: field_name mapping_fn_id: VecU8FromBoolAndU16 "#, )?; assert!(params_spec.is_usable()); Ok(()) } #[test] fn is_usable_returns_false_when_field_wise_contains_stored() -> Result<(), serde_yaml::Error> { let params_spec = ParamsSpec::<VecA>::FieldWise { field_wise_spec: VecAFieldWise(ValueSpec::<Vec<u8>>::Stored), }; assert!(!params_spec.is_usable()); Ok(()) } #[test] fn resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::Stored; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemory { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_not_found") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be `Err(ParamsResolveError::InMemory {{ .. }})`\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn() -> Result<(), ParamsResolveError> { let test_mapping_fn = TestMappingFns::MockSrcFromU8; let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.insert(test_mapping_fn.id(), test_mapping_fn.mapping_fn()); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::mapping_fn(None, test_mapping_fn); let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let test_mapping_fn = TestMappingFns::MockSrcFromU8AndU16; let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.insert(test_mapping_fn.id(), test_mapping_fn.mapping_fn()); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::mapping_fn(None, test_mapping_fn); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_field_wise() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_field_wise"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = MockSrc::field_wise_spec().with_0_in_memory().build(); let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_field_wise_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_field_wise_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = MockSrc::field_wise_spec().with_0_in_memory().build(); let _u8_mut_borrowed = resources.borrow_mut::<u8>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_field_wise_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain() == [ FieldNameAndType::new(String::from("0"), tynm::type_name::<u8>()) ] ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[(0, u8)]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::Stored; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_none_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_none_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(None, mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn() -> Result<(), ParamsResolveError> { let test_mapping_fn = TestMappingFns::MockSrcFromU8; let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.insert(test_mapping_fn.id(), test_mapping_fn.mapping_fn()); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::mapping_fn(None, test_mapping_fn); let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let test_mapping_fn = TestMappingFns::MockSrcFromU8AndU16; let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.insert(test_mapping_fn.id(), test_mapping_fn.mapping_fn()); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8AndU16); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_field_wise() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_field_wise"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = MockSrc::field_wise_spec().with_0_in_memory().build(); let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_field_wise_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_field_wise_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = MockSrc::field_wise_spec().with_0_in_memory().build(); let _u8_mut_borrowed = resources.borrow_mut::<u8>(); let mock_src_result = &ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_field_wise_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain() == [ FieldNameAndType::new(String::from("0"), tynm::type_name::<u8>()) ] ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[(0, u8)]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn merge_stored_with_other_uses_other() { let mut params_spec_a = ParamsSpec::<MockSrc>::Stored; let params_spec_b = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::InMemory); params_spec_a.merge(&*params_spec_b); assert!(matches!(&params_spec_a, ParamsSpec::<MockSrc>::InMemory)); } #[test] fn merge_value_with_other_no_change() { let mut params_spec_a = ParamsSpec::<MockSrc>::Value { value: MockSrc(1) }; let params_spec_b = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); params_spec_a.merge(&*params_spec_b); assert!( matches!(&params_spec_a, ParamsSpec::<MockSrc>::Value { value } if value == &MockSrc(1)) ); } #[test] fn merge_in_memory_with_other_no_change() { let mut params_spec_a = ParamsSpec::<MockSrc>::InMemory; let params_spec_b = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); params_spec_a.merge(&*params_spec_b); assert!(matches!(&params_spec_a, ParamsSpec::<MockSrc>::InMemory)); } #[test] fn merge_mapping_fn_with_other_no_change() { let mut params_spec_a = ParamsSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8);
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
true
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/any_spec_rt_boxed.rs
workspace_tests/src/params/any_spec_rt_boxed.rs
use std::any::TypeId; use peace::{ params::{AnySpecDataType, AnySpecRtBoxed, ParamsSpec}, resource_rt::type_reg::untagged::{BoxDataTypeDowncast, DataType, DataTypeWrapper}, }; use crate::mock_item::MockSrc; #[test] fn clone() { let _any_spec_rt_boxed = Clone::clone(&AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored)); } #[test] fn debug() { let any_spec_rt_boxed = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored); assert_eq!("AnySpecRtBoxed(Stored)", format!("{any_spec_rt_boxed:?}")); } #[test] fn into_inner() { let boxed_any_spec_rt = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored).into_inner(); let params_spec: &ParamsSpec<MockSrc> = boxed_any_spec_rt.downcast_ref().unwrap_or_else( #[cfg_attr(coverage_nightly, coverage(off))] || panic!("Expected to downcast `boxed_any_spec_rt` to `ParamsSpec<MockSrc>`."), ); assert!(matches!(params_spec, ParamsSpec::<MockSrc>::Stored)); } #[test] fn downcast_mut() { let mut any_spec_rt_boxed = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored); let params_spec: &mut ParamsSpec<MockSrc> = BoxDataTypeDowncast::downcast_mut(&mut any_spec_rt_boxed).unwrap_or_else( #[cfg_attr(coverage_nightly, coverage(off))] || panic!("Expected to downcast `any_spec_rt_boxed` to `ParamsSpec<MockSrc>`."), ); assert!(matches!(params_spec, ParamsSpec::<MockSrc>::Stored)); } #[test] fn data_type_wrapper_type_name() { let any_spec_rt_boxed = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored); assert_eq!( "peace_params::params_spec::ParamsSpec<workspace_tests::mock_item::MockSrc>", format!("{}", DataTypeWrapper::type_name(&any_spec_rt_boxed)), ); } #[test] fn data_type_wrapper_clone() { let _any_spec_rt_boxed = DataTypeWrapper::clone(&AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored)); } #[test] fn data_type_wrapper_debug() { let any_spec_rt_boxed = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored); assert_eq!( "Stored", format!("{:?}", DataTypeWrapper::debug(&any_spec_rt_boxed)) ); } #[test] fn data_type_wrapper_inner() { let any_spec_rt_boxed = AnySpecRtBoxed::new(ParamsSpec::<MockSrc>::Stored); let data_type = DataTypeWrapper::inner(&any_spec_rt_boxed); let data_type_type_id = data_type.type_id_inner(); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { // Not sure if type ID of `Box<dyn AnySpecDataType>` is useful. assert_eq!( TypeId::of::<Box<dyn AnySpecDataType>>(), data_type_type_id, "type name: {}", DataType::type_name(data_type) ); } })(); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/value_resolution_ctx.rs
workspace_tests/src/params/value_resolution_ctx.rs
use peace::{ item_model::item_id, params::{FieldNameAndType, ValueResolutionCtx, ValueResolutionMode}, }; use crate::mock_item::MockSrc; #[test] fn debug() { let value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("item_id"), tynm::type_name::<MockSrc>(), ); assert_eq!( "ValueResolutionCtx { \ value_resolution_mode: Current, \ item_id: ItemId(\"item_id\"), \ params_type_name: \"MockSrc\", \ resolution_chain: [] \ }", format!("{value_resolution_ctx:?}") ); } #[test] fn partial_eq() { let value_resolution_ctx_0 = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("item_id_0"), tynm::type_name::<MockSrc>(), ); let value_resolution_ctx_1 = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("item_id_1"), tynm::type_name::<MockSrc>(), ); assert_eq!(value_resolution_ctx_0, value_resolution_ctx_0); assert_ne!(value_resolution_ctx_0, value_resolution_ctx_1); } #[test] fn display_no_resolution_chain() { let value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("item_id"), tynm::type_name::<MockSrc>(), ); assert_eq!("MockSrc {}", format!("{value_resolution_ctx}")); } #[test] fn display_with_resolution_chain() { let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("item_id"), tynm::type_name::<MockSrc>(), ); value_resolution_ctx.push(FieldNameAndType::new( String::from("intermediate"), String::from("Something"), )); value_resolution_ctx.push(FieldNameAndType::new( String::from("inner"), tynm::type_name::<u8>(), )); assert_eq!( r#"MockSrc { intermediate: Something { inner: u8, .. }, .. }"#, format!("{value_resolution_ctx}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/value_spec.rs
workspace_tests/src/params/value_spec.rs
use peace::{ enum_iterator::Sequence, item_model::item_id, params::{ AnySpecRt, AnySpecRtBoxed, FromFunc, MappingFn, MappingFnId, MappingFnImpl, MappingFnReg, MappingFns, ParamsResolveError, ValueResolutionCtx, ValueResolutionMode, ValueSpec, ValueSpecRt, }, resource_rt::{resources::ts::SetUp, Resources}, }; use serde::{Deserialize, Serialize}; use crate::mock_item::MockSrc; #[test] fn clone() { let _value_spec = ValueSpec::<MockSrc>::Value { value: MockSrc(1) }.clone(); } #[test] fn debug() { assert_eq!("Stored", format!("{:?}", ValueSpec::<MockSrc>::Stored)); assert_eq!( "Value { value: MockSrc(1) }", format!("{:?}", ValueSpec::<MockSrc>::Value { value: MockSrc(1) }) ); assert_eq!("InMemory", format!("{:?}", ValueSpec::<MockSrc>::InMemory)); assert_eq!( "MappingFn { \ field_name: Some(\"field\"), \ mapping_fn_id: MappingFnId(\"MockSrcFromU8\") \ }", format!( "{:?}", ValueSpec::<MockSrc>::mapping_fn( Some(String::from("field")), TestMappingFns::MockSrcFromU8, ) ) ); } #[test] fn serialize_stored() -> Result<(), serde_yaml::Error> { let u8_spec = ValueSpec::<u8>::Stored; assert_eq!( r#"Stored "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_value() -> Result<(), serde_yaml::Error> { let u8_spec: ValueSpec<u8> = 1u8.into(); assert_eq!( r#"!Value value: 1 "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_in_memory() -> Result<(), serde_yaml::Error> { let u8_spec = ValueSpec::<u8>::InMemory; assert_eq!( r#"InMemory "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_mapping_fn() -> Result<(), serde_yaml::Error> { let u8_spec: ValueSpec<u8> = ValueSpec::<u8>::mapping_fn(None, TestMappingFns::MockSrcFromU8); assert_eq!( r#"!MappingFn field_name: null mapping_fn_id: MockSrcFromU8 "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn deserialize_stored() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"Stored "# )?, ValueSpec::<u8>::Stored )); Ok(()) } #[test] fn deserialize_value() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"!Value value: 1 "# )?, ValueSpec::<u8>::Value { value } if value == 1u8 )); Ok(()) } #[test] fn deserialize_in_memory() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"InMemory "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!(&deserialized, ValueSpec::<u8>::InMemory), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_mapping_fn() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"!MappingFn field_name: "serialized_field_name" mapping_fn_id: "U8NoneFromU8" "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ValueSpec::<u8>::MappingFn { field_name: Some(field_name), mapping_fn_id, } if field_name == "serialized_field_name" && mapping_fn_id == &TestMappingFns::U8NoneFromU8.id() ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn is_usable_returns_false_for_stored() { assert!(!ValueSpec::<u8>::Stored.is_usable()); } #[test] fn is_usable_returns_true_for_value_and_in_memory() { assert!(ValueSpec::<u8>::Value { value: 1u8 }.is_usable()); assert!(ValueSpec::<u8>::InMemory.is_usable()); } #[test] fn is_usable_returns_true_when_mapping_fn_is_some() { assert!(ValueSpec::<u8>::mapping_fn(None, TestMappingFns::U8NoneFromU8).is_usable()); } #[test] fn is_usable_returns_true_when_mapping_fn_is_deserialized() -> Result<(), serde_yaml::Error> { let params_spec: ValueSpec<u8> = serde_yaml::from_str( r#"!MappingFn field_name: null mapping_fn_id: U8NoneFromU8 "#, )?; assert!(params_spec.is_usable()); Ok(()) } #[test] fn resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::Stored; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemory { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_not_found") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be `Err(ParamsResolveError::InMemory {{ .. }})`\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8AndU16); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::Stored; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_none_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_none_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(None, mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ValueSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8AndU16); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn merge_stored_with_other_uses_other() { let mut value_spec_a = ValueSpec::<MockSrc>::Stored; let value_spec_b = AnySpecRtBoxed::new(ValueSpec::<MockSrc>::InMemory); value_spec_a.merge(&*value_spec_b); assert!(matches!(&value_spec_a, ValueSpec::<MockSrc>::InMemory)); } #[test] fn merge_value_with_other_no_change() { let mut value_spec_a = ValueSpec::<MockSrc>::Value { value: MockSrc(1) }; let value_spec_b = AnySpecRtBoxed::new(ValueSpec::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); value_spec_a.merge(&*value_spec_b); assert!(matches!(&value_spec_a, ValueSpec::<MockSrc>::Value { value } if value == &MockSrc(1))); } #[test] fn merge_in_memory_with_other_no_change() { let mut value_spec_a = ValueSpec::<MockSrc>::InMemory; let value_spec_b = AnySpecRtBoxed::new(ValueSpec::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); value_spec_a.merge(&*value_spec_b); assert!(matches!(&value_spec_a, ValueSpec::<MockSrc>::InMemory)); } #[test] fn merge_mapping_fn_with_other_no_change() { let mut value_spec_a = ValueSpec::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let value_spec_b = AnySpecRtBoxed::new(ValueSpec::<MockSrc>::InMemory); value_spec_a.merge(&*value_spec_b); assert!(matches!(&value_spec_a, ValueSpec::<MockSrc>::MappingFn { field_name: None, mapping_fn_id, } if mapping_fn_id == &TestMappingFns::MockSrcFromU8.id())); } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] enum TestMappingFns { MockSrcFromU8, MockSrcFromU8AndU16, U8NoneFromU8, } impl MappingFns for TestMappingFns { fn id(self) -> MappingFnId { let name = match self { TestMappingFns::MockSrcFromU8 => "MockSrcFromU8", TestMappingFns::MockSrcFromU8AndU16 => "MockSrcFromU8AndU16", TestMappingFns::U8NoneFromU8 => "U8NoneFromU8", }; MappingFnId::new(name.into()) } fn mapping_fn(self) -> Box<dyn MappingFn> { match self { TestMappingFns::MockSrcFromU8 => MappingFnImpl::from_func(|n: &u8| Some(MockSrc(*n))), TestMappingFns::MockSrcFromU8AndU16 => { MappingFnImpl::from_func(|n: &u8, _: &u16| Some(MockSrc(*n))) } TestMappingFns::U8NoneFromU8 => MappingFnImpl::from_func(|_: &u8| Option::<u8>::None), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/field_name_and_type.rs
workspace_tests/src/params/field_name_and_type.rs
use peace::params::FieldNameAndType; #[test] fn debug() { let field_name_and_type = FieldNameAndType::new(String::from("field"), String::from("Type")); assert_eq!( "FieldNameAndType { field_name: \"field\", type_name: \"Type\" }", format!("{field_name_and_type:?}") ); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/params_spec_fieldless.rs
workspace_tests/src/params/params_spec_fieldless.rs
use peace::{ enum_iterator::Sequence, item_model::item_id, params::{ AnySpecRt, AnySpecRtBoxed, FromFunc, MappingFn, MappingFnId, MappingFnImpl, MappingFnReg, MappingFns, ParamsFieldless, ParamsResolveError, ParamsSpecFieldless, ValueResolutionCtx, ValueResolutionMode, ValueSpecRt, }, resource_rt::{resources::ts::SetUp, Resources}, }; use serde::{Deserialize, Serialize}; use crate::mock_item::MockSrc; #[test] fn clone() { let _params_spec_fieldless = ParamsSpecFieldless::<MockSrc>::Value { value: MockSrc(1) }.clone(); } #[test] fn debug() { assert_eq!( "Stored", format!("{:?}", ParamsSpecFieldless::<MockSrc>::Stored) ); assert_eq!( "Value { value: MockSrc(1) }", format!( "{:?}", ParamsSpecFieldless::<MockSrc>::Value { value: MockSrc(1) } ) ); assert_eq!( "InMemory", format!("{:?}", ParamsSpecFieldless::<MockSrc>::InMemory) ); assert_eq!( "MappingFn { \ field_name: Some(\"field\"), \ mapping_fn_id: MappingFnId(\"MockSrcFromU8\") \ }", format!( "{:?}", ParamsSpecFieldless::<MockSrc>::mapping_fn( Some(String::from("field")), TestMappingFns::MockSrcFromU8 ) ) ); } #[test] fn serialize_stored() -> Result<(), serde_yaml::Error> { let u8_spec: <u8 as ParamsFieldless>::Spec = <u8 as ParamsFieldless>::Spec::Stored; assert_eq!( r#"Stored "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_value() -> Result<(), serde_yaml::Error> { let u8_spec: <u8 as ParamsFieldless>::Spec = 1u8.into(); assert_eq!( r#"!Value value: 1 "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_in_memory() -> Result<(), serde_yaml::Error> { let u8_spec: <u8 as ParamsFieldless>::Spec = ParamsSpecFieldless::<u8>::InMemory; assert_eq!( r#"InMemory "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn serialize_mapping_fn() -> Result<(), serde_yaml::Error> { let u8_spec: <u8 as ParamsFieldless>::Spec = ParamsSpecFieldless::<u8>::mapping_fn(None, TestMappingFns::MockSrcFromU8); assert_eq!( r#"!MappingFn field_name: null mapping_fn_id: MockSrcFromU8 "#, serde_yaml::to_string(&u8_spec)?, ); Ok(()) } #[test] fn deserialize_stored() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"Stored "# )?, ParamsSpecFieldless::<u8>::Stored )); Ok(()) } #[test] fn deserialize_value() -> Result<(), serde_yaml::Error> { assert!(matches!( serde_yaml::from_str( r#"!Value value: 1 "# )?, ParamsSpecFieldless::<u8>::Value { value } if value == 1u8 )); Ok(()) } #[test] fn deserialize_in_memory() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"InMemory "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!(&deserialized, ParamsSpecFieldless::<u8>::InMemory), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn deserialize_mapping_fn() -> Result<(), serde_yaml::Error> { let deserialized = serde_yaml::from_str( r#"!MappingFn field_name: "serialized_field_name" mapping_fn_id: "U8NoneFromU8" "#, )?; ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &deserialized, ParamsSpecFieldless::<u8>::MappingFn { field_name: Some(field_name), mapping_fn_id, } if field_name == "serialized_field_name" && mapping_fn_id == &TestMappingFns::U8NoneFromU8.id() ), "was {deserialized:?}" ); } })(); Ok(()) } #[test] fn is_usable_returns_false_for_stored() { assert!(!ParamsSpecFieldless::<u8>::Stored.is_usable()); } #[test] fn is_usable_returns_true_for_value_and_in_memory() { assert!(ParamsSpecFieldless::<u8>::Value { value: 1u8 }.is_usable()); assert!(ParamsSpecFieldless::<u8>::InMemory.is_usable()); } #[test] fn is_usable_returns_true_when_mapping_fn_is_some() { assert!(ParamsSpecFieldless::<u8>::mapping_fn(None, TestMappingFns::U8NoneFromU8).is_usable()); } #[test] fn is_usable_returns_true_when_mapping_fn_is_deserialized() -> Result<(), serde_yaml::Error> { let params_spec: ParamsSpecFieldless<u8> = serde_yaml::from_str( r#"!MappingFn field_name: null mapping_fn_id: U8NoneFromU8 "#, )?; assert!(params_spec.is_usable()); Ok(()) } #[test] fn resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::Stored; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemory { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_not_found") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be `Err(ParamsResolveError::InMemory {{ .. }})`\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let mock_src = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(MockSrc(1), mock_src); Ok(()) } #[test] fn resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8AndU16); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_stored_param() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_stored_param"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::Stored; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_none_when_not_found() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_none_when_not_found"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(None, mock_src); Ok(()) } #[test] fn try_resolve_in_memory_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = { let mut resources = Resources::new(); resources.insert(MockSrc(1)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::InMemory; let _mock_src_mut_borrowed = resources.borrow_mut::<MockSrc>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::InMemoryBorrowConflict { value_resolution_ctx }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_in_memory_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::InMemoryBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn try_resolve_value() -> Result<(), ParamsResolveError> { let mapping_fn_reg = MappingFnReg::new(); let resources = Resources::<SetUp>::from(Resources::new()); let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_value"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::Value { value: MockSrc(1) }; let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let mock_src = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, )?; assert_eq!(Some(MockSrc(1)), mock_src); Ok(()) } #[test] fn try_resolve_mapping_fn_returns_err_when_mutably_borrowed() -> Result<(), ParamsResolveError> { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let resources = { let mut resources = Resources::new(); resources.insert(1u8); resources.insert(2u16); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::Current, item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed"), tynm::type_name::<MockSrc>(), ); let mock_src_spec = ParamsSpecFieldless::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8AndU16); let _u8_borrowed = resources.borrow::<u8>(); let _u16_mut_borrowed = resources.borrow_mut::<u16>(); let mock_src_result = ValueSpecRt::try_resolve( &mock_src_spec, &mapping_fn_reg, &resources, &mut value_resolution_ctx, ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &mock_src_result, Err(ParamsResolveError::FromMapBorrowConflict { value_resolution_ctx, from_type_name }) if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::Current && value_resolution_ctx.item_id() == &item_id!("try_resolve_mapping_fn_returns_err_when_mutably_borrowed") && value_resolution_ctx.params_type_name() == "MockSrc" && value_resolution_ctx.resolution_chain().is_empty() && from_type_name == "u16" ), "expected `mock_src_result` to be \ `Err(ParamsResolveError::FromMapBorrowConflict {{ .. }})`\n\ with `resolution_chain`: `[]`,\n\ but was `{mock_src_result:?}`" ); } })(); Ok(()) } #[test] fn merge_stored_with_other_uses_other() { let mut params_spec_fieldless_a = ParamsSpecFieldless::<MockSrc>::Stored; let params_spec_fieldless_b = AnySpecRtBoxed::new(ParamsSpecFieldless::<MockSrc>::InMemory); params_spec_fieldless_a.merge(&*params_spec_fieldless_b); assert!(matches!( &params_spec_fieldless_a, ParamsSpecFieldless::<MockSrc>::InMemory )); } #[test] fn merge_value_with_other_no_change() { let mut params_spec_fieldless_a = ParamsSpecFieldless::<MockSrc>::Value { value: MockSrc(1) }; let params_spec_fieldless_b = AnySpecRtBoxed::new(ParamsSpecFieldless::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); params_spec_fieldless_a.merge(&*params_spec_fieldless_b); assert!( matches!(&params_spec_fieldless_a, ParamsSpecFieldless::<MockSrc>::Value { value } if value == &MockSrc(1)) ); } #[test] fn merge_in_memory_with_other_no_change() { let mut params_spec_fieldless_a = ParamsSpecFieldless::<MockSrc>::InMemory; let params_spec_fieldless_b = AnySpecRtBoxed::new(ParamsSpecFieldless::<MockSrc>::mapping_fn( None, TestMappingFns::MockSrcFromU8, )); params_spec_fieldless_a.merge(&*params_spec_fieldless_b); assert!(matches!( &params_spec_fieldless_a, ParamsSpecFieldless::<MockSrc>::InMemory )); } #[test] fn merge_mapping_fn_with_other_no_change() { let mut params_spec_fieldless_a = ParamsSpecFieldless::<MockSrc>::mapping_fn(None, TestMappingFns::MockSrcFromU8); let params_spec_fieldless_b = AnySpecRtBoxed::new(ParamsSpecFieldless::<MockSrc>::InMemory); params_spec_fieldless_a.merge(&*params_spec_fieldless_b); assert!(matches!( &params_spec_fieldless_a, ParamsSpecFieldless::<MockSrc>::MappingFn { field_name: None, mapping_fn_id, } if mapping_fn_id == &TestMappingFns::MockSrcFromU8.id() )); } #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Sequence)] #[enum_iterator(crate = peace::enum_iterator)] enum TestMappingFns { MockSrcFromU8, MockSrcFromU8AndU16, U8NoneFromU8, } impl MappingFns for TestMappingFns { fn id(self) -> MappingFnId { let name = match self { TestMappingFns::MockSrcFromU8 => "MockSrcFromU8", TestMappingFns::MockSrcFromU8AndU16 => "MockSrcFromU8AndU16", TestMappingFns::U8NoneFromU8 => "U8NoneFromU8", }; MappingFnId::new(name.into()) } fn mapping_fn(self) -> Box<dyn MappingFn> { match self { TestMappingFns::MockSrcFromU8 => MappingFnImpl::from_func(|n: &u8| Some(MockSrc(*n))), TestMappingFns::MockSrcFromU8AndU16 => { MappingFnImpl::from_func(|n: &u8, _: &u16| Some(MockSrc(*n))) } TestMappingFns::U8NoneFromU8 => MappingFnImpl::from_func(|_: &u8| Option::<u8>::None), } } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/derive.rs
workspace_tests/src/params/derive.rs
use peace::{ enum_iterator::Sequence, params::{FromFunc, MappingFn, MappingFnId, MappingFnImpl, MappingFns}, }; use serde::{Deserialize, Serialize}; mod unit { use std::any::TypeId; use serde::{Deserialize, Serialize}; use peace::params::{Params, ParamsSpec}; #[derive(Clone, Debug, Params, Serialize, Deserialize)] pub struct UnitParams; super::params_tests!(UnitParams, UnitParamsFieldWise, UnitParamsPartial, []); #[test] fn spec_from_params() { let params = UnitParams; assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: UnitParams } )); } #[test] fn field_wise_from_params() { let params = UnitParams; assert!(matches!( UnitParamsFieldWise::from(params), UnitParamsFieldWise )); } #[test] fn spec_debug() { assert_eq!( r#"UnitParamsFieldWise"#, format!("{:?}", UnitParamsFieldWise) ); } #[test] fn params_partial_debug() { assert_eq!(r#"UnitParamsPartial"#, format!("{:?}", UnitParamsPartial)); } #[test] fn params_try_from_partial_returns_ok() { let params_partial = UnitParamsPartial; assert!(matches!( UnitParams::try_from(params_partial), Ok(UnitParams) )); } #[test] fn params_try_from_partial_ref_returns_ok() { let params_partial = UnitParamsPartial; assert!(matches!( UnitParams::try_from(&params_partial), Ok(UnitParams) )); } } mod struct_params { use std::any::TypeId; use serde::{Deserialize, Serialize}; use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, item_model::item_id, params::{ MappingFnReg, Params, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, }, resource_rt::{resources::ts::SetUp, Resources}, }; use super::TestMappingFns; #[derive(Clone, Debug, Params, Serialize, Deserialize)] pub struct StructParams { /// Source / goal value for the state. src: String, /// Destination storage for the state. dest: String, } super::params_tests!(StructParams, StructParamsFieldWise, StructParamsPartial, []); #[test] fn spec_from_params() { let params = StructParams { src: String::from("a"), dest: String::from("b"), }; assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: StructParams { src, dest, } } if src == "a" && dest == "b" )); } #[test] fn field_wise_from_params() { let params = StructParams { src: String::from("a"), dest: String::from("b"), }; assert!(matches!( StructParamsFieldWise::from(params), StructParamsFieldWise { src: ValueSpec::Value { value: src_value }, dest: ValueSpec::Value { value: dest_value }, } if src_value == "a" && dest_value == "b" )); } #[test] fn field_wise_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = StructParams::field_wise_spec() .with_src(String::from("a")) .with_dest_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new(); resources.insert(1u32); Resources::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("field_wise_from_field_wise_builder"), String::from("StructParams"), ); assert!(matches!( field_wise, ParamsSpec::FieldWise { field_wise_spec: StructParamsFieldWise { src: ValueSpec::Value { value: src_value }, dest: ValueSpec::MappingFn { field_name, mapping_fn_id, }, } } if src_value == "a" && { let mapping_fn = mapping_fn_reg.get(&mapping_fn_id).unwrap(); matches!( mapping_fn.map(&resources, &mut value_resolution_ctx, field_name.as_deref()), Ok(dest_mapped) if BoxDataTypeDowncast::<String>::downcast_ref(&dest_mapped).map(String::as_str) == Some("b") ) } )); } #[test] fn spec_debug() { assert_eq!( r#"StructParamsFieldWise { src: Value { value: "a" }, dest: Value { value: "b" } }"#, format!( "{:?}", StructParamsFieldWise { src: ValueSpec::Value { value: String::from("a") }, dest: ValueSpec::Value { value: String::from("b") }, } ) ); } #[test] fn params_partial_debug() { assert_eq!( r#"StructParamsPartial { src: Some("a"), dest: Some("b") }"#, format!( "{:?}", StructParamsPartial { src: Some(String::from("a")), dest: Some(String::from("b")), } ) ); } #[test] fn params_try_from_partial_returns_ok_when_all_fields_are_some() { let params_partial = StructParamsPartial { src: Some(String::from("a")), dest: Some(String::from("b")), }; assert!(matches!( StructParams::try_from(params_partial), Ok(StructParams { src, dest, }) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_returns_err_when_some_fields_are_none() { let params_partial = StructParamsPartial { src: Some(String::from("a")), dest: None, }; assert!(matches!( StructParams::try_from(params_partial), Err(StructParamsPartial { src, dest, }) if src == Some(String::from("a")) && dest.is_none() )); } #[test] fn params_try_from_partial_ref_returns_ok_when_all_fields_are_some() { let params_partial = StructParamsPartial { src: Some(String::from("a")), dest: Some(String::from("b")), }; assert!(matches!( StructParams::try_from(&params_partial), Ok(StructParams { src, dest, }) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_ref_returns_err_when_some_fields_are_none() { let params_partial = StructParamsPartial { src: Some(String::from("a")), dest: None, }; assert!(matches!( StructParams::try_from(&params_partial), Err(StructParamsPartial { src, dest, }) if src == &Some(String::from("a")) && dest.is_none() )); } } mod struct_with_type_params { use std::{any::TypeId, marker::PhantomData}; use derivative::Derivative; use serde::{Deserialize, Serialize}; use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, item_model::item_id, params::{ MappingFnReg, Params, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, }, resource_rt::{resources::ts::SetUp, Resources}, }; use super::TestMappingFns; #[derive(Derivative, Params, Serialize, Deserialize)] #[derivative(Clone, Debug)] pub struct StructWithTypeParams<Id> { /// Source / goal value for the state. src: String, /// Destination storage for the state. dest: String, /// Marker for unique parameters type. marker: PhantomData<Id>, } super::params_tests!( StructWithTypeParams, StructWithTypeParamsFieldWise, StructWithTypeParamsPartial, [<()>] ); #[test] fn spec_from_params() { let params = StructWithTypeParams::<()> { src: String::from("a"), dest: String::from("b"), marker: PhantomData, }; assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: StructWithTypeParams { src, dest, marker: PhantomData, } } if src == "a" && dest == "b" )); } #[test] fn field_wise_from_params() { let params = StructWithTypeParams::<()> { src: String::from("a"), dest: String::from("b"), marker: PhantomData, }; assert!(matches!( StructWithTypeParamsFieldWise::from(params), StructWithTypeParamsFieldWise { src: ValueSpec::Value { value: src_value }, dest: ValueSpec::Value { value: dest_value }, marker: PhantomData, } if src_value == "a" && dest_value == "b" )); } #[test] fn field_wise_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = StructWithTypeParams::<()>::field_wise_spec() .with_src_in_memory() .with_dest_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new(); resources.insert(1u32); Resources::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("field_wise_from_field_wise_builder"), String::from("StructWithTypeParams<()>"), ); assert!(matches!( field_wise, ParamsSpec::FieldWise { field_wise_spec: StructWithTypeParamsFieldWise { src: ValueSpec::InMemory, dest: ValueSpec::MappingFn { field_name, mapping_fn_id, }, marker: PhantomData, } } if { let mapping_fn = mapping_fn_reg.get(&mapping_fn_id).unwrap(); matches!( mapping_fn.map(&resources, &mut value_resolution_ctx, field_name.as_deref()), Ok(dest_mapped) if BoxDataTypeDowncast::<String>::downcast_ref(&dest_mapped).map(String::as_str) == Some("b") ) } )); } #[test] fn spec_debug() { assert_eq!( r#"StructWithTypeParamsFieldWise { src: Value { value: "a" }, dest: Value { value: "b" }, marker: PhantomData<()> }"#, format!( "{:?}", StructWithTypeParamsFieldWise::<()> { src: ValueSpec::Value { value: String::from("a") }, dest: ValueSpec::Value { value: String::from("b") }, marker: PhantomData, } ) ); } #[test] fn params_partial_debug() { assert_eq!( r#"StructWithTypeParamsPartial { src: Some("a"), dest: Some("b"), marker: PhantomData<()> }"#, format!( "{:?}", StructWithTypeParamsPartial::<()> { src: Some(String::from("a")), dest: Some(String::from("b")), marker: PhantomData, } ) ); } #[test] fn params_try_from_partial_returns_ok_when_all_fields_are_some() { let params_partial = StructWithTypeParamsPartial::<()> { src: Some(String::from("a")), dest: Some(String::from("b")), marker: PhantomData, }; assert!(matches!( StructWithTypeParams::try_from(params_partial), Ok(StructWithTypeParams { src, dest, marker: PhantomData, }) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_returns_err_when_some_fields_are_none() { let params_partial = StructWithTypeParamsPartial::<()> { src: Some(String::from("a")), dest: None, marker: PhantomData, }; assert!(matches!( StructWithTypeParams::try_from(params_partial), Err(StructWithTypeParamsPartial { src, dest, marker: PhantomData, }) if src == Some(String::from("a")) && dest.is_none() )); } #[test] fn params_try_from_partial_ref_returns_ok_when_all_fields_are_some() { let params_partial = StructWithTypeParamsPartial::<()> { src: Some(String::from("a")), dest: Some(String::from("b")), marker: PhantomData, }; assert!(matches!( StructWithTypeParams::try_from(&params_partial), Ok(StructWithTypeParams { src, dest, marker: PhantomData, }) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_ref_returns_err_when_some_fields_are_none() { let params_partial = StructWithTypeParamsPartial::<()> { src: Some(String::from("a")), dest: None, marker: PhantomData, }; assert!(matches!( StructWithTypeParams::try_from(&params_partial), Err(StructWithTypeParamsPartial { src, dest, marker: PhantomData, }) if src == &Some(String::from("a")) && dest.is_none() )); } } mod tuple_params { use std::any::TypeId; use serde::{Deserialize, Serialize}; use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, item_model::item_id, params::{ MappingFnReg, Params, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, }, resource_rt::{resources::ts::SetUp, Resources}, }; use super::TestMappingFns; #[derive(Clone, Debug, Params, Serialize, Deserialize)] pub struct TupleParams( /// Source / goal value for the state. String, /// Destination storage for the state. String, ); super::params_tests!(TupleParams, TupleParamsFieldWise, TupleParamsPartial, []); #[test] fn spec_from_params() { let params = TupleParams(String::from("a"), String::from("b")); assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: TupleParams ( src, dest, ) } if src == "a" && dest == "b" )); } #[test] fn field_wise_from_params() { let params = TupleParams(String::from("a"), String::from("b")); assert!(matches!( TupleParamsFieldWise::from(params), TupleParamsFieldWise ( ValueSpec::Value { value: src_value }, ValueSpec::Value { value: dest_value }, ) if src_value == "a" && dest_value == "b" )); } #[test] fn field_wise_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = TupleParams::field_wise_spec() .with_0_in_memory() .with_1_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new(); resources.insert(1u32); Resources::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("field_wise_from_field_wise_builder"), String::from("TupleParams"), ); assert!(matches!( field_wise, ParamsSpec::FieldWise { field_wise_spec: TupleParamsFieldWise( ValueSpec::InMemory, ValueSpec::MappingFn { field_name, mapping_fn_id, }, ) } if { let mapping_fn = mapping_fn_reg.get(&mapping_fn_id).unwrap(); matches!( mapping_fn.map(&resources, &mut value_resolution_ctx, field_name.as_deref()), Ok(dest_mapped) if BoxDataTypeDowncast::<String>::downcast_ref(&dest_mapped).map(String::as_str) == Some("b") ) } )); } #[test] fn spec_debug() { assert_eq!( r#"TupleParamsFieldWise(Value { value: "a" }, Value { value: "b" })"#, format!( "{:?}", TupleParamsFieldWise( ValueSpec::Value { value: String::from("a") }, ValueSpec::Value { value: String::from("b") }, ) ) ); } #[test] fn params_partial_debug() { assert_eq!( r#"TupleParamsPartial(Some("a"), Some("b"))"#, format!( "{:?}", TupleParamsPartial(Some(String::from("a")), Some(String::from("b")),) ) ); } #[test] fn params_try_from_partial_returns_ok_when_all_fields_are_some() { let params_partial = TupleParamsPartial(Some(String::from("a")), Some(String::from("b"))); assert!(matches!( TupleParams::try_from(params_partial), Ok(TupleParams ( src, dest, )) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_returns_err_when_some_fields_are_none() { let params_partial = TupleParamsPartial(Some(String::from("a")), None); assert!(matches!( TupleParams::try_from(params_partial), Err(TupleParamsPartial ( src, dest, )) if src == Some(String::from("a")) && dest.is_none() )); } #[test] fn params_try_from_partial_ref_returns_ok_when_all_fields_are_some() { let params_partial = TupleParamsPartial(Some(String::from("a")), Some(String::from("b"))); assert!(matches!( TupleParams::try_from(&params_partial), Ok(TupleParams ( src, dest, )) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_ref_returns_err_when_some_fields_are_none() { let params_partial = TupleParamsPartial(Some(String::from("a")), None); assert!(matches!( TupleParams::try_from(&params_partial), Err(TupleParamsPartial ( src, dest, )) if src == &Some(String::from("a")) && dest.is_none() )); } } mod tuple_with_type_params { use std::{any::TypeId, fmt::Debug, marker::PhantomData}; use serde::{Deserialize, Serialize}; use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, item_model::item_id, params::{ MappingFnReg, Params, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, }, resource_rt::{resources::ts::SetUp, Resources}, }; use super::TestMappingFns; #[derive(Clone, Debug, Params, Serialize, Deserialize)] pub struct TupleWithTypeParams<Id>(String, String, PhantomData<Id>) where Id: Clone + Debug; super::params_tests!( TupleWithTypeParams, TupleWithTypeParamsFieldWise, TupleWithTypeParamsPartial, [<()>] ); #[test] fn spec_from_params() { let params = TupleWithTypeParams::<()>(String::from("a"), String::from("b"), PhantomData); assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: TupleWithTypeParams ( src, dest, PhantomData, ) } if src == "a" && dest == "b" )); } #[test] fn field_wise_from_params() { let params = TupleWithTypeParams::<()>(String::from("a"), String::from("b"), PhantomData); assert!(matches!( TupleWithTypeParamsFieldWise::from(params), TupleWithTypeParamsFieldWise::<()>( ValueSpec::Value { value: src_value }, ValueSpec::Value { value: dest_value }, PhantomData, ) if src_value == "a" && dest_value == "b" )); } #[test] fn field_wise_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = TupleWithTypeParams::<()>::field_wise_spec() .with_0_in_memory() .with_1_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new(); resources.insert(1u32); Resources::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("field_wise_from_field_wise_builder"), String::from("TupleWithTypeParams<()>"), ); assert!(matches!( field_wise, ParamsSpec::FieldWise { field_wise_spec: TupleWithTypeParamsFieldWise( ValueSpec::InMemory, ValueSpec::MappingFn { field_name, mapping_fn_id, }, PhantomData, ) } if { let mapping_fn = mapping_fn_reg.get(&mapping_fn_id).unwrap(); matches!( mapping_fn.map(&resources, &mut value_resolution_ctx, field_name.as_deref()), Ok(dest_mapped) if BoxDataTypeDowncast::<String>::downcast_ref(&dest_mapped).map(String::as_str) == Some("b") ) } )); } #[test] fn spec_debug() { assert_eq!( r#"TupleWithTypeParamsFieldWise(Value { value: "a" }, Value { value: "b" }, PhantomData<()>)"#, format!( "{:?}", TupleWithTypeParamsFieldWise::<()>( ValueSpec::Value { value: String::from("a") }, ValueSpec::Value { value: String::from("b") }, PhantomData, ) ) ); } #[test] fn params_partial_debug() { assert_eq!( r#"TupleWithTypeParamsPartial(Some("a"), Some("b"), PhantomData<()>)"#, format!( "{:?}", TupleWithTypeParamsPartial::<()>( Some(String::from("a")), Some(String::from("b")), PhantomData, ) ) ); } #[test] fn params_try_from_partial_returns_ok_when_all_fields_are_some() { let params_partial = TupleWithTypeParamsPartial::<()>( Some(String::from("a")), Some(String::from("b")), PhantomData, ); assert!(matches!( TupleWithTypeParams::try_from(params_partial), Ok(TupleWithTypeParams::<()> ( src, dest, PhantomData, )) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_returns_err_when_some_fields_are_none() { let params_partial = TupleWithTypeParamsPartial::<()>(Some(String::from("a")), None, PhantomData); assert!(matches!( TupleWithTypeParams::try_from(params_partial), Err(TupleWithTypeParamsPartial::<()> ( src, dest, PhantomData, )) if src == Some(String::from("a")) && dest.is_none() )); } #[test] fn params_try_from_partial_ref_returns_ok_when_all_fields_are_some() { let params_partial = TupleWithTypeParamsPartial::<()>( Some(String::from("a")), Some(String::from("b")), PhantomData, ); assert!(matches!( TupleWithTypeParams::try_from(&params_partial), Ok(TupleWithTypeParams::<()> ( src, dest, PhantomData, )) if src == "a" && dest == "b" )); } #[test] fn params_try_from_partial_ref_returns_err_when_some_fields_are_none() { let params_partial = TupleWithTypeParamsPartial::<()>(Some(String::from("a")), None, PhantomData); assert!(matches!( TupleWithTypeParams::try_from(&params_partial), Err(TupleWithTypeParamsPartial::<()> ( src, dest, PhantomData, )) if src == &Some(String::from("a")) && dest.is_none() )); } } mod enum_params { use std::{any::TypeId, marker::PhantomData}; use derivative::Derivative; use serde::{Deserialize, Serialize}; use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, item_model::item_id, params::{ MappingFnReg, Params, ParamsSpec, ValueResolutionCtx, ValueResolutionMode, ValueSpec, }, resource_rt::{resources::ts::SetUp, Resources}, }; use super::TestMappingFns; #[derive(Derivative, Params, Serialize, Deserialize)] #[derivative(Clone, Debug)] pub enum EnumParams<Id> { Named { /// Source / goal value for the state. src: String, /// Marker for unique parameters type. marker: PhantomData<Id>, }, Tuple(String), TupleMarker(String, PhantomData<Id>), Unit, } super::params_tests!( EnumParams, EnumParamsFieldWise, EnumParamsPartial, [<()>] ); #[test] fn spec_named_from_params() { let params = EnumParams::<()>::Named { src: String::from("a"), marker: PhantomData, }; assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: EnumParams::Named { src, marker: PhantomData, } } if src == "a" )); } #[test] fn spec_tuple_from_params() { let params = EnumParams::<()>::Tuple(String::from("a")); assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: EnumParams::Tuple(src)} if src == "a" )); } #[test] fn spec_tuple_marker_from_params() { let params = EnumParams::<()>::TupleMarker(String::from("a"), PhantomData); assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: EnumParams::TupleMarker(src, PhantomData)} if src == "a" )); } #[test] fn spec_unit_from_params() { let params = EnumParams::<()>::Unit; assert!(matches!( ParamsSpec::from(params), ParamsSpec::Value { value: EnumParams::Unit } )); } #[test] fn field_wise_named_from_params() { let params = EnumParams::<()>::Named { src: String::from("a"), marker: PhantomData, }; assert!(matches!( EnumParamsFieldWise::from(params), EnumParamsFieldWise::<()>::Named { src: ValueSpec::Value { value }, marker: PhantomData, } if value == "a" )); } #[test] fn field_wise_tuple_from_params() { let params = EnumParams::<()>::Tuple(String::from("a")); assert!(matches!( EnumParamsFieldWise::from(params), EnumParamsFieldWise::<()>::Tuple(ValueSpec::Value { value }) if value == "a" )); } #[test] fn field_wise_tuple_marker_from_params() { let params = EnumParams::<()>::TupleMarker(String::from("a"), PhantomData); assert!(matches!( EnumParamsFieldWise::from(params), EnumParamsFieldWise::<()>::TupleMarker(ValueSpec::Value { value }, PhantomData) if value == "a" )); } #[test] fn field_wise_unit_from_params() { let params = EnumParams::<()>::Unit; assert!(matches!( EnumParamsFieldWise::from(params), EnumParamsFieldWise::<()>::Unit )); } #[test] fn field_wise_named_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = EnumParams::<()>::field_wise_spec() .named() .with_src(String::from("a")) .with_src_in_memory() .with_src_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new(); resources.insert(1u32); Resources::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::ApplyDry, item_id!("field_wise_named_from_field_wise_builder"), String::from("EnumParams<()>"), ); assert!(matches!( field_wise, ParamsSpec::FieldWise { field_wise_spec: EnumParamsFieldWise::Named { src: ValueSpec::MappingFn { field_name, mapping_fn_id, }, marker: PhantomData, } } if { let mapping_fn = mapping_fn_reg.get(&mapping_fn_id).unwrap(); matches!( mapping_fn.map(&resources, &mut value_resolution_ctx, field_name.as_deref()), Ok(src_mapped) if BoxDataTypeDowncast::<String>::downcast_ref(&src_mapped).map(String::as_str) == Some("b") ) } )); } #[test] fn field_wise_tuple_from_field_wise_builder() { let mut mapping_fn_reg = MappingFnReg::new(); mapping_fn_reg.register_all::<TestMappingFns>(); let field_wise = EnumParams::<()>::field_wise_spec() .tuple() .with_0(String::from("a")) .with_0_in_memory() .with_0_from_mapping_fn(TestMappingFns::StringBFromU32) .build(); let resources: Resources<SetUp> = { let mut resources = Resources::new();
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
true
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/params_specs.rs
workspace_tests/src/params/params_specs.rs
use peace::{ item_model::item_id, params::{ParamsSpec, ParamsSpecs}, }; use crate::mock_item::MockSrc; #[test] fn debug() { let mut params_specs = ParamsSpecs::new(); params_specs.insert(item_id!("item_id"), ParamsSpec::<MockSrc>::InMemory); assert_eq!( "ParamsSpecs({\ ItemId(\"item_id\"): \ TypedValue { \ type: \"peace_params::params_spec::ParamsSpec<workspace_tests::mock_item::MockSrc>\", \ value: InMemory \ }})", format!("{params_specs:?}") ); } #[test] fn into_inner() { let mut params_specs = ParamsSpecs::new(); params_specs.insert(item_id!("item_id"), ParamsSpec::<MockSrc>::InMemory); let type_map = params_specs.into_inner(); let params_spec = type_map.get::<ParamsSpec<MockSrc>, _>(&item_id!("item_id")); assert!(matches!(params_spec, Some(ParamsSpec::<MockSrc>::InMemory))); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/params/mapping_fn_impl.rs
workspace_tests/src/params/mapping_fn_impl.rs
use peace::params::MappingFnImpl; #[test] fn debug() { let mapping_fn_impl = MappingFnImpl::from( #[cfg_attr(coverage_nightly, coverage(off))] |_: &bool| None::<Option<u16>>, ); assert_eq!( "MappingFnImpl { \ fn_map: \"Some(Fn(&bool,) -> Option<Option<u16>>)\", \ marker: PhantomData<(core::option::Option<u16>, (bool,))> \ }", format!("{mapping_fn_impl:?}") ); let mapping_fn_impl = MappingFnImpl::from( #[cfg_attr(coverage_nightly, coverage(off))] |_: &u32, _: &u64| None::<Option<u16>>, ); assert_eq!( "MappingFnImpl { \ fn_map: \"Some(Fn(&u32, &u64) -> Option<Option<u16>>)\", \ marker: PhantomData<(core::option::Option<u16>, (u32, u64))> \ }", format!("{mapping_fn_impl:?}") ); } mapping_tests!(apply_dry, ApplyDry); mapping_tests!(current, Current); mapping_tests!(goal, Goal); mapping_tests!(clean, Clean); macro_rules! mapping_tests { ($module_name:ident, $value_resolution_mode:ident) => { mod $module_name { use peace::{ cmd_ctx::type_reg::untagged::BoxDataTypeDowncast, data::marker::$value_resolution_mode, item_model::item_id, params::{ MappingFn, MappingFnImpl, ParamsResolveError, ValueResolutionCtx, ValueResolutionMode, }, resource_rt::{resources::ts::SetUp, Resources}, }; #[test] fn mapping_fn_map_returns_ok_when_referenced_values_are_present_directly() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert(1u32); resources.insert(2u64); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum = MappingFn::map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), )?; assert_eq!(Some(3), BoxDataTypeDowncast::<u16>::downcast_ref(&sum).copied()); Ok(()) } #[test] fn mapping_fn_map_returns_ok_when_referenced_values_are_present_through_data_marker() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); resources.insert($value_resolution_mode(Some(2u64))); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum = MappingFn::map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), )?; assert_eq!(Some(3), BoxDataTypeDowncast::<u16>::downcast_ref(&sum).copied()); Ok(()) } #[test] fn mapping_fn_map_returns_err_when_referenced_value_is_none() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); resources.insert($value_resolution_mode(None::<u64>)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum_result = MappingFn::map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &sum_result, Err(ParamsResolveError::FromMap { value_resolution_ctx, from_type_name }) if matches!( value_resolution_ctx, value_resolution_ctx if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::$value_resolution_mode && value_resolution_ctx.item_id() == &item_id!("mapping_fn_map") && value_resolution_ctx.params_type_name() == crate::fn_name_short!() && value_resolution_ctx.resolution_chain() == [] ) && from_type_name == "u64" // u64 is missing from `resources` ), "expected `sum_result` to be \ `Err(ParamsResolveError::FromMap {{ .. }}`,\n\ but was {sum_result:?}" ); } })(); Ok(()) } #[test] fn mapping_fn_map_returns_err_when_referenced_value_is_absent() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); // resources.insert($value_resolution_mode(Some(2u64))); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum_result = MappingFn::map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), ); ({ #[cfg_attr(coverage_nightly, coverage(off))] || { assert!( matches!( &sum_result, Err(ParamsResolveError::FromMap { value_resolution_ctx, from_type_name }) if matches!( value_resolution_ctx, value_resolution_ctx if value_resolution_ctx.value_resolution_mode() == ValueResolutionMode::$value_resolution_mode && value_resolution_ctx.item_id() == &item_id!("mapping_fn_map") && value_resolution_ctx.params_type_name() == crate::fn_name_short!() && value_resolution_ctx.resolution_chain() == [] ) && from_type_name == "u64" // u64 is missing from `resources` ), "expected `sum_result` to be \ `Err(ParamsResolveError::FromMap {{ .. }}`,\n\ but was {sum_result:?}" ); } })(); Ok(()) } #[test] fn mapping_fn_try_map_returns_ok_some_when_referenced_values_are_present() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); resources.insert($value_resolution_mode(Some(2u64))); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum = MappingFn::try_map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), )?; assert_eq!(Some(3), sum.as_ref().and_then(BoxDataTypeDowncast::<u16>::downcast_ref).copied()); Ok(()) } #[test] fn mapping_fn_try_map_returns_ok_none_when_referenced_value_is_none() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); resources.insert($value_resolution_mode(None::<u64>)); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum = MappingFn::try_map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), )?; assert!(sum.is_none(), "Expected `sum` to be `None` but was {sum:?}"); Ok(()) } #[test] fn mapping_fn_try_map_returns_ok_none_when_referenced_value_is_absent() -> Result<(), ParamsResolveError> { let mapping_fn_impl = MappingFnImpl::from(|a: &u32, b: &u64| { let a = u16::try_from(*a).ok()?; let b = u16::try_from(*b).ok()?; a.checked_add(b) }); let resources = { let mut resources = Resources::new(); resources.insert($value_resolution_mode(Some(1u32))); // resources.insert($value_resolution_mode(Some(2u64))); Resources::<SetUp>::from(resources) }; let mut value_resolution_ctx = ValueResolutionCtx::new( ValueResolutionMode::$value_resolution_mode, item_id!("mapping_fn_map"), String::from(crate::fn_name_short!()), ); let sum = MappingFn::try_map( &mapping_fn_impl, &resources, &mut value_resolution_ctx, Some("field_name"), )?; assert!(sum.is_none(), "Expected `sum` to be `None` but was {sum:?}"); Ok(()) } } }; } use mapping_tests;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model/item_stream_outcome.rs
workspace_tests/src/cmd_model/item_stream_outcome.rs
use peace::{ cmd_model::ItemStreamOutcome, item_model::item_id, rt_model::fn_graph::StreamOutcomeState, }; #[test] fn map() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); let item_stream_outcome = item_stream_outcome.map(|n| n + 1); assert_eq!( ItemStreamOutcome::finished_with(2u16, vec![item_id!("mock")]), item_stream_outcome ); } #[test] fn replace() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); let (item_stream_outcome, n) = item_stream_outcome.replace(2u32); assert_eq!(1u16, n); assert_eq!( ItemStreamOutcome::finished_with(2u32, vec![item_id!("mock")]), item_stream_outcome ); } #[test] fn replace_with() { let item_stream_outcome = ItemStreamOutcome::finished_with((1u16, "value_to_extract"), vec![item_id!("mock")]); let (item_stream_outcome, value) = item_stream_outcome.replace_with(|(n, value)| (n, value)); assert_eq!("value_to_extract", value); assert_eq!( ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]), item_stream_outcome ); } #[test] fn into_value() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); let n = item_stream_outcome.into_value(); assert_eq!(1u16, n); } #[test] fn value() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); let n = item_stream_outcome.value(); assert_eq!(1u16, *n); } #[test] fn value_mut() { let mut item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); *item_stream_outcome.value_mut() += 1; assert_eq!(2u16, *item_stream_outcome.value()); } #[test] fn state() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); assert_eq!(StreamOutcomeState::Finished, item_stream_outcome.state()); } #[test] fn item_ids_processed() { let item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); assert_eq!( &[item_id!("mock")], item_stream_outcome.item_ids_processed() ); } #[test] fn item_ids_not_processed() { let mut item_stream_outcome = ItemStreamOutcome::finished_with(1u16, vec![item_id!("mock")]); item_stream_outcome.item_ids_not_processed = vec![item_id!("mock_1")]; assert_eq!( &[item_id!("mock_1")], item_stream_outcome.item_ids_not_processed() ); } #[test] fn default() { let item_stream_outcome = ItemStreamOutcome::<u16>::default(); assert_eq!(0u16, *item_stream_outcome.value()); assert_eq!(StreamOutcomeState::NotStarted, item_stream_outcome.state()); assert!(item_stream_outcome.item_ids_processed().is_empty()); assert!(item_stream_outcome.item_ids_not_processed().is_empty()); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model/cmd_block_outcome.rs
workspace_tests/src/cmd_model/cmd_block_outcome.rs
use peace::{ cmd_model::{CmdBlockOutcome, StreamOutcomeAndErrors, ValueAndStreamOutcome}, item_model::item_id, rt_model::{fn_graph::StreamOutcome, IndexMap}, }; #[test] fn is_ok() { assert!(cmd_block_outcome_single(123).is_ok()); assert!(cmd_block_outcome_item_wise(123, None).is_ok()); assert!(!cmd_block_outcome_item_wise(123, Some("err".to_string())).is_ok()); } #[test] fn is_err() { assert!(!cmd_block_outcome_single(123).is_err()); assert!(!cmd_block_outcome_item_wise(123, None).is_err()); assert!(cmd_block_outcome_item_wise(123, Some("err".to_string())).is_err()); } #[test] fn try_into_value() { assert_eq!( Ok(ValueAndStreamOutcome { value: 123, stream_outcome: None, }), cmd_block_outcome_single(123).try_into_value() ); assert_eq!( Ok(ValueAndStreamOutcome { value: 123, stream_outcome: Some(StreamOutcome::finished_with((), Vec::new())), }), cmd_block_outcome_item_wise(123, None).try_into_value() ); let mut errors = IndexMap::new(); errors.insert(item_id!("mock"), "err".to_string()); assert_eq!( Err(StreamOutcomeAndErrors { stream_outcome: StreamOutcome::finished_with(123, Vec::new()), errors, }), cmd_block_outcome_item_wise(123, Some("err".to_string())).try_into_value() ); } #[test] fn map() { assert_eq!( cmd_block_outcome_single(124), cmd_block_outcome_single(123).map(|value| value + 1) ); assert_eq!( cmd_block_outcome_item_wise(124, None), cmd_block_outcome_item_wise(123, None).map(|value| value + 1) ); assert_eq!( cmd_block_outcome_item_wise(124, Some("err".to_string())), cmd_block_outcome_item_wise(123, Some("err".to_string())).map(|value| value + 1) ); } #[test] fn clone() { let cmd_block_outcome = cmd_block_outcome_single(123); assert_eq!(cmd_block_outcome, Clone::clone(&cmd_block_outcome)); } #[test] fn debug() { let cmd_block_outcome = cmd_block_outcome_single(123); assert_eq!("Single(123)", format!("{cmd_block_outcome:?}")); } fn cmd_block_outcome_single<T>(value: T) -> CmdBlockOutcome<T, String> { CmdBlockOutcome::<T, String>::Single(value) } fn cmd_block_outcome_item_wise<T>(value: T, error: Option<String>) -> CmdBlockOutcome<T, String> { let mut errors = IndexMap::new(); if let Some(error) = error { errors.insert(item_id!("mock"), error); } CmdBlockOutcome::<T, String>::ItemWise { stream_outcome: StreamOutcome::finished_with(value, Vec::new()), errors, } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model/cmd_execution_error.rs
workspace_tests/src/cmd_model/cmd_execution_error.rs
#[cfg(feature = "error_reporting")] mod input_fetch_error;
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model/cmd_outcome.rs
workspace_tests/src/cmd_model/cmd_outcome.rs
use peace::{ cmd_model::{CmdOutcome, ItemStreamOutcome}, rt_model::IndexMap, }; #[test] fn value() { assert_eq!(Some(123), cmd_outcome_complete(123).value().copied()); assert_eq!( Some(123), cmd_outcome_block_interrupted(123).value().copied() ); assert_eq!( Some(123), cmd_outcome_execution_interrupted(Some(123)) .value() .copied() ); assert_eq!(Some(123), cmd_outcome_item_error(123).value().copied()); } #[test] fn is_complete() { assert!(cmd_outcome_complete(123).is_complete()); assert!(!cmd_outcome_block_interrupted(123).is_complete()); assert!(!cmd_outcome_execution_interrupted(Some(123)).is_complete()); assert!(!cmd_outcome_item_error(123).is_complete()); } #[test] fn is_interrupted() { assert!(!cmd_outcome_complete(123).is_interrupted()); assert!(cmd_outcome_block_interrupted(123).is_interrupted()); assert!(cmd_outcome_execution_interrupted(Some(123)).is_interrupted()); assert!(!cmd_outcome_item_error(123).is_interrupted()); } #[test] fn is_err() { assert!(!cmd_outcome_complete(123).is_err()); assert!(!cmd_outcome_block_interrupted(123).is_err()); assert!(!cmd_outcome_execution_interrupted(Some(123)).is_err()); assert!(cmd_outcome_item_error(123).is_err()); } #[test] fn map() { assert_eq!( cmd_outcome_complete(124), cmd_outcome_complete(123).map(|value| value + 1) ); assert_eq!( cmd_outcome_block_interrupted(124), cmd_outcome_block_interrupted(123).map(|value| value + 1) ); assert_eq!( cmd_outcome_execution_interrupted(Some(124)), cmd_outcome_execution_interrupted(Some(123)).map(|value| value + 1) ); assert_eq!( cmd_outcome_execution_interrupted(None::<u32>), cmd_outcome_execution_interrupted(None::<u32>).map(|value| value + 1) ); assert_eq!( cmd_outcome_item_error(124), cmd_outcome_item_error(123).map(|value| value + 1) ); } #[tokio::test] async fn map_async() { assert_eq!( cmd_outcome_complete(124), cmd_outcome_complete(123) .map_async(|value| async move { value + 1 }) .await ); assert_eq!( cmd_outcome_block_interrupted(124), cmd_outcome_block_interrupted(123) .map_async(|value| async move { value + 1 }) .await ); assert_eq!( cmd_outcome_execution_interrupted(Some(124)), cmd_outcome_execution_interrupted(Some(123)) .map_async(|value| async move { value + 1 }) .await ); assert_eq!( cmd_outcome_execution_interrupted(None::<u32>), cmd_outcome_execution_interrupted(None::<u32>) .map_async(|value| async move { value + 1 }) .await ); assert_eq!( cmd_outcome_item_error(124), cmd_outcome_item_error(123) .map_async(|value| async move { value + 1 }) .await ); } #[test] fn transpose() { assert_eq!( Ok(cmd_outcome_complete(123)), cmd_outcome_complete(Ok(123)).transpose() ); assert_eq!( Err("err".to_string()), cmd_outcome_complete(Err::<u32, _>("err".to_string())).transpose() ); assert_eq!( Ok(cmd_outcome_block_interrupted(123)), cmd_outcome_block_interrupted(Ok(123)).transpose() ); assert_eq!( Err("err".to_string()), cmd_outcome_block_interrupted(Err::<u32, _>("err".to_string())).transpose() ); assert_eq!( Ok(cmd_outcome_execution_interrupted(Some(123))), cmd_outcome_execution_interrupted(Some(Ok(123))).transpose() ); assert_eq!( Err("err".to_string()), cmd_outcome_execution_interrupted(Some(Err::<u32, _>("err".to_string()))).transpose() ); assert_eq!( Ok(cmd_outcome_execution_interrupted(None::<u32>)), cmd_outcome_execution_interrupted(None::<Result<u32, String>>).transpose() ); assert_eq!( Ok(cmd_outcome_item_error(123)), cmd_outcome_item_error(Ok(123)).transpose() ); assert_eq!( Err("err".to_string()), cmd_outcome_item_error(Err::<u32, _>("err".to_string())).transpose() ); } #[test] fn clone() { let cmd_outcome = cmd_outcome_complete(123); assert_eq!(cmd_outcome, Clone::clone(&cmd_outcome)); } #[test] fn debug() { let cmd_outcome = cmd_outcome_complete(123); assert_eq!( "Complete { value: 123, cmd_blocks_processed: [] }", format!("{cmd_outcome:?}") ); } fn cmd_outcome_complete<T>(value: T) -> CmdOutcome<T, String> { CmdOutcome::<T, String>::Complete { value, cmd_blocks_processed: vec![], } } fn cmd_outcome_block_interrupted<T>(value: T) -> CmdOutcome<T, String> { CmdOutcome::<T, String>::BlockInterrupted { item_stream_outcome: ItemStreamOutcome::finished_with(value, Vec::new()), cmd_blocks_processed: vec![], cmd_blocks_not_processed: vec![], } } fn cmd_outcome_execution_interrupted<T>(value: Option<T>) -> CmdOutcome<T, String> { CmdOutcome::<T, String>::ExecutionInterrupted { value, cmd_blocks_processed: vec![], cmd_blocks_not_processed: vec![], } } fn cmd_outcome_item_error<T>(value: T) -> CmdOutcome<T, String> { CmdOutcome::<T, String>::ItemError { item_stream_outcome: ItemStreamOutcome::finished_with(value, Vec::new()), cmd_blocks_processed: vec![], cmd_blocks_not_processed: vec![], errors: IndexMap::new(), } }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/cmd_model/cmd_execution_error/input_fetch_error.rs
workspace_tests/src/cmd_model/cmd_execution_error/input_fetch_error.rs
use miette::{Diagnostic, SourceOffset, SourceSpan}; use peace::cmd_model::InputFetchError; #[test] fn coverage_diagnostic() { let cmd_execution_src = String::from( r#"CmdExecution: ExecutionOutcome: (States<Previous>, States<Ensured>, States<Goal>) CmdBlocks: - StatesCurrentReadCmdBlock: Input: States<Current> Outcome: States<Goal> - StatesGoalReadCmdBlock: Input: States<Current> Outcome: States<Goal> - StatesDiscoverCmdBlock: Input: () Outcome: (States<Current>, States<Goal>) - ApplyStateSyncCheckCmdBlock: Input: (States<CurrentStored>, States<Current>, States<GoalStored>, States<Goal>) Outcome: (States<CurrentStored>, States<Current>, States<GoalStored>, States<Goal>) - ApplyExecCmdBlock: Input: (States<Current>, States<Goal>) Outcome: (States<Previous>, States<Ensured>, States<Goal>) "#, ); let full_span = SourceSpan::new(SourceOffset::from_location(&cmd_execution_src, 4, 5), 25); let error = Box::new(InputFetchError { cmd_block_descs: Vec::new(), cmd_block_index: 0, input_name_short: String::from("StatesCurrentReadCmdBlock"), input_name_full: String::from("peace_rt::cmd_blocks::StatesCurrentReadCmdBlock"), cmd_execution_src, input_span: None, full_span, }); std::borrow::Borrow::<dyn miette::Diagnostic + '_>::borrow(&error); let _ = error.code(); let _ = error.severity(); let _ = error.help(); let _ = error.url(); let _ = error.source_code(); let _ = error.labels(); let _ = error.related(); let _ = error.diagnostic_source(); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false
azriel91/peace
https://github.com/azriel91/peace/blob/5e2c43f2c0b18672749d0902d2285c703e24de97/workspace_tests/src/progress_model/progress_limit.rs
workspace_tests/src/progress_model/progress_limit.rs
use peace::progress_model::ProgressLimit; #[test] fn defaults_to_unknown() { assert_eq!(ProgressLimit::Unknown, ProgressLimit::default()); } #[test] fn clone() { let progress_limit_0 = ProgressLimit::Steps(3); let progress_limit_1 = Clone::clone(&progress_limit_0); assert_eq!(progress_limit_0, progress_limit_1); } #[test] fn copy() { let progress_limit_0 = ProgressLimit::Steps(3); let progress_limit_1 = progress_limit_0; assert_eq!(progress_limit_0, progress_limit_1); } #[test] fn deserialize() { assert_eq!( ProgressLimit::Steps(3), serde_yaml::from_str("!Steps 3\n").unwrap() ) } #[test] fn serialize() { assert_eq!( "!Steps 3\n", serde_yaml::to_string(&ProgressLimit::Steps(3)).unwrap() ) } #[test] fn eq() { assert_eq!(ProgressLimit::Steps(3), ProgressLimit::Steps(3)); assert_eq!(ProgressLimit::Bytes(3), ProgressLimit::Bytes(3)); // Should this be equal? It should match at least. assert_eq!(ProgressLimit::Unknown, ProgressLimit::Unknown); } #[test] fn ne() { assert_ne!(ProgressLimit::Steps(3), ProgressLimit::Steps(4)); assert_ne!(ProgressLimit::Steps(3), ProgressLimit::Bytes(3)); assert_ne!(ProgressLimit::Steps(3), ProgressLimit::Unknown); assert_ne!(ProgressLimit::Bytes(3), ProgressLimit::Bytes(4)); assert_ne!(ProgressLimit::Bytes(3), ProgressLimit::Unknown); } #[test] fn debug() { assert_eq!(r#"Unknown"#, format!("{:?}", ProgressLimit::Unknown)); assert_eq!(r#"Steps(3)"#, format!("{:?}", ProgressLimit::Steps(3))); assert_eq!(r#"Bytes(3)"#, format!("{:?}", ProgressLimit::Bytes(3))); }
rust
Apache-2.0
5e2c43f2c0b18672749d0902d2285c703e24de97
2026-01-04T20:22:52.922300Z
false