forge_fmt/solang_ext/safe_unwrap.rs
1use solang_parser::pt;
2
3/// Trait implemented to unwrap optional parse tree items initially introduced in
4/// [hyperledger/solang#1068].
5///
6/// Note that the methods of this trait should only be used on parse tree items' fields, like
7/// [pt::VariableDefinition] or [pt::EventDefinition], where the `name` field is `None` only when an
8/// error occurred during parsing.
9///
10/// [hyperledger/solang#1068]: https://github.com/hyperledger/solang/pull/1068
11pub trait SafeUnwrap<T> {
12 /// See [SafeUnwrap].
13 fn safe_unwrap(&self) -> &T;
14
15 /// See [SafeUnwrap].
16 fn safe_unwrap_mut(&mut self) -> &mut T;
17}
18
19#[inline(never)]
20#[cold]
21#[track_caller]
22fn invalid() -> ! {
23 panic!("invalid parse tree")
24}
25
26macro_rules! impl_ {
27 ($($t:ty),+ $(,)?) => {
28 $(
29 impl SafeUnwrap<$t> for Option<$t> {
30 #[inline]
31 #[track_caller]
32 fn safe_unwrap(&self) -> &$t {
33 match *self {
34 Some(ref x) => x,
35 None => invalid(),
36 }
37 }
38
39 #[inline]
40 #[track_caller]
41 fn safe_unwrap_mut(&mut self) -> &mut $t {
42 match *self {
43 Some(ref mut x) => x,
44 None => invalid(),
45 }
46 }
47 }
48 )+
49 };
50}
51
52impl_!(pt::Identifier, pt::StringLiteral);