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
use super::{SolIdent, Storage, Type};
use crate::{utils::tts_until_semi, VariableAttributes};
use proc_macro2::{Span, TokenStream};
use std::fmt::{self, Write};
use syn::{
    ext::IdentExt,
    parse::{Parse, ParseStream},
    Attribute, Ident, Result, Token,
};

mod list;
pub use list::{FieldList, ParameterList, Parameters};

/// A variable declaration.
///
/// `<ty> [storage] <name>`
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct VariableDeclaration {
    /// The attributes of the variable.
    pub attrs: Vec<Attribute>,
    /// The type of the variable.
    pub ty: Type,
    /// The storage location of the variable, if any.
    pub storage: Option<Storage>,
    /// The name of the variable. This is always Some if parsed as part of
    /// [`Parameters`].
    pub name: Option<SolIdent>,
}

impl fmt::Display for VariableDeclaration {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.ty.fmt(f)?;
        if let Some(storage) = &self.storage {
            f.write_char(' ')?;
            storage.fmt(f)?;
        }
        if let Some(name) = &self.name {
            f.write_char(' ')?;
            name.fmt(f)?;
        }
        Ok(())
    }
}

impl Parse for VariableDeclaration {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Self::_parse(input, false)
    }
}

impl VariableDeclaration {
    pub const fn new(ty: Type) -> Self {
        Self {
            attrs: Vec::new(),
            ty,
            storage: None,
            name: None,
        }
    }

    pub fn span(&self) -> Span {
        let span = self.ty.span();
        match (&self.storage, &self.name) {
            (Some(storage), None) => span.join(storage.span()),
            (_, Some(name)) => span.join(name.span()),
            (None, None) => Some(span),
        }
        .unwrap_or(span)
    }

    pub fn set_span(&mut self, span: Span) {
        self.ty.set_span(span);
        if let Some(storage) = &mut self.storage {
            storage.set_span(span);
        }
        if let Some(name) = &mut self.name {
            name.set_span(span);
        }
    }

    /// Formats `self` as an EIP-712 field: `<ty> <name>`
    pub fn fmt_eip712(&self, f: &mut impl Write) -> fmt::Result {
        write!(f, "{}", self.ty)?;
        if let Some(name) = &self.name {
            write!(f, " {}", name)?;
        }
        Ok(())
    }

    pub fn parse_for_struct(input: ParseStream<'_>) -> Result<Self> {
        Self::_parse(input, true)
    }

    fn _parse(input: ParseStream<'_>, for_struct: bool) -> Result<Self> {
        Ok(Self {
            attrs: input.call(Attribute::parse_outer)?,
            ty: input.parse()?,
            storage: input.call(Storage::parse_opt)?,
            // structs must have field names
            name: if for_struct || input.peek(Ident::peek_any) {
                Some(input.parse()?)
            } else {
                None
            },
        })
    }
}

#[derive(Clone, Debug)]
pub struct VariableDefinition {
    pub ty: Type,
    pub attributes: VariableAttributes,
    pub name: SolIdent,
    // TODO: Expr
    pub initializer: Option<(Token![=], TokenStream)>,
    pub semi_token: Token![;],
}

impl Parse for VariableDefinition {
    fn parse(input: ParseStream<'_>) -> Result<Self> {
        Ok(Self {
            ty: input.parse()?,
            attributes: input.parse()?,
            name: input.parse()?,
            initializer: if input.peek(Token![=]) {
                Some((input.parse()?, tts_until_semi(input)))
            } else {
                None
            },
            semi_token: input.parse()?,
        })
    }
}

impl VariableDefinition {
    pub fn span(&self) -> Span {
        let span = self.ty.span();
        span.join(self.semi_token.span).unwrap_or(span)
    }

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