///|
/// What the elements below an object of the type `owner` get from this value of it.
fn StoredValue::supplied(self : StoredValue, owner : OwnerType) -> AnyValue? {
  if !self.property.metadata(owner).inherits {
    self.passed
  } else if self.is_default() {
    None
  } else {
    Some(self.effective())
  }
}

///|
/// What the parent supplies. That is the value of the nearest ancestor on which the property inherits.
fn DependencyObject::inherited(
  self : DependencyObject,
  property : PropertyInfo,
) -> AnyValue? {
  guard self.parent is Some(parent) else { return None }
  guard parent.stored(property) is Some(value) else { return None }
  value.supplied(parent.owner_type)
}

///|
/// Whether two sources supply equal values, or both supply none.
fn PropertyInfo::same_supply(
  self : PropertyInfo,
  a : AnyValue?,
  b : AnyValue?,
) -> Bool {
  match (a, b) {
    (Some(a), Some(b)) => self.equal_values(a, b)
    (None, None) => true
    _ => false
  }
}

///|
/// Evaluate what the elements of this subtree inherit, after it got another place in the tree. The walk goes to all of them, so
/// it finds a loop also when nothing is inherited.
fn DependencyObject::inherit_subtree(self : DependencyObject) -> Unit raise {
  self.inherit_all()
  self.walk(element => {
    element.inherit_all()
    true
  })
}

///|
/// Take each value that the parent supplies and the element does not have, and replace each one that is not the same any more.
fn DependencyObject::inherit_all(self : DependencyObject) -> Unit raise {
  self.make_room()
  for value in self.values {
    let property = value.property
    let known = match self.stored(property) {
      Some({ source: Inherited, base, .. }) => Some(base)
      Some({ passed, .. }) => passed
      None => None
    }
    if !property.same_supply(known, self.inherited(property)) {
      ignore(self.update(property, Inherit))
    }
  }
}

///|
/// Store the default value of each property that the parent supplies and for which nothing is stored. The inherited values then
/// replace them, without a new array for each.
fn DependencyObject::make_room(self : DependencyObject) -> Unit {
  guard self.parent is Some(parent) else { return }
  let added = []
  for value in parent.values {
    let property = value.property
    if self.find(property) is Err(_) &&
      value.supplied(parent.owner_type) is Some(_) {
      added.push(property.metadata(self.owner_type).unset(property))
    }
  }
  if !added.is_empty() {
    let values = [..self.values, ..added]
    values.sort_by((a, b) => a.property.index.compare(b.property.index))
    self.values = FixedArray::from_array(values)
  }
}