solar-ast 0.2.0

Solidity and Yul AST type and visitor trait definitions
Documentation
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use super::{Box, Lit, SubDenomination, Type};
use crate::BoxSlice;
use either::Either;
use solar_data_structures::trustme;
use solar_interface::{Ident, Span, SpannedOption, diagnostics::ErrorGuaranteed};
use std::fmt;

/// A list of named arguments: `{a: "1", b: 2}`.
///
/// Present in [`CallArgsKind::Named`] and [`ExprKind::CallOptions`].
pub type NamedArgList<'ast> = BoxSlice<'ast, NamedArg<'ast>>;

/// An expression.
///
/// Reference: <https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.expression>
#[derive(Debug)]
pub struct Expr<'ast> {
    pub span: Span,
    pub kind: ExprKind<'ast>,
}

impl AsRef<Self> for Expr<'_> {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<'ast> Expr<'ast> {
    /// Peels off unnecessary parentheses from the expression.
    pub fn peel_parens(&self) -> &Self {
        let mut expr = self;
        while let ExprKind::Tuple(x) = &expr.kind
            && let [SpannedOption::Some(inner)] = x.as_slice()
        {
            expr = inner;
        }
        expr
    }

    /// Peels off unnecessary parentheses from the expression.
    pub fn peel_parens_mut(&mut self) -> &mut Self {
        let mut expr = self;
        // SAFETY: This is a bug in the compiler. This works when `x` is a slice and we can inline
        // into one pattern.
        while let ExprKind::Tuple(x) = &mut unsafe { trustme::decouple_lt_mut(expr) }.kind
            && let [SpannedOption::Some(inner)] = x.as_mut_slice()
        {
            expr = inner;
        }
        expr
    }

    /// Creates a new expression from an identifier.
    pub fn from_ident(ident: Ident) -> Self {
        Self { span: ident.span, kind: ExprKind::Ident(ident) }
    }

    /// Creates a new expression from a type.
    pub fn from_ty(ty: Type<'ast>) -> Self {
        Self { span: ty.span, kind: ExprKind::Type(ty) }
    }
}

/// A kind of expression.
#[derive(Debug)]
pub enum ExprKind<'ast> {
    /// An array literal expression: `[a, b, c, d]`.
    Array(BoxSlice<'ast, Box<'ast, Expr<'ast>>>),

    /// An assignment: `a = b`, `a += b`.
    Assign(Box<'ast, Expr<'ast>>, Option<BinOp>, Box<'ast, Expr<'ast>>),

    /// A binary operation: `a + b`, `a >> b`.
    Binary(Box<'ast, Expr<'ast>>, BinOp, Box<'ast, Expr<'ast>>),

    /// A function call expression: `foo(42)` or `foo({ bar: 42 })`.
    Call(Box<'ast, Expr<'ast>>, CallArgs<'ast>),

    /// Function call options: `foo.bar{ value: 1, gas: 2 }`.
    CallOptions(Box<'ast, Expr<'ast>>, NamedArgList<'ast>),

    /// A unary `delete` expression: `delete vector`.
    Delete(Box<'ast, Expr<'ast>>),

    /// An identifier: `foo`.
    Ident(Ident),

    /// A square bracketed indexing expression: `vector[index]`, `slice[l:r]`.
    Index(Box<'ast, Expr<'ast>>, IndexKind<'ast>),

    /// A literal: `hex"1234"`, `5.6 ether`.
    ///
    /// Note that the `SubDenomination` is only present for numeric literals, and it's already
    /// applied to `Lit`'s value. It is only present for error reporting/formatting purposes.
    Lit(Box<'ast, Lit<'ast>>, Option<SubDenomination>),

    /// Access of a named member: `obj.k`.
    Member(Box<'ast, Expr<'ast>>, Ident),

    /// A `new` expression: `new Contract`.
    New(Type<'ast>),

    /// A `payable` expression: `payable(address(0x...))`.
    Payable(CallArgs<'ast>),

    /// A ternary (AKA conditional) expression: `foo ? bar : baz`.
    Ternary(Box<'ast, Expr<'ast>>, Box<'ast, Expr<'ast>>, Box<'ast, Expr<'ast>>),

    /// A tuple expression: `(a,,, b, c, d)`.
    Tuple(BoxSlice<'ast, SpannedOption<Box<'ast, Expr<'ast>>>>),

    /// A `type()` expression: `type(uint256)`.
    TypeCall(Type<'ast>),

    /// An elementary type name: `uint256`.
    Type(Type<'ast>),

    /// A unary operation: `!x`, `-x`, `x++`.
    Unary(UnOp, Box<'ast, Expr<'ast>>),

    /// An erroneous expression emitted during parser recovery.
    Err(ErrorGuaranteed),
}

/// A binary operation: `a + b`, `a += b`.
#[derive(Clone, Copy, Debug)]
pub struct BinOp {
    pub span: Span,
    pub kind: BinOpKind,
}

/// A kind of binary operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum BinOpKind {
    /// `<`
    Lt,
    /// `<=`
    Le,
    /// `>`
    Gt,
    /// `>=`
    Ge,
    /// `==`
    Eq,
    /// `!=`
    Ne,
    /// `||`
    Or,
    /// `&&`
    And,

    /// `>>`
    Shr,
    /// `<<`
    Shl,
    /// `>>>`
    Sar,
    /// `&`
    BitAnd,
    /// `|`
    BitOr,
    /// `^`
    BitXor,

    /// `+`
    Add,
    /// `-`
    Sub,
    /// `**`
    Pow,
    /// `*`
    Mul,
    /// `/`
    Div,
    /// `%`
    Rem,
}

impl fmt::Display for BinOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.kind.to_str())
    }
}

impl BinOpKind {
    /// Returns the string representation of the operator.
    pub const fn to_str(self) -> &'static str {
        match self {
            Self::Lt => "<",
            Self::Le => "<=",
            Self::Gt => ">",
            Self::Ge => ">=",
            Self::Eq => "==",
            Self::Ne => "!=",
            Self::Or => "||",
            Self::And => "&&",
            Self::Sar => ">>>",
            Self::Shr => ">>",
            Self::Shl => "<<",
            Self::BitAnd => "&",
            Self::BitOr => "|",
            Self::BitXor => "^",
            Self::Add => "+",
            Self::Sub => "-",
            Self::Pow => "**",
            Self::Mul => "*",
            Self::Div => "/",
            Self::Rem => "%",
        }
    }

    /// Returns `true` if the operator is able to be used in an assignment.
    pub const fn assignable(self) -> bool {
        // https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.expression
        use BinOpKind::*;
        matches!(self, BitOr | BitXor | BitAnd | Shl | Shr | Sar | Add | Sub | Mul | Div | Rem)
    }

    /// Returns `true` if the operator is a comparison operator.
    pub const fn is_cmp(self) -> bool {
        use BinOpKind::*;
        matches!(self, Lt | Le | Gt | Ge | Eq | Ne)
    }

    /// Returns `true` if the operator is a shift operator.
    pub const fn is_shift(self) -> bool {
        use BinOpKind::*;
        matches!(self, Shl | Shr | Sar)
    }
}

/// A unary operation: `!x`, `-x`, `x++`.
#[derive(Clone, Copy, Debug)]
pub struct UnOp {
    pub span: Span,
    pub kind: UnOpKind,
}

/// A kind of unary operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum UnOpKind {
    /// `++x`
    PreInc,
    /// `--x`
    PreDec,
    /// `!`
    Not,
    /// `-`
    Neg,
    /// `~`
    BitNot,

    /// `x++`
    PostInc,
    /// `x--`
    PostDec,
}

impl fmt::Display for UnOp {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.kind.to_str())
    }
}

impl UnOpKind {
    /// Returns the string representation of the operator.
    pub const fn to_str(self) -> &'static str {
        match self {
            Self::PreInc | Self::PostInc => "++",
            Self::PreDec | Self::PostDec => "--",
            Self::Not => "!",
            Self::Neg => "-",
            Self::BitNot => "~",
        }
    }

    /// Returns `true` if the operator is a prefix operator.
    pub const fn is_prefix(self) -> bool {
        match self {
            Self::PreInc | Self::PreDec | Self::Not | Self::Neg | Self::BitNot => true,
            Self::PostInc | Self::PostDec => false,
        }
    }

    /// Returns `true` if the operator is a postfix operator.
    pub const fn is_postfix(self) -> bool {
        !self.is_prefix()
    }

    /// Returns `true` if the operator has side effects.
    pub const fn has_side_effects(self) -> bool {
        match self {
            Self::PreInc | Self::PreDec | Self::PostInc | Self::PostDec => true,
            Self::Not | Self::Neg | Self::BitNot => false,
        }
    }
}

/// A list of function call arguments.
#[derive(Debug)]
pub struct CallArgs<'ast> {
    /// The span of the arguments. This points to the parenthesized list of arguments.
    ///
    /// If the list is empty, this points to the empty `()`/`({})` or to where the `(` would be.
    pub span: Span,
    pub kind: CallArgsKind<'ast>,
}

impl<'ast> CallArgs<'ast> {
    /// Creates a new empty list of arguments.
    ///
    /// `span` should be an empty span.
    pub fn empty(span: Span) -> Self {
        Self { span, kind: CallArgsKind::empty() }
    }

    /// Returns `true` if the argument list is not present in the source code.
    ///
    /// For example, a modifier `m` can be invoked in a function declaration as `m` or `m()`. In the
    /// first case, this returns `true`, and the span will point to after `m`. In the second case,
    /// this returns `false`.
    pub fn is_dummy(&self) -> bool {
        self.span.lo() == self.span.hi()
    }

    /// Returns the length of the arguments.
    pub fn len(&self) -> usize {
        self.kind.len()
    }

    /// Returns `true` if the list of arguments is empty.
    pub fn is_empty(&self) -> bool {
        self.kind.is_empty()
    }

    /// Returns an iterator over the expressions.
    pub fn exprs(
        &self,
    ) -> impl ExactSizeIterator<Item = &Expr<'ast>> + DoubleEndedIterator + Clone {
        self.kind.exprs()
    }

    /// Returns an iterator over the expressions.
    pub fn exprs_mut(
        &mut self,
    ) -> impl ExactSizeIterator<Item = &mut Box<'ast, Expr<'ast>>> + DoubleEndedIterator {
        self.kind.exprs_mut()
    }
}

/// A list of function call argument expressions.
#[derive(Debug)]
pub enum CallArgsKind<'ast> {
    /// A list of unnamed arguments: `(1, 2, 3)`.
    Unnamed(BoxSlice<'ast, Box<'ast, Expr<'ast>>>),

    /// A list of named arguments: `({x: 1, y: 2, z: 3})`.
    Named(NamedArgList<'ast>),
}

impl Default for CallArgsKind<'_> {
    fn default() -> Self {
        Self::empty()
    }
}

impl<'ast> CallArgsKind<'ast> {
    /// Creates a new empty list of unnamed arguments.
    pub fn empty() -> Self {
        Self::Unnamed(BoxSlice::default())
    }

    /// Returns the length of the arguments.
    pub fn len(&self) -> usize {
        match self {
            Self::Unnamed(exprs) => exprs.len(),
            Self::Named(args) => args.len(),
        }
    }

    /// Returns `true` if the list of arguments is empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns an iterator over the expressions.
    pub fn exprs(
        &self,
    ) -> impl ExactSizeIterator<Item = &Expr<'ast>> + DoubleEndedIterator + Clone {
        match self {
            Self::Unnamed(exprs) => Either::Left(exprs.iter().map(|expr| &**expr)),
            Self::Named(args) => Either::Right(args.iter().map(|arg| &*arg.value)),
        }
    }

    /// Returns an iterator over the expressions.
    pub fn exprs_mut(
        &mut self,
    ) -> impl ExactSizeIterator<Item = &mut Box<'ast, Expr<'ast>>> + DoubleEndedIterator {
        match self {
            Self::Unnamed(exprs) => Either::Left(exprs.iter_mut()),
            Self::Named(args) => Either::Right(args.iter_mut().map(|arg| &mut arg.value)),
        }
    }

    /// Returns the span of the argument expressions. Does not include the parentheses.
    pub fn span(&self) -> Option<Span> {
        if self.is_empty() {
            return None;
        }
        Some(Span::join_first_last(self.exprs().map(|e| e.span)))
    }
}

/// A named argument: `name: value`.
#[derive(Debug)]
pub struct NamedArg<'ast> {
    pub name: Ident,
    pub value: Box<'ast, Expr<'ast>>,
}

/// A kind of square bracketed indexing expression: `vector[index]`, `slice[l:r]`.
#[derive(Debug)]
pub enum IndexKind<'ast> {
    /// A single index: `vector[index]`.
    Index(Option<Box<'ast, Expr<'ast>>>),

    /// A slice: `slice[l:r]`.
    Range(Option<Box<'ast, Expr<'ast>>>, Option<Box<'ast, Expr<'ast>>>),
}