solar-parse 0.3.1

Solidity and Yul lexer and parser
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
use crate::{PResult, Parser};
use smallvec::SmallVec;
use solar_ast::{token::*, *};

use solar_interface::{Ident, SpannedOption, Symbol, kw};

impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
    /// Parses an expression.
    #[inline]
    pub fn parse_expr(&mut self) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        self.with_recursion_limit("expression", |this| this.parse_expr_with(None))
    }

    pub(super) fn parse_expr_with(
        &mut self,
        with: Option<Box<'ast, Expr<'ast>>>,
    ) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        let expr = self.parse_binary_expr(4, with)?;
        if self.eat(TokenKind::Question) {
            let then = self.parse_expr()?;
            self.expect(TokenKind::Colon)?;
            let else_ = self.parse_expr()?;
            let span = expr.span.to(self.prev_token.span);
            Ok(self.alloc(Expr { span, kind: ExprKind::Ternary(expr, then, else_) }))
        } else {
            let kind = if let Some(binop_eq) = self.token.as_binop_eq() {
                Some(binop_eq)
            } else if self.token.kind == TokenKind::Eq {
                None
            } else {
                return Ok(expr);
            };
            self.bump(); // binop token
            let rhs = self.parse_expr()?;
            let span = expr.span.to(self.prev_token.span);
            Ok(self.alloc(Expr { span, kind: ExprKind::Assign(expr, kind, rhs) }))
        }
    }

    /// Parses a binary expression.
    #[inline]
    fn parse_binary_expr(
        &mut self,
        min_precedence: usize,
        with: Option<Box<'ast, Expr<'ast>>>,
    ) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        // Nested expressions merge their depth into the outer value when they finish, also when
        // they fail and the caller recovers. A `with` expression carries its depth in `expr_depth`
        // already.
        let outer_depth = if with.is_some() { 0 } else { std::mem::take(&mut self.expr_depth) };
        let res = self.parse_binary_expr_inner(min_precedence, with);
        self.expr_depth = self.expr_depth.max(outer_depth);
        res
    }

    fn parse_binary_expr_inner(
        &mut self,
        min_precedence: usize,
        with: Option<Box<'ast, Expr<'ast>>>,
    ) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        let mut expr = self.parse_unary_expr(with)?;
        let mut precedence = token_precedence(self.token);
        while precedence >= min_precedence {
            while token_precedence(self.token) == precedence {
                let token = self.token;
                self.bump(); // binop token

                // Parse a**b**c as a**(b**c), counting each nested `**` toward the recursion limit.
                let rhs = if token.kind == TokenKind::StarStar {
                    self.with_recursion_limit("expression", |this| {
                        this.parse_binary_expr(precedence, None)
                    })?
                } else {
                    self.parse_binary_expr(precedence + 1, None)?
                };

                let span = expr.span.to(self.prev_token.span);

                let kind = if let Some(binop) = token.as_binop() {
                    ExprKind::Binary(expr, binop, rhs)
                } else if let Some(binop_eq) = token.as_binop_eq() {
                    ExprKind::Assign(expr, Some(binop_eq), rhs)
                } else if token.kind == TokenKind::Eq {
                    ExprKind::Assign(expr, None, rhs)
                } else {
                    self.unknown_binop(token, span);
                };
                expr = self.alloc(Expr { span, kind });
                self.bump_expr_depth()?;
            }
            precedence -= 1;
        }
        Ok(expr)
    }

    #[cold]
    #[inline(never)]
    fn unknown_binop(&self, token: Token, span: Span) -> ! {
        let msg = format!("unknown binop token: {token:?}");
        self.dcx().bug(msg).span(span).emit()
    }

    /// Parses a unary expression.
    fn parse_unary_expr(
        &mut self,
        with: Option<Box<'ast, Expr<'ast>>>,
    ) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        if with.is_none() && self.eat(TokenKind::BinOp(BinOpToken::Plus)) {
            self.dcx().emit_err(self.prev_token.span, "unary plus is not supported");
        }

        let lo = with.as_ref().map(|e| e.span).unwrap_or(self.token.span);
        let parse_lhs = |this: &mut Self, with| {
            this.parse_lhs_expr(with, lo).map(|expr| {
                if let Some(unop) = this.token.as_unop(true) {
                    this.bump(); // unop
                    this.expr_depth += 1;
                    let span = lo.to(this.prev_token.span);
                    this.alloc(Expr { span, kind: ExprKind::Unary(unop, expr) })
                } else {
                    expr
                }
            })
        };
        if let Some(with) = with {
            parse_lhs(self, Some(with))
        } else if self.eat_keyword(kw::Delete) {
            self.parse_prefix_operand().map(|expr| {
                self.expr_depth += 1;
                let span = lo.to(self.prev_token.span);
                self.alloc(Expr { span, kind: ExprKind::Delete(expr) })
            })
        } else if let Some(unop) = self.token.as_unop(false) {
            self.bump(); // unop
            self.parse_prefix_operand().map(|expr| {
                self.expr_depth += 1;
                let span = lo.to(self.prev_token.span);
                self.alloc(Expr { span, kind: ExprKind::Unary(unop, expr) })
            })
        } else {
            parse_lhs(self, None)
        }
    }

    /// Parses the operand of a prefix operator, which counts toward the recursion limit.
    fn parse_prefix_operand(&mut self) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        self.with_recursion_limit("expression", |this| this.parse_unary_expr(None))
    }

    /// Parses a primary left-hand-side expression.
    fn parse_lhs_expr(
        &mut self,
        with: Option<Box<'ast, Expr<'ast>>>,
        lo: Span,
    ) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        let counted = with.is_some();
        let mut expr = if let Some(with) = with {
            Ok(with)
        } else if self.eat_keyword(kw::New) {
            self.parse_type().map(|ty| {
                let span = lo.to(self.prev_token.span);
                self.alloc(Expr { span, kind: ExprKind::New(ty) })
            })
        } else if self.eat_keyword(kw::Payable) {
            self.parse_call_args().map(|args| {
                let span = lo.to(self.prev_token.span);
                self.alloc(Expr { span, kind: ExprKind::Payable(args) })
            })
        } else {
            self.parse_primary_expr()
        }?;
        // A `with` expression carries its depth in `expr_depth` already.
        if !counted {
            self.expr_depth += 1;
        }
        loop {
            let kind = if self.eat(TokenKind::Dot) {
                let dot_span = self.prev_token.span;
                // expr.member
                match self.parse_ident_any() {
                    Ok(member) => ExprKind::Member(expr, member),
                    Err(err) => {
                        err.emit();
                        let member = Ident::new(Symbol::DUMMY, dot_span.shrink_to_hi());
                        ExprKind::Member(expr, member)
                    }
                }
            } else if self.check(TokenKind::OpenDelim(Delimiter::Parenthesis)) {
                // expr(args)
                let args = self.parse_call_args()?;
                ExprKind::Call(expr, args)
            } else if self.check(TokenKind::OpenDelim(Delimiter::Bracket)) {
                let kind = self.parse_expr_index_kind()?;
                ExprKind::Index(expr, kind)
            } else if self.check(TokenKind::OpenDelim(Delimiter::Brace)) {
                // This may be `try` statement block.
                if !self.look_ahead(1).is_ident() || self.look_ahead(2).kind != TokenKind::Colon {
                    break;
                }

                // expr{args}
                let args = self.parse_named_args(false)?;
                ExprKind::CallOptions(expr, args)
            } else {
                break;
            };
            let span = lo.to(self.prev_token.span);
            expr = self.alloc(Expr { span, kind });
            self.bump_expr_depth()?;
        }
        Ok(expr)
    }

    /// Parses a primary expression.
    fn parse_primary_expr(&mut self) -> PResult<'sess, Box<'ast, Expr<'ast>>> {
        let lo = self.token.span;
        let kind = if self.check_lit() {
            self.parse_lit_expr()?
        } else if self.eat_keyword(kw::Type) {
            self.expect(TokenKind::OpenDelim(Delimiter::Parenthesis))?;
            let ty = self.parse_type()?;
            self.expect(TokenKind::CloseDelim(Delimiter::Parenthesis))?;
            ExprKind::TypeCall(ty)
        } else if self.check_elementary_type() {
            let mut ty = self.parse_type()?;
            if let TypeKind::Elementary(ElementaryType::Address(payable)) = &mut ty.kind
                && *payable
            {
                let msg = "`address payable` cannot be used in an expression";
                self.dcx().emit_err(ty.span, msg);
                *payable = false;
            }
            ExprKind::Type(ty)
        } else if self.check_nr_ident() {
            let ident = self.parse_ident()?;
            ExprKind::Ident(ident)
        } else if self.check(TokenKind::OpenDelim(Delimiter::Parenthesis))
            || self.check(TokenKind::OpenDelim(Delimiter::Bracket))
        {
            self.parse_tuple_or_array_expr(lo)?
        } else {
            return self.unexpected();
        };
        let span = lo.to(self.prev_token.span);
        Ok(self.alloc(Expr { span, kind }))
    }

    /// Parses a literal expression.
    ///
    /// Kept out of line so that the literal takes no space in other expressions.
    #[inline(never)]
    fn parse_lit_expr(&mut self) -> PResult<'sess, ExprKind<'ast>> {
        let (lit, sub) = self.parse_lit(true)?;
        Ok(ExprKind::Lit(self.alloc(lit), sub))
    }

    /// Parses an array or tuple expression.
    fn parse_tuple_or_array_expr(&mut self, lo: Span) -> PResult<'sess, ExprKind<'ast>> {
        let TokenKind::OpenDelim(close_delim) = self.token.kind else { unreachable!() };
        let close = TokenKind::CloseDelim(close_delim);
        let next = self.look_ahead(1).kind;
        if next == TokenKind::Comma || next == close {
            return self.parse_tuple_or_array_expr_list(lo, close_delim, None);
        }

        // Parse the first component before the list exists, so that nested single components
        // take less stack.
        self.bump();
        let first = self.parse_expr()?;
        if !self.eat(close) {
            return self.parse_tuple_or_array_expr_list(lo, close_delim, Some(first));
        }
        Ok(if close_delim == Delimiter::Parenthesis {
            ExprKind::Tuple(self.alloc_from_iter(std::iter::once(SpannedOption::Some(first))))
        } else {
            ExprKind::Array(self.alloc_from_iter(std::iter::once(first)))
        })
    }

    /// Parses the components of an array or tuple expression, starting after `first` if given.
    ///
    /// Kept out of line so that its buffer takes no space in other expressions.
    #[inline(never)]
    fn parse_tuple_or_array_expr_list(
        &mut self,
        lo: Span,
        close_delim: Delimiter,
        first: Option<Box<'ast, Expr<'ast>>>,
    ) -> PResult<'sess, ExprKind<'ast>> {
        let mut list = SmallVec::new();
        if let Some(first) = first {
            list.push(SpannedOption::Some(first));
            self.parse_optional_items_seq_required(close_delim, &mut list, Self::parse_expr)?;
        } else {
            self.parse_optional_items_seq(close_delim, &mut list, Self::parse_expr)?;
        }
        if close_delim == Delimiter::Parenthesis {
            return Ok(ExprKind::Tuple(self.alloc_drain(&mut list)));
        }
        if list.iter().any(SpannedOption::is_none) {
            let msg = "array expression components cannot be empty";
            return Err(self.dcx().err_at(lo.to(self.prev_token.span), msg));
        }
        Ok(ExprKind::Array(self.alloc_from_iter(list.drain(..).map(|item| item.unspan().unwrap()))))
    }

    /// Parses a list of function call arguments.
    #[track_caller]
    pub(super) fn parse_call_args(&mut self) -> PResult<'sess, CallArgs<'ast>> {
        self.parse_spanned(Self::parse_call_args_kind).map(|(span, kind)| CallArgs { span, kind })
    }

    #[track_caller]
    fn parse_call_args_kind(&mut self) -> PResult<'sess, CallArgsKind<'ast>> {
        if self.look_ahead(1).kind == TokenKind::OpenDelim(Delimiter::Brace) {
            self.expect(TokenKind::OpenDelim(Delimiter::Parenthesis))?;
            let args = self.parse_named_args(true).map(CallArgsKind::Named)?;
            self.expect(TokenKind::CloseDelim(Delimiter::Parenthesis))?;
            Ok(args)
        } else {
            self.parse_unnamed_args().map(CallArgsKind::Unnamed)
        }
    }

    /// Parses a `[]` indexing expression.
    pub(super) fn parse_expr_index_kind(&mut self) -> PResult<'sess, IndexKind<'ast>> {
        self.expect(TokenKind::OpenDelim(Delimiter::Bracket))?;
        let kind = if self.check(TokenKind::CloseDelim(Delimiter::Bracket)) {
            // expr[]
            IndexKind::Index(None)
        } else {
            let start = if self.check(TokenKind::Colon) { None } else { Some(self.parse_expr()?) };
            if self.eat_noexpect(TokenKind::Colon) {
                // expr[start?:end?]
                let end = if self.check(TokenKind::CloseDelim(Delimiter::Bracket)) {
                    None
                } else {
                    Some(self.parse_expr()?)
                };
                IndexKind::Range(start, end)
            } else {
                // expr[start?]
                IndexKind::Index(start)
            }
        };
        self.expect(TokenKind::CloseDelim(Delimiter::Bracket))?;
        Ok(kind)
    }

    /// Parses a list of named arguments: `{a: b, c: d, ...}`
    #[track_caller]
    fn parse_named_args(&mut self, allow_empty: bool) -> PResult<'sess, NamedArgList<'ast>> {
        self.parse_delim_comma_seq(Delimiter::Brace, allow_empty, Self::parse_named_arg)
    }

    /// Parses a single named argument: `a: b`.
    #[track_caller]
    fn parse_named_arg(&mut self) -> PResult<'sess, NamedArg<'ast>> {
        let name = self.parse_ident()?;
        self.expect(TokenKind::Colon)?;
        let value = self.parse_expr()?;
        Ok(NamedArg { name, value })
    }

    /// Parses a list of expressions: `(a, b, c, ...)`.
    #[allow(clippy::vec_box)]
    #[track_caller]
    fn parse_unnamed_args(&mut self) -> PResult<'sess, BoxSlice<'ast, Box<'ast, Expr<'ast>>>> {
        self.parse_paren_comma_seq(true, Self::parse_expr)
    }
}

fn token_precedence(t: Token) -> usize {
    // https://github.com/argotorg/solidity/blob/78ec8dd6f93bf5a5b4ca7582f9d491a4f66c3610/liblangutil/Token.h#L68
    use BinOpToken::*;
    use TokenKind::*;
    match t.kind {
        Question => 3,
        Eq => 2,
        BinOpEq(_) => 2,
        Comma => 1,
        OrOr => 4,
        AndAnd => 5,
        BinOp(Or) => 8,
        BinOp(Caret) => 9,
        BinOp(And) => 10,
        BinOp(Shl) => 11,
        BinOp(Sar) => 11,
        BinOp(Shr) => 11,
        BinOp(Plus) => 12,
        BinOp(Minus) => 12,
        BinOp(Star) => 13,
        BinOp(Slash) => 13,
        BinOp(Percent) => 13,
        StarStar => 14,
        EqEq => 6,
        Ne => 6,
        Lt => 7,
        Gt => 7,
        Le => 7,
        Ge => 7,
        Walrus => 2,
        _ => 0,
    }
}