Skip to content
Myr

Document tagged dispatch approach

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent 14bab22 · Browse files · 1 file+46 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+46 added−0 removed

  • other:+46 added−0 removed

1 file+46 added−0 removed

modified:src/kind.rs+46 added
1// Tagged dispatch mechanism for resolving the behavior of `anyhow!($expr)`.2//3// When anyhow! is given a single expr argument to turn into anyhow::Error, we4// want the resulting Error to pick up the input's implementation of source()5// and backtrace() if it has a std::error::Error impl, otherwise require nothing6// more than Display and Debug.7//8// Expressed in terms of specialization, we want something like:9//10// trait AnyhowNew {11// fn new(self) -> Error;12// }13//14// impl<T> AnyhowNew for T15// where16// T: Display + Debug + Send + Sync + 'static,17// {18// default fn new(self) -> Error {19// /* no std error impl */20// }21// }22//23// impl<T> AnyhowNew for T24// where25// T: std::error::Error + Send + Sync + 'static,26// {27// fn new(self) -> Error {28// /* use std error's source() and backtrace() */29// }30// }31//32// Since specialization is not stable yet, instead we rely on autoref behavior33// of method resolution to perform tagged dispatch. Here we have two traits34// AdhocKind and TraitKind that both have an anyhow_kind() method. AdhocKind is35// implemented whether or not the caller's type has a std error impl, while36// TraitKind is implemented only when a std error impl does exist. The ambiguity37// is resolved by AdhocKind requiring an extra autoref so that it has lower38// precedence.39//40// The anyhow! macro will set up the call in this form:41//42// #[allow(unused_imports)]43// use $crate::private::{AdhocKind, TraitKind};44// let error = $msg;45// error.anyhow_kind().new(error)4647use crate::Error;48use std::error::Error as StdError;49use std::fmt::{Debug, Display};50
42 unmodified lines