syn_solidity/item/
function.rs

1use crate::{
2    kw, Block, FunctionAttribute, FunctionAttributes, Mutability, ParameterList, Parameters,
3    SolIdent, Spanned, Stmt, Type, VariableDeclaration, VariableDefinition, Visibility,
4};
5use proc_macro2::Span;
6use std::{
7    fmt,
8    hash::{Hash, Hasher},
9    num::NonZeroU16,
10};
11use syn::{
12    parenthesized,
13    parse::{Parse, ParseStream},
14    token::{Brace, Paren},
15    Attribute, Error, Result, Token,
16};
17
18/// A function, constructor, fallback, receive, or modifier definition:
19/// `function helloWorld() external pure returns(string memory);`.
20///
21/// Solidity reference:
22/// <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.functionDefinition>
23#[derive(Clone)]
24pub struct ItemFunction {
25    /// The `syn` attributes of the function.
26    pub attrs: Vec<Attribute>,
27    pub kind: FunctionKind,
28    pub name: Option<SolIdent>,
29    /// Parens are optional for modifiers:
30    /// <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.modifierDefinition>
31    pub paren_token: Option<Paren>,
32    pub parameters: ParameterList,
33    /// The Solidity attributes of the function.
34    pub attributes: FunctionAttributes,
35    /// The optional return types of the function.
36    pub returns: Option<Returns>,
37    pub body: FunctionBody,
38}
39
40impl fmt::Display for ItemFunction {
41    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
42        f.write_str(self.kind.as_str())?;
43        if let Some(name) = &self.name {
44            f.write_str(" ")?;
45            name.fmt(f)?;
46        }
47        write!(f, "({})", self.parameters)?;
48
49        if !self.attributes.is_empty() {
50            write!(f, " {}", self.attributes)?;
51        }
52
53        if let Some(returns) = &self.returns {
54            write!(f, " {returns}")?;
55        }
56
57        if !self.body.is_empty() {
58            f.write_str(" ")?;
59        }
60        f.write_str(self.body.as_str())
61    }
62}
63
64impl fmt::Debug for ItemFunction {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        f.debug_struct("ItemFunction")
67            .field("attrs", &self.attrs)
68            .field("kind", &self.kind)
69            .field("name", &self.name)
70            .field("arguments", &self.parameters)
71            .field("attributes", &self.attributes)
72            .field("returns", &self.returns)
73            .field("body", &self.body)
74            .finish()
75    }
76}
77
78impl Parse for ItemFunction {
79    fn parse(input: ParseStream<'_>) -> Result<Self> {
80        let attrs = input.call(Attribute::parse_outer)?;
81        let kind: FunctionKind = input.parse()?;
82        let name = input.call(SolIdent::parse_opt)?;
83
84        let (paren_token, parameters) = if kind.is_modifier() && !input.peek(Paren) {
85            (None, ParameterList::new())
86        } else {
87            let content;
88            (Some(parenthesized!(content in input)), content.parse()?)
89        };
90
91        let attributes = input.parse()?;
92        let returns = input.call(Returns::parse_opt)?;
93        let body = input.parse()?;
94
95        Ok(Self { attrs, kind, name, paren_token, parameters, attributes, returns, body })
96    }
97}
98
99impl Spanned for ItemFunction {
100    fn span(&self) -> Span {
101        if let Some(name) = &self.name {
102            name.span()
103        } else {
104            self.kind.span()
105        }
106    }
107
108    fn set_span(&mut self, span: Span) {
109        self.kind.set_span(span);
110        if let Some(name) = &mut self.name {
111            name.set_span(span);
112        }
113    }
114}
115
116impl ItemFunction {
117    /// Create a new function of the given kind.
118    pub fn new(kind: FunctionKind, name: Option<SolIdent>) -> Self {
119        let span = name.as_ref().map_or_else(|| kind.span(), |name| name.span());
120        Self {
121            attrs: Vec::new(),
122            kind,
123            name,
124            paren_token: Some(Paren(span)),
125            parameters: Parameters::new(),
126            attributes: FunctionAttributes::new(),
127            returns: None,
128            body: FunctionBody::Empty(Token![;](span)),
129        }
130    }
131
132    /// Create a new function with the given name and arguments.
133    ///
134    /// Note that:
135    /// - the type is not validated
136    /// - structs/array of structs in return position are not expanded
137    /// - the body is not set
138    ///
139    /// The attributes are set to `public view`.
140    ///
141    /// See [the Solidity documentation][ref] for more details on how getters
142    /// are generated.
143    ///
144    /// [ref]: https://docs.soliditylang.org/en/latest/contracts.html#getter-functions
145    pub fn new_getter(name: SolIdent, ty: Type) -> Self {
146        let span = name.span();
147        let kind = FunctionKind::new_function(span);
148        let mut function = Self::new(kind, Some(name.clone()));
149
150        // `public view`
151        function.attributes.0 = vec![
152            FunctionAttribute::Visibility(Visibility::new_public(span)),
153            FunctionAttribute::Mutability(Mutability::new_view(span)),
154        ];
155
156        // Recurse into mappings and arrays to generate arguments and the return type.
157        // If the return type is simple, the return value name is set to the variable name.
158        let mut ty = ty;
159        let mut return_name = None;
160        let mut first = true;
161        loop {
162            match ty {
163                // mapping(k => v) -> arguments += k, ty = v
164                Type::Mapping(map) => {
165                    let key = VariableDeclaration::new_with(*map.key, None, map.key_name);
166                    function.parameters.push(key);
167                    return_name = map.value_name;
168                    ty = *map.value;
169                }
170                // inner[] -> arguments += uint256, ty = inner
171                Type::Array(array) => {
172                    let uint256 = Type::Uint(span, NonZeroU16::new(256));
173                    function.parameters.push(VariableDeclaration::new(uint256));
174                    ty = *array.ty;
175                }
176                _ => {
177                    if first {
178                        return_name = Some(name);
179                    }
180                    break;
181                }
182            }
183            first = false;
184        }
185        let mut returns = ParameterList::new();
186        returns.push(VariableDeclaration::new_with(ty, None, return_name));
187        function.returns = Some(Returns::new(span, returns));
188
189        function
190    }
191
192    /// Creates a new function from a variable definition.
193    ///
194    /// The function will have the same name and the variable type's will be the
195    /// return type. The variable attributes are ignored, and instead will
196    /// always generate `public returns`.
197    ///
198    /// See [`new_getter`](Self::new_getter) for more details.
199    pub fn from_variable_definition(var: VariableDefinition) -> Self {
200        let mut function = Self::new_getter(var.name, var.ty);
201        function.attrs = var.attrs;
202        function
203    }
204
205    /// Returns the name of the function.
206    ///
207    /// # Panics
208    ///
209    /// Panics if the function has no name. This is the case when `kind` is not
210    /// `Function`.
211    #[track_caller]
212    pub fn name(&self) -> &SolIdent {
213        match &self.name {
214            Some(name) => name,
215            None => panic!("function has no name: {self:?}"),
216        }
217    }
218
219    /// Returns true if the function returns nothing.
220    pub fn is_void(&self) -> bool {
221        match &self.returns {
222            None => true,
223            Some(returns) => returns.returns.is_empty(),
224        }
225    }
226
227    /// Returns true if the function has a body.
228    pub fn has_implementation(&self) -> bool {
229        matches!(self.body, FunctionBody::Block(_))
230    }
231
232    /// Returns the function's arguments tuple type.
233    pub fn call_type(&self) -> Type {
234        Type::Tuple(self.parameters.types().cloned().collect())
235    }
236
237    /// Returns the function's return tuple type.
238    pub fn return_type(&self) -> Option<Type> {
239        self.returns.as_ref().map(|returns| Type::Tuple(returns.returns.types().cloned().collect()))
240    }
241
242    /// Returns a reference to the function's body, if any.
243    pub fn body(&self) -> Option<&[Stmt]> {
244        match &self.body {
245            FunctionBody::Block(block) => Some(&block.stmts),
246            _ => None,
247        }
248    }
249
250    /// Returns a mutable reference to the function's body, if any.
251    pub fn body_mut(&mut self) -> Option<&mut Vec<Stmt>> {
252        match &mut self.body {
253            FunctionBody::Block(block) => Some(&mut block.stmts),
254            _ => None,
255        }
256    }
257
258    pub fn into_body(self) -> std::result::Result<Vec<Stmt>, Self> {
259        match self.body {
260            FunctionBody::Block(block) => Ok(block.stmts),
261            _ => Err(self),
262        }
263    }
264}
265
266kw_enum! {
267    /// The kind of function.
268    pub enum FunctionKind {
269        Constructor(kw::constructor),
270        Function(kw::function),
271        Fallback(kw::fallback),
272        Receive(kw::receive),
273        Modifier(kw::modifier),
274    }
275}
276
277/// The `returns` attribute of a function.
278#[derive(Clone)]
279pub struct Returns {
280    pub returns_token: kw::returns,
281    pub paren_token: Paren,
282    /// The returns of the function. This cannot be parsed empty.
283    pub returns: ParameterList,
284}
285
286impl PartialEq for Returns {
287    fn eq(&self, other: &Self) -> bool {
288        self.returns == other.returns
289    }
290}
291
292impl Eq for Returns {}
293
294impl Hash for Returns {
295    fn hash<H: Hasher>(&self, state: &mut H) {
296        self.returns.hash(state);
297    }
298}
299
300impl fmt::Display for Returns {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        f.write_str("returns (")?;
303        self.returns.fmt(f)?;
304        f.write_str(")")
305    }
306}
307
308impl fmt::Debug for Returns {
309    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
310        f.debug_tuple("Returns").field(&self.returns).finish()
311    }
312}
313
314impl Parse for Returns {
315    fn parse(input: ParseStream<'_>) -> Result<Self> {
316        let content;
317        let this = Self {
318            returns_token: input.parse()?,
319            paren_token: parenthesized!(content in input),
320            returns: content.parse()?,
321        };
322        if this.returns.is_empty() {
323            Err(Error::new(this.paren_token.span.join(), "expected at least one return type"))
324        } else {
325            Ok(this)
326        }
327    }
328}
329
330impl Spanned for Returns {
331    fn span(&self) -> Span {
332        let span = self.returns_token.span;
333        span.join(self.paren_token.span.join()).unwrap_or(span)
334    }
335
336    fn set_span(&mut self, span: Span) {
337        self.returns_token.span = span;
338        self.paren_token = Paren(span);
339    }
340}
341
342impl Returns {
343    pub fn new(span: Span, returns: ParameterList) -> Self {
344        Self { returns_token: kw::returns(span), paren_token: Paren(span), returns }
345    }
346
347    pub fn parse_opt(input: ParseStream<'_>) -> Result<Option<Self>> {
348        if input.peek(kw::returns) {
349            input.parse().map(Some)
350        } else {
351            Ok(None)
352        }
353    }
354}
355
356/// The body of a function.
357#[derive(Clone)]
358pub enum FunctionBody {
359    /// A function without implementation.
360    Empty(Token![;]),
361    /// A function body delimited by curly braces.
362    Block(Block),
363}
364
365impl fmt::Display for FunctionBody {
366    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
367        f.write_str(self.as_str())
368    }
369}
370
371impl fmt::Debug for FunctionBody {
372    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
373        f.write_str("FunctionBody::")?;
374        match self {
375            Self::Empty(_) => f.write_str("Empty"),
376            Self::Block(block) => block.fmt(f),
377        }
378    }
379}
380
381impl Parse for FunctionBody {
382    fn parse(input: ParseStream<'_>) -> Result<Self> {
383        let lookahead = input.lookahead1();
384        if lookahead.peek(Brace) {
385            input.parse().map(Self::Block)
386        } else if lookahead.peek(Token![;]) {
387            input.parse().map(Self::Empty)
388        } else {
389            Err(lookahead.error())
390        }
391    }
392}
393
394impl FunctionBody {
395    /// Returns `true` if the function body is empty.
396    #[inline]
397    pub fn is_empty(&self) -> bool {
398        matches!(self, Self::Empty(_))
399    }
400
401    /// Returns a string representation of the function body.
402    #[inline]
403    pub fn as_str(&self) -> &'static str {
404        match self {
405            Self::Empty(_) => ";",
406            // TODO: fmt::Display for Stmt
407            Self::Block(_) => "{ <stmts> }",
408        }
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use super::*;
415    use pretty_assertions::assert_eq;
416    use std::{
417        error::Error,
418        io::Write,
419        process::{Command, Stdio},
420    };
421    use syn::parse_quote;
422
423    #[test]
424    fn modifiers() {
425        let none: ItemFunction = parse_quote! {
426            modifier noParens {
427                _;
428            }
429        };
430        let some: ItemFunction = parse_quote! {
431            modifier withParens() {
432                _;
433            }
434        };
435        assert_eq!(none.kind, FunctionKind::new_modifier(Span::call_site()));
436        assert_eq!(none.kind, some.kind);
437        assert_eq!(none.paren_token, None);
438        assert_eq!(some.paren_token, Some(Default::default()));
439    }
440
441    #[test]
442    #[cfg_attr(miri, ignore = "takes too long")]
443    fn getters() {
444        let run_solc = run_solc();
445
446        macro_rules! test_getters {
447            ($($var:literal => $f:literal),* $(,)?) => {
448                let vars: &[&str] = &[$($var),*];
449                let fns: &[&str] = &[$($f),*];
450                for (var, f) in std::iter::zip(vars, fns) {
451                    test_getter(var, f, run_solc);
452                }
453            };
454        }
455
456        test_getters! {
457            "bool public simple;"
458                => "function simple() public view returns (bool simple);",
459            "bool public constant simpleConstant = false;"
460                => "function simpleConstant() public view returns (bool simpleConstant);",
461
462            "mapping(address => bool) public map;"
463                => "function map(address) public view returns (bool);",
464            "mapping(address a => bool b) public mapWithNames;"
465                => "function mapWithNames(address a) public view returns (bool b);",
466            "mapping(uint256 k1 => mapping(uint256 k2 => bool v) ignored) public nested2;"
467                => "function nested2(uint256 k1, uint256 k2) public view returns (bool v);",
468            "mapping(uint256 k1 => mapping(uint256 k2 => mapping(uint256 k3 => bool v) ignored1) ignored2) public nested3;"
469                => "function nested3(uint256 k1, uint256 k2, uint256 k3) public view returns (bool v);",
470
471            "bool[] public boolArray;"
472                => "function boolArray(uint256) public view returns(bool);",
473            "mapping(bool => bytes2)[] public mapArray;"
474                => "function mapArray(uint256, bool) public view returns(bytes2);",
475            "mapping(bool => mapping(address => int[])[])[][] public nestedMapArray;"
476                => "function nestedMapArray(uint256, uint256, bool, uint256, address, uint256) public view returns(int);",
477        }
478    }
479
480    fn test_getter(var_s: &str, fn_s: &str, run_solc: bool) {
481        let var = syn::parse_str::<VariableDefinition>(var_s).unwrap();
482        let getter = ItemFunction::from_variable_definition(var);
483        let f = syn::parse_str::<ItemFunction>(fn_s).unwrap();
484        assert_eq!(format!("{getter:#?}"), format!("{f:#?}"), "{var_s}");
485
486        // Test that the ABIs are the same.
487        // Skip `simple` getters since the return type will have a different ABI because Solc
488        // doesn't populate the field.
489        if run_solc && !var_s.contains("simple") {
490            match (wrap_and_compile(var_s, true), wrap_and_compile(fn_s, false)) {
491                (Ok(a), Ok(b)) => {
492                    assert_eq!(a.trim(), b.trim(), "\nleft:  {var_s:?}\nright: {fn_s:?}")
493                }
494                (Err(e), _) | (_, Err(e)) => panic!("{e}"),
495            }
496        }
497    }
498
499    fn run_solc() -> bool {
500        let Some(v) = get_solc_version() else { return false };
501        // Named keys in mappings: https://soliditylang.org/blog/2023/02/01/solidity-0.8.18-release-announcement/
502        v >= (0, 8, 18)
503    }
504
505    fn get_solc_version() -> Option<(u16, u16, u16)> {
506        let output = Command::new("solc").arg("--version").output().ok()?;
507        if !output.status.success() {
508            return None;
509        }
510        let stdout = String::from_utf8(output.stdout).ok()?;
511
512        let start = stdout.find(": 0.")?;
513        let version = &stdout[start + 2..];
514        let end = version.find('+')?;
515        let version = &version[..end];
516
517        let mut iter = version.split('.').map(|s| s.parse::<u16>().expect("bad solc version"));
518        let major = iter.next().unwrap();
519        let minor = iter.next().unwrap();
520        let patch = iter.next().unwrap();
521        Some((major, minor, patch))
522    }
523
524    fn wrap_and_compile(s: &str, var: bool) -> std::result::Result<String, Box<dyn Error>> {
525        let contract = if var {
526            format!("contract C {{ {s} }}")
527        } else {
528            format!("abstract contract C {{ {} }}", s.replace("returns", "virtual returns"))
529        };
530        let mut cmd = Command::new("solc")
531            .args(["--abi", "--pretty-json", "-"])
532            .stdin(Stdio::piped())
533            .stdout(Stdio::piped())
534            .stderr(Stdio::piped())
535            .spawn()?;
536        cmd.stdin.as_mut().unwrap().write_all(contract.as_bytes())?;
537        let output = cmd.wait_with_output()?;
538        if output.status.success() {
539            String::from_utf8(output.stdout).map_err(Into::into)
540        } else {
541            Err(String::from_utf8(output.stderr)?.into())
542        }
543    }
544}