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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
use crate::{PResult, Parser};
use smallvec::SmallVec;
use solar_ast::{
    AstPath, Box, DocComments, Lit, LitKind, PathSlice, StrKind, StrLit, Symbol, token::*, yul::*,
};
use solar_interface::{Ident, error_code, kw, sym};

impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
    /// Parses a Yul object or plain block.
    ///
    /// The plain block gets returned as a Yul object named "object", with a single `code` block.
    /// See: <https://github.com/argotorg/solidity/blob/eff410eb746f202fe756a2473fd0c8a718348457/libyul/ObjectParser.cpp#L50>
    #[instrument(level = "debug", skip_all)]
    pub fn parse_yul_file_object(&mut self) -> PResult<'sess, Object<'ast>> {
        self.in_pure_yul(|this| {
            let docs = this.parse_doc_comments();
            let object = if this.check_keyword(sym::object) {
                this.parse_yul_object(docs)
            } else {
                let lo = this.token.span;
                this.parse_yul_block().map(|code| {
                    let span = lo.to(this.prev_token.span);
                    let name = StrLit { span, value: sym::object };
                    let code = CodeBlock { span, code };
                    Object {
                        docs,
                        span,
                        name,
                        code,
                        children: Box::default(),
                        data: Box::default(),
                    }
                })
            }?;
            this.expect(TokenKind::Eof)?;
            Ok(object)
        })
    }

    /// Parses a Yul object.
    ///
    /// Reference: <https://docs.soliditylang.org/en/latest/yul.html#specification-of-yul-object>
    pub fn parse_yul_object(&mut self, docs: DocComments<'ast>) -> PResult<'sess, Object<'ast>> {
        let lo = self.token.span;
        self.expect_keyword(sym::object)?;
        let name = self.parse_str_lit()?;

        self.expect(TokenKind::OpenDelim(Delimiter::Brace))?;
        let code = self.parse_yul_code()?;
        let mut children = Vec::new();
        let mut data = Vec::new();
        loop {
            let docs = self.parse_doc_comments();
            if self.check_keyword(sym::object) {
                children.push(self.parse_yul_object(docs)?);
            } else if self.check_keyword(sym::data) {
                data.push(self.parse_yul_data()?);
            } else {
                break;
            }
        }
        self.expect(TokenKind::CloseDelim(Delimiter::Brace))?;

        let span = lo.to(self.prev_token.span);
        let children = self.alloc_vec(children);
        let data = self.alloc_vec(data);
        Ok(Object { docs, span, name, code, children, data })
    }

    /// Parses a Yul code block.
    fn parse_yul_code(&mut self) -> PResult<'sess, CodeBlock<'ast>> {
        let lo = self.token.span;
        self.expect_keyword(sym::code)?;
        let code = self.parse_yul_block()?;
        let span = lo.to(self.prev_token.span);
        Ok(CodeBlock { span, code })
    }

    /// Parses a Yul data segment.
    fn parse_yul_data(&mut self) -> PResult<'sess, Data<'ast>> {
        let lo = self.token.span;
        self.expect_keyword(sym::data)?;
        let name = self.parse_str_lit()?;
        let data = self.parse_yul_lit()?;
        if !matches!(data.kind, LitKind::Str(StrKind::Str | StrKind::Hex, ..)) {
            let msg = "only string and hex string literals are allowed in `data` segments";
            return Err(self.dcx().err_at(data.span, msg));
        }
        let span = lo.to(self.prev_token.span);
        Ok(Data { span, name, data })
    }

    fn parse_yul_lit(&mut self) -> PResult<'sess, Lit<'ast>> {
        let (mut lit, subdenomination) = self.parse_lit(false)?;
        assert!(subdenomination.is_none());
        // Yul numbers are integers; see PARSE-005.
        if let LitKind::Rational(..) = lit.kind {
            let guar =
                self.dcx().emit_err_code(lit.span, error_code!(4828), "invalid number literal");
            lit.kind = LitKind::Err(guar);
        }
        Ok(lit)
    }

    /// Parses a Yul statement.
    pub fn parse_yul_stmt(&mut self) -> PResult<'sess, Stmt<'ast>> {
        self.in_yul(Self::parse_yul_stmt_unchecked)
    }

    /// Parses a Yul statement, without setting `in_yul`.
    pub fn parse_yul_stmt_unchecked(&mut self) -> PResult<'sess, Stmt<'ast>> {
        self.with_recursion_limit("Yul statement", |this| {
            let docs = this.parse_doc_comments();
            this.parse_spanned(Self::parse_yul_stmt_kind).map(|(span, kind)| Stmt {
                docs,
                span,
                kind,
            })
        })
    }

    /// Parses a Yul block.
    pub fn parse_yul_block(&mut self) -> PResult<'sess, Block<'ast>> {
        self.in_yul(Self::parse_yul_block_unchecked)
    }

    /// Parses a Yul block, without setting `in_yul`.
    pub fn parse_yul_block_unchecked(&mut self) -> PResult<'sess, Block<'ast>> {
        let lo = self.token.span;
        self.parse_block_seq(|this| &mut this.yul_stmts, Self::parse_yul_stmt_unchecked).map(
            |stmts| {
                let span = lo.to(self.prev_token.span);
                Block { span, stmts }
            },
        )
    }

    /// Parses a Yul statement kind.
    fn parse_yul_stmt_kind(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        if self.eat_keyword(kw::Let) {
            self.parse_yul_stmt_var_decl()
        } else if self.eat_keyword(kw::Function) {
            self.parse_yul_function()
        } else if self.check(TokenKind::OpenDelim(Delimiter::Brace)) {
            self.parse_yul_block_unchecked().map(StmtKind::Block)
        } else if self.eat_keyword(kw::If) {
            self.parse_yul_stmt_if()
        } else if self.eat_keyword(kw::Switch) {
            self.parse_yul_stmt_switch().map(StmtKind::Switch)
        } else if self.eat_keyword(kw::For) {
            self.parse_yul_stmt_for()
        } else if self.eat_keyword(kw::Break) {
            Ok(StmtKind::Break)
        } else if self.eat_keyword(kw::Continue) {
            Ok(StmtKind::Continue)
        } else if self.eat_keyword(kw::Leave) {
            Ok(StmtKind::Leave)
        } else if self.check_ident() {
            self.parse_yul_stmt_path()
        } else {
            self.unexpected()
        }
    }

    /// Parses a Yul call or assignment statement.
    ///
    /// Kept out of line so that its locals take no space in nested blocks.
    #[inline(never)]
    fn parse_yul_stmt_path(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        let lo = self.token.span;
        let path = self.parse_path_any()?;
        if self.check(TokenKind::OpenDelim(Delimiter::Parenthesis)) {
            let name = self.expect_single_ident_path(path);
            let (hi, call) = self.parse_spanned(|this| this.parse_yul_expr_call_with(name))?;
            let span = lo.to(hi);
            Ok(StmtKind::Expr(Expr { span, kind: ExprKind::Call(call) }))
        } else if self.eat(TokenKind::Walrus) {
            self.check_valid_path(&path);
            let expr = self.parse_yul_expr()?;
            Ok(StmtKind::AssignSingle(path, expr))
        } else if self.check(TokenKind::Comma) {
            self.check_valid_path(&path);
            let mut paths = SmallVec::<[_; 4]>::new();
            paths.push(path);
            while self.eat(TokenKind::Comma) {
                paths.push(self.parse_yul_path()?);
            }
            let paths = self.alloc_drain(&mut paths);
            self.expect(TokenKind::Walrus)?;
            let expr = self.parse_yul_expr()?;
            let ExprKind::Call(_expr) = &expr.kind else {
                let msg = "only function calls are allowed in multi-assignment";
                return Err(self.dcx().err_at(expr.span, msg));
            };
            Ok(StmtKind::AssignMulti(paths, expr))
        } else {
            self.unexpected()
        }
    }

    /// Parses a Yul variable declaration.
    ///
    /// Kept out of line so that its locals take no space in nested blocks.
    #[inline(never)]
    fn parse_yul_stmt_var_decl(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        let mut idents = SmallVec::<[_; 8]>::new();
        loop {
            idents.push(self.parse_ident()?);
            if !self.eat(TokenKind::Comma) {
                break;
            }
        }
        let idents = self.alloc_drain(&mut idents);
        let expr = if self.eat(TokenKind::Walrus) { Some(self.parse_yul_expr()?) } else { None };
        Ok(StmtKind::VarDecl(idents, expr))
    }

    /// Parses a Yul function definition.
    ///
    /// Kept out of line so that its locals take no space in other statements.
    #[inline(never)]
    fn parse_yul_function(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        let name = self.parse_ident()?;
        let parameters = self.parse_paren_comma_seq(true, Self::parse_ident)?;
        let returns = if self.eat(TokenKind::Arrow) {
            self.parse_nodelim_comma_seq(
                TokenKind::OpenDelim(Delimiter::Brace),
                false,
                Self::parse_ident,
            )?
        } else {
            Default::default()
        };
        let body = self.parse_yul_block_unchecked()?;
        Ok(StmtKind::FunctionDef(Function { name, parameters, returns, body }))
    }

    /// Parses a Yul if statement.
    fn parse_yul_stmt_if(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        let cond = self.parse_yul_expr()?;
        let body = self.parse_yul_block_unchecked()?;
        Ok(StmtKind::If(cond, body))
    }

    /// Parses a Yul switch statement.
    ///
    /// Kept out of line so that its locals take no space in other statements.
    #[inline(never)]
    fn parse_yul_stmt_switch(&mut self) -> PResult<'sess, StmtSwitch<'ast>> {
        let lo = self.prev_token.span;
        let selector = self.parse_yul_expr()?;
        let mut cases = Vec::new();
        let mut has_cases = false;
        let mut has_default = false;
        // A single call site, so that only one case is kept on the stack.
        while !has_default {
            let kw = if self.check_keyword(kw::Case) {
                has_cases = true;
                kw::Case
            } else if self.check_keyword(kw::Default) {
                has_default = true;
                kw::Default
            } else {
                break;
            };
            self.parse_yul_stmt_switch_case(kw, &mut cases)?;
        }
        if !has_cases {
            let span = lo.to(self.prev_token.span);
            if !has_default {
                self.dcx().emit_err(span, "`switch` statement has no cases");
            } else {
                self.dcx().emit_warn_code(
                    span,
                    error_code!(9592),
                    "`switch` statement has only a default case",
                );
            }
        }
        let cases = self.alloc_vec(cases);
        Ok(StmtSwitch { selector, cases })
    }

    fn parse_yul_stmt_switch_case(
        &mut self,
        kw: Symbol,
        cases: &mut Vec<StmtSwitchCase<'ast>>,
    ) -> PResult<'sess, ()> {
        let (span, ()) = self.parse_spanned(|this| {
            this.parse_yul_stmt_switch_case_head(kw, cases)?;
            let body = this.parse_yul_block_unchecked()?;
            cases.last_mut().unwrap().body = body;
            Ok(())
        })?;
        cases.last_mut().unwrap().span = span;
        Ok(())
    }

    /// Parses the keyword and literal of a Yul switch case, and pushes the case with an empty body.
    ///
    /// Kept out of line so that the literal is not kept on the stack while parsing the body.
    #[inline(never)]
    fn parse_yul_stmt_switch_case_head(
        &mut self,
        kw: Symbol,
        cases: &mut Vec<StmtSwitchCase<'ast>>,
    ) -> PResult<'sess, ()> {
        debug_assert!(self.token.is_keyword(kw));
        let lo = self.token.span;
        self.bump();
        let constant = if kw == kw::Case {
            let lit = self.parse_yul_lit()?;
            self.expect_no_subdenomination();
            Some(lit)
        } else {
            None
        };
        let body = Block { span: lo, stmts: Default::default() };
        cases.push(StmtSwitchCase { span: lo, constant, body });
        Ok(())
    }

    /// Parses a Yul for statement.
    ///
    /// Kept out of line so that its locals take no space in other statements.
    #[inline(never)]
    fn parse_yul_stmt_for(&mut self) -> PResult<'sess, StmtKind<'ast>> {
        let init = self.parse_yul_block_unchecked()?;
        let cond = self.parse_yul_expr()?;
        let step = self.parse_yul_block_unchecked()?;
        let body = self.parse_yul_block_unchecked()?;
        Ok(StmtKind::For(self.alloc(StmtFor { init, cond, step, body })))
    }

    /// Parses a Yul expression.
    fn parse_yul_expr(&mut self) -> PResult<'sess, Expr<'ast>> {
        self.parse_spanned(Self::parse_yul_expr_kind).map(|(span, kind)| Expr { span, kind })
    }

    /// Parses a Yul expression kind.
    fn parse_yul_expr_kind(&mut self) -> PResult<'sess, ExprKind<'ast>> {
        if self.check_lit() {
            self.parse_yul_lit_expr()
        } else if self.check_path() {
            let path = self.parse_path_any()?;
            if self.token.is_open_delim(Delimiter::Parenthesis) {
                // Paths are not allowed in call expressions, but Solc parses them anyway.
                let ident = self.expect_single_ident_path(path);
                self.parse_yul_expr_call_with(ident).map(ExprKind::Call)
            } else if path.segments().len() == 1 && self.is_reserved_yul_expr_ident(*path.first()) {
                let name = path.first();
                self.dcx()
                    .emit_err(path.span(), format!("builtin function `{name}` must be called"));
                Ok(ExprKind::Path(path))
            } else {
                self.check_valid_path(&path);
                Ok(ExprKind::Path(path))
            }
        } else {
            self.unexpected()
        }
    }

    /// Parses a Yul literal expression.
    ///
    /// Kept out of line so that the literal takes no space in other expressions.
    #[inline(never)]
    fn parse_yul_lit_expr(&mut self) -> PResult<'sess, ExprKind<'ast>> {
        // NOTE: We can't `expect_no_subdenomination` because they're valid variable names.
        self.parse_yul_lit().map(|lit| ExprKind::Lit(self.alloc(lit)))
    }

    /// Parses a Yul function call expression with the given name.
    fn parse_yul_expr_call_with(&mut self, name: Ident) -> PResult<'sess, ExprCall<'ast>> {
        if !name.is_yul_builtin() && self.is_reserved_yul_ident(name) {
            self.expected_ident_found_other(name.into(), false).unwrap_err().emit();
        }
        let arguments = self.parse_paren_comma_seq(true, Self::parse_yul_expr)?;
        Ok(ExprCall { name, arguments })
    }

    /// Expects a single identifier path and returns the identifier.
    #[track_caller]
    fn expect_single_ident_path(&mut self, path: AstPath<'_>) -> Ident {
        if path.segments().len() > 1 {
            self.dcx().emit_err(path.span(), "fully-qualified paths aren't allowed here");
        }
        *path.last()
    }

    fn parse_yul_path(&mut self) -> PResult<'sess, AstPath<'ast>> {
        let path = self.parse_path_any()?;
        self.check_valid_path(&path);
        Ok(path)
    }

    // https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.yulPath
    #[track_caller]
    fn check_valid_path(&mut self, path: &PathSlice) {
        // We allow EVM builtins in any position if multiple segments are present:
        // https://github.com/argotorg/solidity/issues/16054
        let first = *path.first();
        if first.is_yul_keyword()
            || (path.segments().len() == 1 && self.is_reserved_yul_expr_ident(first))
        {
            self.expected_ident_found_other(first.into(), false).unwrap_err().emit();
        }
        for &ident in &path.segments()[1..] {
            if ident.is_yul_keyword() {
                self.expected_ident_found_other(ident.into(), false).unwrap_err().emit();
            }
        }
    }

    fn is_reserved_yul_expr_ident(&self, ident: Ident) -> bool {
        self.is_reserved_yul_ident(ident)
            && !(ident.name == kw::Difficulty && self.sess.opts.evm_version.has_prev_randao())
    }
}