pub struct OkMaybe<T, E>(pub T, pub Option<E>);Expand description
Represents generic data and maybe an error
- Full data when err is empty
OkMaybe(_, None). - Maybe partial data when err is present:
OkMaybe(_, Some(_)).
§Why
When parsing, we want to accumulate as many errors as possible. That means that even partial data may be useful. For example, this code has the same attribute specified twice and also a syntax error that will prevent it from parsing additional attributes:
#[macro_name(unknown attribute here, ignore)]
#[macro_name(rename = "First", rename = "Again")]In this situation unknown attribute here constitutes a syntax error that would
prevent parsing ignore. However, the second line can be fully parsed but
we want to error on the accidental duplicate rename attribute. By returning
partial data along side of errors we can report
§Examples
If E implements IntoIterator and Extend (as syn::Error or does) then you can
accumulate errors using OkMaybe::push_unwrap. Use this when partial data
returned might hold additional errors that you wish to accumulate before returning.
For example:
use proc_micro::{OkMaybe, MaybeError};
let mut errors = MaybeError::new();
let _out: () =
OkMaybe((), Some(syn::Error::new(span, "message".to_string())))
.push_unwrap(&mut errors);
assert!(errors.has_err());
assert!(matches!(errors.maybe(), Some(_)));For situations where partial data is not usable, convert into a result:
use proc_micro::OkMaybe;
let result: Result<(), syn::Error> =
OkMaybe((), Some(syn::Error::new(span, "message".to_string())))
.to_result();
assert!(result.is_err(), "Expected an error, got {:?}", result);
let result: Result<(), syn::Error> =
OkMaybe((), None)
.to_result();
assert!(result.is_ok(), "Expected Ok, got {:?}", result);Tuple Fields§
§0: T§1: Option<E>Implementations§
Source§impl<T, E> OkMaybe<T, E>where
E: IntoIterator<Item = E>,
impl<T, E> OkMaybe<T, E>where
E: IntoIterator<Item = E>,
Sourcepub fn push_unwrap(self, push_to: impl Extend<E>) -> T
pub fn push_unwrap(self, push_to: impl Extend<E>) -> T
If E implements IntoIterator and Extend (like syn::Error does) then the error can be pushed into an accumulator (such as a MaybeError in order to return the original value.