forge_fmt/solang_ext/
safe_unwrap.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
use solang_parser::pt;

/// Trait implemented to unwrap optional parse tree items initially introduced in
/// [hyperledger/solang#1068].
///
/// Note that the methods of this trait should only be used on parse tree items' fields, like
/// [pt::VariableDefinition] or [pt::EventDefinition], where the `name` field is `None` only when an
/// error occurred during parsing.
///
/// [hyperledger/solang#1068]: https://github.com/hyperledger/solang/pull/1068
pub trait SafeUnwrap<T> {
    /// See [SafeUnwrap].
    fn safe_unwrap(&self) -> &T;

    /// See [SafeUnwrap].
    fn safe_unwrap_mut(&mut self) -> &mut T;
}

#[inline(never)]
#[cold]
#[track_caller]
fn invalid() -> ! {
    panic!("invalid parse tree")
}

macro_rules! impl_ {
    ($($t:ty),+ $(,)?) => {
        $(
            impl SafeUnwrap<$t> for Option<$t> {
                #[inline]
                #[track_caller]
                fn safe_unwrap(&self) -> &$t {
                    match *self {
                        Some(ref x) => x,
                        None => invalid(),
                    }
                }

                #[inline]
                #[track_caller]
                fn safe_unwrap_mut(&mut self) -> &mut $t {
                    match *self {
                        Some(ref mut x) => x,
                        None => invalid(),
                    }
                }
            }
        )+
    };
}

impl_!(pt::Identifier, pt::StringLiteral);