alloy_sol_type_parser/
stem.rs
1use crate::{Error, Input, Result, RootType, TupleSpecifier};
2use winnow::{combinator::trace, ModalResult, Parser};
3
4#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum TypeStem<'a> {
23 Root(RootType<'a>),
25 Tuple(TupleSpecifier<'a>),
27}
28
29impl<'a> TryFrom<&'a str> for TypeStem<'a> {
30 type Error = Error;
31
32 #[inline]
33 fn try_from(value: &'a str) -> Result<Self> {
34 Self::parse(value)
35 }
36}
37
38impl AsRef<str> for TypeStem<'_> {
39 #[inline]
40 fn as_ref(&self) -> &str {
41 self.span()
42 }
43}
44
45impl<'a> TypeStem<'a> {
46 #[inline]
48 pub fn parse(input: &'a str) -> Result<Self> {
49 if input.starts_with('(') || input.starts_with("tuple(") {
50 input.try_into().map(Self::Tuple)
51 } else {
52 input.try_into().map(Self::Root)
53 }
54 }
55
56 pub(crate) fn parser(input: &mut Input<'a>) -> ModalResult<Self> {
58 let name = "TypeStem";
59 if input.starts_with('(') || input.starts_with("tuple(") {
60 trace(name, TupleSpecifier::parser).parse_next(input).map(Self::Tuple)
61 } else {
62 trace(name, RootType::parser).parse_next(input).map(Self::Root)
63 }
64 }
65
66 #[inline]
68 pub const fn as_root(&self) -> Option<&RootType<'a>> {
69 match self {
70 Self::Root(root) => Some(root),
71 Self::Tuple(_) => None,
72 }
73 }
74
75 #[inline]
77 pub const fn as_tuple(&self) -> Option<&TupleSpecifier<'a>> {
78 match self {
79 Self::Root(_) => None,
80 Self::Tuple(tuple) => Some(tuple),
81 }
82 }
83
84 #[inline]
86 pub const fn span(&self) -> &'a str {
87 match self {
88 Self::Root(root) => root.span(),
89 Self::Tuple(tuple) => tuple.span(),
90 }
91 }
92
93 #[inline]
95 pub fn try_basic_solidity(&self) -> Result<()> {
96 match self {
97 Self::Root(root) => root.try_basic_solidity(),
98 Self::Tuple(tuple) => tuple.try_basic_solidity(),
99 }
100 }
101}
102
103#[cfg(test)]
104mod tests {
105 use super::*;
106
107 #[test]
108 fn tuple() {
109 assert_eq!(
111 TypeStem::parse("()"),
112 Ok(TypeStem::Tuple(TupleSpecifier { span: "()", types: vec![] }))
113 );
114 TypeStem::parse("tuple(").unwrap_err();
115 assert_eq!(
116 TypeStem::parse("tuple()"),
117 Ok(TypeStem::Tuple(TupleSpecifier { span: "tuple()", types: vec![] }))
118 );
119
120 assert_eq!(TypeStem::parse("tuple"), Ok(TypeStem::Root(RootType::parse("tuple").unwrap())))
122 }
123}