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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use crate::{kw, FunctionAttributes, ParameterList, Returns, Spanned};
use proc_macro2::Span;
use std::{
    fmt,
    hash::{Hash, Hasher},
};
use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    token::Paren,
    Result,
};

/// A function type: `function() returns (string memory)`.
///
/// Solidity reference:
/// <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.functionTypeName>
#[derive(Clone)]
pub struct TypeFunction {
    pub function_token: kw::function,
    pub paren_token: Paren,
    pub arguments: ParameterList,
    /// The Solidity attributes of the function.
    pub attributes: FunctionAttributes,
    /// The optional return types of the function.
    pub returns: Option<Returns>,
}

impl PartialEq for TypeFunction {
    fn eq(&self, other: &Self) -> bool {
        self.arguments == other.arguments && self.returns == other.returns
    }
}

impl Eq for TypeFunction {}

impl Hash for TypeFunction {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.arguments.hash(state);
        self.returns.hash(state);
    }
}

impl fmt::Display for TypeFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("function (")?;
        self.arguments.fmt(f)?;
        f.write_str(")")?;

        for attr in &self.attributes.0 {
            write!(f, " {attr}")?;
        }

        if let Some(returns) = &self.returns {
            write!(f, " {returns}")?;
        }

        Ok(())
    }
}

impl fmt::Debug for TypeFunction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TypeFunction")
            .field("arguments", &self.arguments)
            .field("attributes", &self.attributes)
            .field("returns", &self.returns)
            .finish()
    }
}

impl Parse for TypeFunction {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let content;
        Ok(Self {
            function_token: input.parse()?,
            paren_token: parenthesized!(content in input),
            arguments: content.parse()?,
            attributes: input.parse()?,
            returns: input.call(Returns::parse_opt)?,
        })
    }
}

impl Spanned for TypeFunction {
    fn span(&self) -> Span {
        self.function_token.span
    }

    fn set_span(&mut self, span: Span) {
        self.function_token.span = span;
    }
}