// Error bridge between the primitive backend ABI and the typed core.
//
// The backend returns `Int32` codes (or `0` handles) because a virtual package
// cannot carry concrete error types; `backend_last_error()` carries the message
// across as a plain `String`, and this is where it becomes a typed error.

pub suberror RhiError {
  BackendFailed(String)
}

///|
/// Errors end up in `println("\{err}")` in every consumer that reports a failed
/// draw or pipeline build, so the message has to survive formatting.
pub impl Show for RhiError with output(self, logger) {
  match self {
    RhiError::BackendFailed(msg) => logger.write_string("RhiError: " + msg)
  }
}

///|
/// Wrap the message recorded by the last failing backend call.
pub fn backend_error() -> RhiError {
  RhiError::BackendFailed(@be.backend_last_error())
}

///|
/// The bare message recorded by the last failing backend call, for logging.
pub fn last_backend_error() -> String {
  @be.backend_last_error()
}

///|
/// Turn a backend return code into a `RhiError`, `0` meaning success.
///
/// A backend entry point that fails must record a message, but a missing one
/// used to produce a bare `RhiError:` with nothing after it, which is impossible
/// to act on. The code goes into the message in that case so the failure still
/// identifies itself.
pub fn check(code : Int32) -> Unit raise RhiError {
  if code != (0 : Int32) {
    let msg = @be.backend_last_error()
    if msg == ("" : String) {
      raise RhiError::BackendFailed("backend call failed with code \{code}")
    }
    raise RhiError::BackendFailed(msg)
  }
}