///|
/// How deep changes of properties and raises of routed events can cause each other. One more level fails with an error.
/// WPF has no limit, and its process ends when the stack is full.
pub let nesting_limit : Int32 = 128

///|
let depth : Ref[Int32] = Ref(0)

///|
/// Go one level deeper. Every exit of the caller has to call `leave`.
fn enter(label : () -> String) -> Unit raise DependencyError {
  if depth.val >= nesting_limit {
    raise NestingLimit(
      "`\{label()}` is more than \{nesting_limit} levels deep in changes that cause each other",
    )
  }
  depth.val += 1
}

///|
fn leave() -> Unit {
  depth.val -= 1
}

///|
/// Run `f` one level deeper in the nesting that the changes of properties share, and fail past `nesting_limit` with an
/// error that names `label`. Code that calls handlers which can change properties, such as a raise of a routed event,
/// runs them with this function.
pub fn[T] guard_nesting(label : String, f : () -> T raise) -> T raise {
  enter(() => label)
  defer leave()
  f()
}