syn_solidity/expr/
array.rs

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