alloy_sol_type_parser/
error.rs

1use alloc::{boxed::Box, string::String};
2use core::fmt;
3
4/// Parser result
5pub type Result<T, E = Error> = core::result::Result<T, E>;
6
7/// Parser error.
8#[derive(Clone, PartialEq, Eq)]
9pub struct Error(Repr);
10
11impl core::error::Error for Error {}
12
13impl fmt::Debug for Error {
14    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
15        f.debug_tuple("Error").field(&self.0 .0).finish()
16    }
17}
18
19impl fmt::Display for Error {
20    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21        self.0.fmt(f)
22    }
23}
24
25impl Error {
26    /// Instantiate a new error.
27    pub fn new(s: impl fmt::Display) -> Self {
28        Self::_new("", &s)
29    }
30
31    /// Instantiate a new parser error.
32    pub fn parser(e: impl fmt::Display) -> Self {
33        Self::_new(if cfg!(feature = "std") { "parser error:\n" } else { "parser error: " }, &e)
34    }
35
36    /// Instantiate an invalid type string error. Invalid type string errors are
37    /// for type strings that are not valid type strings. E.g. "uint256))))[".
38    pub fn invalid_type_string(ty: impl fmt::Display) -> Self {
39        Self::_new("invalid type string: ", &ty)
40    }
41
42    /// Instantiate an invalid identifier string error. Invalid identifier string errors are for
43    /// identifier strings that do not follow the format described in
44    /// <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityLexer.Identifier>.
45    pub fn invalid_identifier_string(identifier: impl fmt::Display) -> Self {
46        Self::_new("invalid identifier string: ", &identifier)
47    }
48
49    /// Instantiate an invalid size error. Invalid size errors are for valid
50    /// primitive types with invalid sizes. E.g. `"uint7"` or `"bytes1337"` or
51    /// `"string[aaaaaa]"`.
52    pub fn invalid_size(ty: impl fmt::Display) -> Self {
53        Self::_new("invalid size for type: ", &ty)
54    }
55
56    // Not public API.
57    #[doc(hidden)]
58    #[inline(never)]
59    #[cold]
60    pub fn _new(s: &str, e: &dyn fmt::Display) -> Self {
61        Self(Repr(Box::new(format!("{s}{e}"))))
62    }
63}
64
65#[derive(Clone, PartialEq, Eq)]
66#[allow(clippy::box_collection)] // `Box<String>` is smaller than `String` or `Box<str>`.
67struct Repr(Box<String>);
68
69impl fmt::Display for Repr {
70    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
71        f.write_str(&self.0)
72    }
73}