syn_solidity/variable/
mod.rs

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
use crate::{Expr, SolIdent, Spanned, Storage, Type, VariableAttributes};
use proc_macro2::Span;
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: `string memory hello`.
#[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`] or a [`Stmt`][crate::Stmt].
    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 Spanned for VariableDeclaration {
    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)
    }

    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);
        }
    }
}

impl VariableDeclaration {
    pub const fn new(ty: Type) -> Self {
        Self::new_with(ty, None, None)
    }

    pub const fn new_with(ty: Type, storage: Option<Storage>, name: Option<SolIdent>) -> Self {
        Self { attrs: Vec::new(), ty, storage, name }
    }

    /// 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_with_name(input: ParseStream<'_>) -> Result<Self> {
        Self::_parse(input, true)
    }

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

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

impl fmt::Display for VariableDefinition {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} {} {}", self.ty, self.attributes, self.name)?;
        if let Some((_, _expr)) = &self.initializer {
            // TODO: fmt::Display for Expr
            write!(f, " = <expr>")?;
        }
        f.write_str(";")
    }
}

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

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

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

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

impl VariableDefinition {
    pub fn as_declaration(&self) -> VariableDeclaration {
        VariableDeclaration {
            attrs: Vec::new(),
            ty: self.ty.clone(),
            storage: None,
            name: Some(self.name.clone()),
        }
    }
}