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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
use crate::{
    kw, utils::DebugPunctuated, ParameterList, SolIdent, SolPath, Spanned, Type,
    VariableDeclaration,
};
use proc_macro2::Span;
use std::fmt;
use syn::{
    parenthesized,
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    token::Paren,
    Attribute, Error, Result, Token,
};

#[derive(Clone)]
pub struct ItemEvent {
    pub attrs: Vec<Attribute>,
    pub event_token: kw::event,
    pub name: SolIdent,
    pub paren_token: Paren,
    pub parameters: Punctuated<EventParameter, Token![,]>,
    pub anonymous: Option<kw::anonymous>,
    pub semi_token: Token![;],
}

impl fmt::Display for ItemEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "event {}(", self.name)?;
        for (i, param) in self.parameters.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            param.fmt(f)?;
        }
        f.write_str(")")?;
        if self.is_anonymous() {
            f.write_str(" anonymous")?;
        }
        f.write_str(";")
    }
}

impl fmt::Debug for ItemEvent {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ItemEvent")
            .field("attrs", &self.attrs)
            .field("name", &self.name)
            .field("arguments", DebugPunctuated::new(&self.parameters))
            .field("anonymous", &self.is_anonymous())
            .finish()
    }
}

impl Parse for ItemEvent {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        let content;
        Ok(Self {
            attrs: input.call(Attribute::parse_outer)?,
            event_token: input.parse()?,
            name: input.parse()?,
            paren_token: parenthesized!(content in input),
            parameters: content.parse_terminated(EventParameter::parse, Token![,])?,
            anonymous: input.parse()?,
            semi_token: input.parse()?,
        })
    }
}

impl Spanned for ItemEvent {
    fn span(&self) -> Span {
        self.name.span()
    }

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

impl ItemEvent {
    /// Returns `true` if the event is anonymous.
    #[inline]
    pub const fn is_anonymous(&self) -> bool {
        self.anonymous.is_some()
    }

    /// Returns the maximum amount of indexed parameters this event can have.
    ///
    /// This is `4` if the event is anonymous, otherwise `3`.
    #[inline]
    pub fn max_indexed(&self) -> usize {
        if self.is_anonymous() {
            4
        } else {
            3
        }
    }

    /// Returns `true` if the event has more indexed parameters than allowed by
    /// Solidity.
    ///
    /// See [`Self::max_indexed`].
    #[inline]
    pub fn exceeds_max_indexed(&self) -> bool {
        self.indexed_params().count() > self.max_indexed()
    }

    /// Asserts that the event has a valid amount of indexed parameters.
    pub fn assert_valid(&self) -> Result<()> {
        if self.exceeds_max_indexed() {
            let msg = if self.is_anonymous() {
                "more than 4 indexed arguments for anonymous event"
            } else {
                "more than 3 indexed arguments for event"
            };
            Err(Error::new(self.span(), msg))
        } else {
            Ok(())
        }
    }

    pub fn params(&self) -> ParameterList {
        self.parameters.iter().map(EventParameter::as_param).collect()
    }

    pub fn param_types(
        &self,
    ) -> impl ExactSizeIterator<Item = &Type> + DoubleEndedIterator + Clone {
        self.parameters.iter().map(|var| &var.ty)
    }

    pub fn param_types_mut(
        &mut self,
    ) -> impl ExactSizeIterator<Item = &mut Type> + DoubleEndedIterator {
        self.parameters.iter_mut().map(|var| &mut var.ty)
    }

    pub fn param_types_and_names(
        &self,
    ) -> impl ExactSizeIterator<Item = (&Type, Option<&SolIdent>)> + DoubleEndedIterator {
        self.parameters.iter().map(|p| (&p.ty, p.name.as_ref()))
    }

    pub fn param_type_strings(
        &self,
    ) -> impl ExactSizeIterator<Item = String> + DoubleEndedIterator + Clone + '_ {
        self.parameters.iter().map(|var| var.ty.to_string())
    }

    pub fn non_indexed_params(&self) -> impl Iterator<Item = &EventParameter> {
        self.parameters.iter().filter(|p| !p.is_indexed())
    }

    pub fn indexed_params(&self) -> impl Iterator<Item = &EventParameter> {
        self.parameters.iter().filter(|p| p.is_indexed())
    }

    pub fn as_type(&self) -> Type {
        let mut ty = Type::Tuple(self.parameters.iter().map(|arg| arg.ty.clone()).collect());
        ty.set_span(self.span());
        ty
    }
}

/// An event parameter.
///
/// `<ty> [indexed] [name]`
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct EventParameter {
    pub attrs: Vec<Attribute>,
    pub ty: Type,
    pub indexed: Option<kw::indexed>,
    pub name: Option<SolIdent>,
}

impl fmt::Display for EventParameter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.ty.fmt(f)?;
        if self.indexed.is_some() {
            f.write_str(" indexed")?;
        }
        if let Some(name) = &self.name {
            write!(f, " {name}")?;
        }
        Ok(())
    }
}

impl fmt::Debug for EventParameter {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EventParameter")
            .field("attrs", &self.attrs)
            .field("ty", &self.ty)
            .field("indexed", &self.indexed.is_some())
            .field("name", &self.name)
            .finish()
    }
}

impl Parse for EventParameter {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(Self {
            attrs: input.call(Attribute::parse_outer)?,
            ty: input.parse()?,
            indexed: input.parse()?,
            name: if SolIdent::peek_any(input) { Some(input.parse()?) } else { None },
        })
    }
}

impl Spanned for EventParameter {
    /// Get the span of the event parameter
    fn span(&self) -> Span {
        let span = self.ty.span();
        self.name.as_ref().and_then(|name| span.join(name.span())).unwrap_or(span)
    }

    /// Sets the span of the event parameter.
    fn set_span(&mut self, span: Span) {
        self.ty.set_span(span);
        if let Some(kw) = &mut self.indexed {
            kw.span = span;
        }
        if let Some(name) = &mut self.name {
            name.set_span(span);
        }
    }
}

impl EventParameter {
    /// Convert to a parameter declaration.
    pub fn as_param(&self) -> VariableDeclaration {
        VariableDeclaration {
            attrs: self.attrs.clone(),
            name: self.name.clone(),
            storage: None,
            ty: self.ty.clone(),
        }
    }

    /// Returns `true` if the parameter is indexed.
    #[inline]
    pub const fn is_indexed(&self) -> bool {
        self.indexed.is_some()
    }

    /// Returns `true` if the event parameter is stored in the event data
    /// section.
    pub const fn is_non_indexed(&self) -> bool {
        self.indexed.is_none()
    }

    /// Returns `true` if the event parameter is indexed and dynamically sized.
    /// These types are hashed, and then stored in the topics as specified in
    /// [the Solidity spec][ref].
    ///
    /// `custom_is_value_type` accounts for custom value types.
    ///
    /// [ref]: https://docs.soliditylang.org/en/latest/abi-spec.html#events
    pub fn indexed_as_hash(&self, custom_is_value_type: impl Fn(&SolPath) -> bool) -> bool {
        self.is_indexed() && !self.ty.is_value_type(custom_is_value_type)
    }
}