syn_solidity/expr/
array.rs

1use crate::{
2    Expr, Spanned,
3    utils::{DebugPunctuated, ParseNested},
4};
5use proc_macro2::Span;
6use std::fmt;
7use syn::{
8    Result, Token, bracketed,
9    parse::{Parse, ParseStream},
10    punctuated::Punctuated,
11    token::Bracket,
12};
13
14/// An array literal expression: `[a, b, c, d]`.
15#[derive(Clone)]
16pub struct ExprArray {
17    pub bracket_token: Bracket,
18    pub elems: Punctuated<Expr, Token![,]>,
19}
20
21impl fmt::Debug for ExprArray {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.debug_struct("ExprArray").field("elems", DebugPunctuated::new(&self.elems)).finish()
24    }
25}
26
27impl Parse for ExprArray {
28    fn parse(input: ParseStream<'_>) -> Result<Self> {
29        let content;
30        Ok(Self {
31            bracket_token: bracketed!(content in input),
32            elems: content.parse_terminated(Expr::parse, Token![,])?,
33        })
34    }
35}
36
37impl Spanned for ExprArray {
38    fn span(&self) -> Span {
39        self.bracket_token.span.join()
40    }
41
42    fn set_span(&mut self, span: Span) {
43        self.bracket_token = Bracket(span);
44    }
45}
46
47/// A square bracketed indexing expression: `vector[2]`.
48#[derive(Clone)]
49pub struct ExprIndex {
50    pub expr: Box<Expr>,
51    pub bracket_token: Bracket,
52    pub start: Option<Box<Expr>>,
53    pub colon_token: Option<Token![:]>,
54    pub end: Option<Box<Expr>>,
55}
56
57impl fmt::Debug for ExprIndex {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        f.debug_struct("ExprIndex")
60            .field("expr", &self.expr)
61            .field("start", &self.start)
62            .field("end", &self.end)
63            .finish()
64    }
65}
66
67impl ParseNested for ExprIndex {
68    fn parse_nested(expr: Box<Expr>, input: ParseStream<'_>) -> Result<Self> {
69        let content;
70        let bracket_token = bracketed!(content in input);
71        let start = if content.is_empty() || content.peek(Token![:]) {
72            None
73        } else {
74            Some(content.parse()?)
75        };
76        let colon_token = if content.is_empty() { None } else { Some(content.parse()?) };
77        let end =
78            if content.is_empty() || colon_token.is_none() { None } else { Some(content.parse()?) };
79        Ok(Self { expr, bracket_token, start, colon_token, end })
80    }
81}
82
83derive_parse!(ExprIndex);
84
85impl Spanned for ExprIndex {
86    fn span(&self) -> Span {
87        let span = self.expr.span();
88        span.join(self.bracket_token.span.join()).unwrap_or(span)
89    }
90
91    fn set_span(&mut self, span: Span) {
92        self.expr.set_span(span);
93        self.bracket_token = Bracket(span);
94    }
95}
96
97impl ExprIndex {
98    pub fn is_range(&self) -> bool {
99        self.colon_token.is_some()
100    }
101}