1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624
//! Storing and accessing definitions of standard blocks in a [`Universe`].
//!
//! An enum implementing [`BlockModule`] defines a set of names, and
//! [`BlockProvider`] assists in ensuring that all of those names are defined
//! and storing or retrieving their block values in a specific [`Universe`].
//!
//! In the future this mechanism may grow to become a dynamic linker/dependency injector
//! by becoming aware of dependencies between “modules”. For now, it's just enough to
//! solve bootstrapping needs.
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::hash::Hash;
use core::ops::Index;
use exhaust::Exhaust;
use hashbrown::HashMap as HbHashMap;
use crate::block::{Block, BlockDef};
use crate::space::{SetCubeError, SpaceTransaction};
use crate::transaction::ExecuteError;
use crate::universe::{Handle, InsertError, Name, Universe, UniverseTransaction};
use crate::util::{ErrorIfStd, YieldProgress};
#[cfg(doc)]
use crate::block::Primitive;
fn name_in_module<E: BlockModule>(key: &E) -> Name {
Name::from(format!("{ns}/{key}", ns = E::namespace()))
}
/// Allows the use of [`Provider::default`] to construct a [`Provider`]
/// using this type as its set of keys. [`Self::module_default()`] will be called once for
/// each value of [`Self`].
///
/// See [`BlockModule`] for related expectations.
pub trait DefaultProvision<T> {
/// Returns the default value to use for the given key.
fn module_default(self) -> T;
}
/// Types whose values identify blocks in a set of related blocks, which may be
/// stored in a [`BlockProvider`] or under specific names in a [`Universe`].
///
/// The names of the [`Universe`]'s corresponding [`BlockDef`]s are formed by
/// combining the [`namespace()`](Self::namespace) and `self.to_string()` (the
/// [`Display`](fmt::Display) trait implementation).
///
/// Implement this trait for an enum, then use the functions of
/// [`BlockProvider`] to work with the described set of blocks.
///
/// TODO: consider replacing Display with a separate method so as not to presume its meaning
pub trait BlockModule: Exhaust + fmt::Debug + fmt::Display + Eq + Hash + Clone {
/// A namespace for the members of this module; currently, this should be a
/// `/`-separated path with no trailing slash, but (TODO:) we should have a
/// more rigorous namespace scheme for [`Name`]s in future versions.
fn namespace() -> &'static str;
}
/// An instance of a [`BlockModule`]; a container of a `Block` for every possible `E`.
///
/// TODO: Deprecate and remove this alias.
pub type BlockProvider<E> = Provider<E, Block>;
/// Key-value container of a `V` value for every possible `E`.
#[derive(Clone, Debug)]
pub struct Provider<E, V> {
/// Guaranteed to contain an entry for every variant of `E` if `E`'s
/// [`Exhaust`] implementation is accurate.
map: HbHashMap<E, V>,
}
impl<E, V> Default for Provider<E, V>
where
E: DefaultProvision<V> + Exhaust + Eq + Hash + Clone,
{
fn default() -> Self {
Self {
map: E::exhaust()
.map(|key| {
let value = DefaultProvision::module_default(key.clone());
(key, value)
})
.collect(),
}
}
}
impl<E, V> Provider<E, V>
where
E: BlockModule,
{
/// Constructs a `Provider` with values computed by the given function.
///
/// This is an async function for the sake of cancellation and optional cooperative
/// multitasking. It may be blocked on from a synchronous context (but if that is the
/// only use, consider calling [`Provider::new_sync()`] instead).
pub async fn new<F>(progress: YieldProgress, mut definer: F) -> Result<Self, GenError>
where
F: FnMut(E) -> Result<V, InGenError>,
{
let count = E::exhaust().count();
let mut map = HbHashMap::with_capacity(count);
for (key, progress) in E::exhaust().zip(progress.split_evenly(count)) {
match definer(key.clone()) {
Ok(value) => {
map.insert(key, value);
progress.finish().await;
}
Err(e) => return Err(GenError::failure(e, name_in_module(&key))),
};
}
Ok(Self { map })
}
}
// TODO: Generalize these to non-blocks however makes sense
impl<E: BlockModule> Provider<E, Block> {
/// Add the block definitions stored in this [`BlockProvider`] into `universe` as
/// [`BlockDef`]s, returning a new [`BlockProvider`] whose blocks refer to those
/// definitions (via [`Primitive::Indirect`]).
pub fn install(&self, txn: &mut UniverseTransaction) -> Result<Self, InsertError> {
// The non-generic part of the code.
#[inline(never)]
fn create_block_def_and_indirect(
txn: &mut UniverseTransaction,
name: Name,
block: &Block,
) -> Result<Block, InsertError> {
let block_def_handle = Handle::new_pending(name, BlockDef::new(block.clone()));
txn.insert_mut(block_def_handle.clone())?;
let indirect_block = Block::from(block_def_handle);
Ok(indirect_block)
}
let mut map = HbHashMap::with_capacity(self.map.len());
for key in E::exhaust() {
let indirect_block =
create_block_def_and_indirect(txn, name_in_module(&key), &self[&key])?;
map.insert(key, indirect_block);
}
Ok(Self { map })
}
/// Obtain the definitions of `E`'s blocks from `universe`, returning a new
/// [`BlockProvider`] whose blocks refer to those definitions (via
/// [`Primitive::Indirect`]).
///
/// Returns an error if any of the blocks are not defined in that universe.
pub fn using(universe: &Universe) -> Result<Self, ProviderError>
where
E: Eq + Hash + fmt::Display,
{
let mut found: HbHashMap<E, Handle<BlockDef>> = HbHashMap::new();
let mut missing = Vec::new();
for key in E::exhaust() {
let name = name_in_module(&key);
if let Some(handle) = universe.get(&name) {
found.insert(key, handle);
} else {
missing.push(name);
}
}
if !missing.is_empty() {
return Err(ProviderError {
missing: missing.into(),
});
}
Ok(Provider {
map: E::exhaust()
.map(|key| {
let block = Block::from(found.remove(&key).unwrap());
(key, block)
})
.collect(),
})
}
}
/// These methods do not require `E` to be a [`BlockModule`].
impl<E: Exhaust + fmt::Debug + Clone + Eq + Hash, V> Provider<E, V> {
/// Alternative to [`Self::new()`] which is neither async nor fallible.
pub fn new_sync<F>(mut definer: F) -> Self
where
F: FnMut(E) -> V,
{
Provider {
map: E::exhaust()
.map(|key| (key.clone(), definer(key)))
.collect(),
}
}
/// Create another [`Provider`] with different keys that map into a subset of
/// this provider's keys.
///
/// TODO: add a test
#[must_use]
pub fn subset<K>(&self, function: impl Fn(K) -> E) -> Provider<K, V>
where
K: Exhaust + fmt::Debug + Clone + Eq + Hash,
V: Clone,
{
Provider::new_sync(|key: K| self[function(key)].clone())
}
/// Create another [`Provider`] with a modification to each value.
#[must_use]
pub fn map<V2>(&self, mut function: impl FnMut(&E, &V) -> V2) -> Provider<E, V2> {
Provider {
map: self
.map
.iter()
.map(|(key, value)| (key.clone(), function(key, value)))
.collect(),
}
}
/// Iterate over the entire contents of this.
pub fn iter(&self) -> ModuleIter<'_, E, V> {
ModuleIter {
key_iter: E::exhaust(),
map: &self.map,
}
}
#[cfg(test)]
fn consistency_check(&self) {
use hashbrown::HashSet;
let expected_keys: HashSet<E> = E::exhaust().collect();
let actual_keys: HashSet<E> = self.map.keys().cloned().collect();
assert_eq!(
expected_keys, actual_keys,
"Provider keys are not as expected"
);
}
}
impl<E: Eq + Hash, V: PartialEq> PartialEq for Provider<E, V> {
fn eq(&self, other: &Self) -> bool {
let Self { map } = self;
*map == other.map
}
}
impl<E: Eq + Hash, V: PartialEq> Eq for Provider<E, V> {}
impl<E: Eq + Hash, V> Index<E> for Provider<E, V> {
type Output = V;
fn index(&self, index: E) -> &Self::Output {
&self.map[&index]
}
}
impl<E: Eq + Hash, V> Index<&E> for Provider<E, V> {
type Output = V;
fn index(&self, index: &E) -> &Self::Output {
&self.map[index]
}
}
impl<'provider, E: Exhaust + fmt::Debug + Clone + Eq + Hash, V> IntoIterator
for &'provider Provider<E, V>
{
type Item = (E, &'provider V);
type IntoIter = ModuleIter<'provider, E, V>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
/// Iterator returned by [`Provider::iter()`].
#[allow(missing_debug_implementations)]
pub struct ModuleIter<'provider, E: Exhaust, V> {
/// Using the `Exhaust` iterator instead of the `HashMap` iterator guarantees a deterministic
/// iteration order. (We don't currently publicly promise that, though.)
key_iter: <E as Exhaust>::Iter,
map: &'provider HbHashMap<E, V>,
}
impl<'provider, E: Exhaust + Eq + Hash, V> Iterator for ModuleIter<'provider, E, V> {
type Item = (E, &'provider V);
fn next(&mut self) -> Option<Self::Item> {
self.key_iter.next().map(|key| {
let value: &V = &self.map[&key];
(key, value)
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.key_iter.size_hint()
}
}
impl<E, V> ExactSizeIterator for ModuleIter<'_, E, V> where
E: Exhaust<Iter: ExactSizeIterator> + Eq + Hash
{
}
/// Error when a [`Provider`] could not be created because the definitions of some
/// of its members are missing.
#[derive(Clone, Debug, Eq, displaydoc::Display, PartialEq)]
#[displaydoc("module definitions missing from universe: {missing:?}")] // TODO: use Name's Display within the list
pub struct ProviderError {
missing: Box<[Name]>,
}
crate::util::cfg_should_impl_error! {
impl std::error::Error for ProviderError {}
}
/// An error resulting from “world generation”: failure to calculate/create/place objects
/// (due to bad parameters or unforeseen edge cases), failure to successfully store them
/// in or retrieve them from a [`Universe`], et cetera.
#[derive(Debug)]
pub struct GenError {
#[cfg_attr(not(feature = "std"), allow(dead_code))]
detail: InGenError,
for_object: Option<Name>,
}
crate::util::cfg_should_impl_error! {
impl std::error::Error for GenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.detail)
}
}
}
impl GenError {
/// Wrap an error, that occurred while creating an object, as a [`GenError`] which also
/// names the object.
pub fn failure(error: impl Into<InGenError>, object: Name) -> Self {
Self {
detail: error.into(),
for_object: Some(object),
}
}
}
impl fmt::Display for GenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Don't include `detail` because that's our `Error::source()`.
// The assumption is that the cause chain will be walked when printing an error.
if let Some(name) = &self.for_object {
write!(f, "An error occurred while generating object {name}")?;
} else {
write!(f, "An error occurred while generating an object")?;
}
Ok(())
}
}
impl From<InsertError> for GenError {
// TODO: Maybe InsertError should just be a variant of GenError?
fn from(error: InsertError) -> Self {
GenError {
for_object: Some(error.name.clone()),
detail: error.into(),
}
}
}
impl From<ExecuteError<UniverseTransaction>> for GenError {
// TODO: Ideally, this works only for `UniverseTransaction` errors, which relate to
// specific members, but we don't have a static distinction between different transactions'
// errors yet.
fn from(error: ExecuteError<UniverseTransaction>) -> Self {
GenError {
for_object: None,
detail: error.into(),
}
}
}
/// Aggregation of types of errors that might occur in “world generation”.
///
/// This is distinct from [`GenError`] in that this type is returned from functions
/// _responsible for generation,_ and that type is returned from functions that
/// _manage_ generation — that invoke the first kind and (usually) store its result
/// in the [`Universe`]. This separation is intended to encourage more precise
/// attribution of the source of the error despite implicit conversions, because a
/// “nested” [`GenError`] will be obligated to be wrapped in `InGenError` rather than
/// mistakenly taken as the same level.
///
/// TODO: Work this into a coherent set of error cases rather than purely
/// "I saw one of these once, so add it".
#[derive(Debug)]
#[non_exhaustive]
pub enum InGenError {
/// Generic error container for unusual situations.
Other(Box<dyn ErrorIfStd + Send + Sync>),
/// Something else needed to be generated and that failed.
Gen(Box<GenError>),
/// Failed to insert the generated items in the [`Universe`].
Insert(InsertError),
/// Failed to find a needed dependency.
// TODO: Any special handling? Phrase this as "missing dependency"?
Provider(ProviderError),
/// Failed during [`Space`](crate::space::Space) manipulation.
SetCube(SetCubeError),
/// Failed during a transaction executed as part of generation.
UniverseTransaction(ExecuteError<UniverseTransaction>),
/// Failed during a transaction executed as part of generation.
SpaceTransaction(ExecuteError<SpaceTransaction>),
}
impl InGenError {
/// Convert an arbitrary error to `InGenError`.
#[cfg_attr(not(feature = "std"), doc(hidden))]
pub fn other<E: ErrorIfStd + Send + Sync + 'static>(error: E) -> Self {
Self::Other(Box::new(error))
}
}
crate::util::cfg_should_impl_error! {
impl std::error::Error for InGenError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
InGenError::Other(e) => e.source(),
InGenError::Gen(e) => e.source(),
InGenError::Insert(e) => e.source(),
InGenError::Provider(e) => e.source(),
InGenError::SetCube(e) => e.source(),
InGenError::UniverseTransaction(e) => e.source(),
InGenError::SpaceTransaction(e) => e.source(),
}
}
}
}
impl fmt::Display for InGenError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InGenError::Other(e) => e.fmt(f),
InGenError::Gen(e) => e.fmt(f),
InGenError::Insert(e) => e.fmt(f),
InGenError::Provider(e) => e.fmt(f),
InGenError::SetCube(e) => e.fmt(f),
InGenError::UniverseTransaction(e) => e.fmt(f),
InGenError::SpaceTransaction(e) => e.fmt(f),
}
}
}
impl From<GenError> for InGenError {
fn from(error: GenError) -> Self {
// We need to box this to avoid an unboxed recursive type.
InGenError::Gen(Box::new(error))
}
}
impl From<InsertError> for InGenError {
fn from(error: InsertError) -> Self {
InGenError::Insert(error)
}
}
impl From<ProviderError> for InGenError {
fn from(error: ProviderError) -> Self {
InGenError::Provider(error)
}
}
impl From<SetCubeError> for InGenError {
fn from(error: SetCubeError) -> Self {
InGenError::SetCube(error)
}
}
impl From<ExecuteError<UniverseTransaction>> for InGenError {
fn from(error: ExecuteError<UniverseTransaction>) -> Self {
InGenError::UniverseTransaction(error)
}
}
impl From<ExecuteError<SpaceTransaction>> for InGenError {
fn from(error: ExecuteError<SpaceTransaction>) -> Self {
InGenError::SpaceTransaction(error)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::block::{Quote, Resolution::*, AIR};
use crate::content::make_some_blocks;
use crate::math::GridAab;
use crate::transaction::Transactional as _;
use crate::util::assert_send_sync;
#[derive(Exhaust, Clone, Debug, Eq, Hash, PartialEq)]
enum Key {
A,
B,
C,
}
impl fmt::Display for Key {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{self:?}")
}
}
impl BlockModule for Key {
fn namespace() -> &'static str {
"test-key"
}
}
fn test_provider() -> ([Block; 3], BlockProvider<Key>) {
let blocks = make_some_blocks();
let provider = BlockProvider::new_sync(|k: Key| match k {
Key::A => blocks[0].clone(),
Key::B => blocks[1].clone(),
Key::C => blocks[2].clone(),
});
provider.consistency_check();
(blocks, provider)
}
#[test]
fn provider_install() {
let mut universe = Universe::new();
let (_, provider) = test_provider();
// TODO: double-unwrap in this case is a bad sign (InsertError != UniverseConflict)
let installed = universe
.transact(|txn, _| Ok(provider.install(txn)))
.unwrap()
.unwrap();
assert_eq!(installed, BlockProvider::using(&universe).unwrap());
}
#[test]
fn provider_subset() {
let (_, p1) = test_provider();
let p2 = p1.subset(|x: bool| if x { Key::A } else { Key::B });
p2.consistency_check();
assert_eq!(p1[Key::A], p2[true]);
assert_eq!(p1[Key::B], p2[false]);
}
#[test]
fn provider_map() {
let (_, p1) = test_provider();
let p2 = p1.map(|_, block| block.clone().with_modifier(Quote::default()));
p2.consistency_check();
assert_eq!(
p1[Key::A].clone().with_modifier(Quote::default()),
p2[Key::A],
);
}
#[test]
fn provider_eq() {
let (_, p1) = test_provider();
let (_, p2) = test_provider();
assert_eq!(p1, p2);
assert_ne!(
p1,
p2.map(|key, block| if *key == Key::B { AIR } else { block.clone() })
);
}
#[test]
fn errors_are_send_sync() {
assert_send_sync::<GenError>();
assert_send_sync::<InGenError>();
}
#[test]
#[cfg(feature = "std")] // Error::source only exists on std
fn gen_error_message() {
use alloc::string::ToString;
use std::error::Error;
let set_cube_error = SetCubeError::OutOfBounds {
modification: GridAab::for_block(R1),
space_bounds: GridAab::for_block(R4),
};
let e = GenError::failure(set_cube_error.clone(), "x".into());
assert_eq!(
e.to_string(),
"An error occurred while generating object 'x'",
);
let source = Error::source(&e)
.expect("has source")
.downcast_ref::<InGenError>()
.expect("is InGenError");
assert_eq!(source.to_string(), set_cube_error.to_string());
}
#[test]
#[allow(clippy::try_err)]
fn gen_error_composition() {
// TODO: this isn't the greatest example situation
fn a() -> Result<(), GenError> {
b().map_err(|e| GenError::failure(e, "x".into()))?;
Ok(())
}
fn b() -> Result<(), InGenError> {
Err(SetCubeError::OutOfBounds {
modification: GridAab::for_block(R1),
space_bounds: GridAab::for_block(R1),
})?;
Ok(())
}
let r = a();
assert!(
matches!(
r,
Err(GenError {
detail: InGenError::SetCube(_),
for_object: Some(Name::Specific(_)),
})
),
"got error: {r:?}"
);
}
}