solar_parse/parser/
yul.rs

1use super::SeqSep;
2use crate::{PResult, Parser};
3use smallvec::SmallVec;
4use solar_ast::{
5    AstPath, Box, DocComments, Lit, LitKind, PathSlice, StrKind, StrLit, token::*, yul::*,
6};
7use solar_interface::{Ident, error_code, kw, sym};
8
9impl<'sess, 'ast> Parser<'sess, 'ast> {
10    /// Parses a Yul object or plain block.
11    ///
12    /// The plain block gets returned as a Yul object named "object", with a single `code` block.
13    /// See: <https://github.com/ethereum/solidity/blob/eff410eb746f202fe756a2473fd0c8a718348457/libyul/ObjectParser.cpp#L50>
14    #[instrument(level = "debug", skip_all)]
15    pub fn parse_yul_file_object(&mut self) -> PResult<'sess, Object<'ast>> {
16        let docs = self.parse_doc_comments();
17        let object = if self.check_keyword(sym::object) {
18            self.parse_yul_object(docs)
19        } else {
20            let lo = self.token.span;
21            self.parse_yul_block().map(|code| {
22                let span = lo.to(self.prev_token.span);
23                let name = StrLit { span, value: sym::object };
24                let code = CodeBlock { span, code };
25                Object { docs, span, name, code, children: Box::default(), data: Box::default() }
26            })
27        }?;
28        self.expect(TokenKind::Eof)?;
29        Ok(object)
30    }
31
32    /// Parses a Yul object.
33    ///
34    /// Reference: <https://docs.soliditylang.org/en/latest/yul.html#specification-of-yul-object>
35    pub fn parse_yul_object(&mut self, docs: DocComments<'ast>) -> PResult<'sess, Object<'ast>> {
36        let lo = self.token.span;
37        self.expect_keyword(sym::object)?;
38        let name = self.parse_str_lit()?;
39
40        self.expect(TokenKind::OpenDelim(Delimiter::Brace))?;
41        let code = self.parse_yul_code()?;
42        let mut children = Vec::new();
43        let mut data = Vec::new();
44        loop {
45            let docs = self.parse_doc_comments();
46            if self.check_keyword(sym::object) {
47                children.push(self.parse_yul_object(docs)?);
48            } else if self.check_keyword(sym::data) {
49                data.push(self.parse_yul_data()?);
50            } else {
51                break;
52            }
53        }
54        self.expect(TokenKind::CloseDelim(Delimiter::Brace))?;
55
56        let span = lo.to(self.prev_token.span);
57        let children = self.alloc_vec(children);
58        let data = self.alloc_vec(data);
59        Ok(Object { docs, span, name, code, children, data })
60    }
61
62    /// Parses a Yul code block.
63    fn parse_yul_code(&mut self) -> PResult<'sess, CodeBlock<'ast>> {
64        let lo = self.token.span;
65        self.expect_keyword(sym::code)?;
66        let code = self.parse_yul_block()?;
67        let span = lo.to(self.prev_token.span);
68        Ok(CodeBlock { span, code })
69    }
70
71    /// Parses a Yul data segment.
72    fn parse_yul_data(&mut self) -> PResult<'sess, Data<'ast>> {
73        let lo = self.token.span;
74        self.expect_keyword(sym::data)?;
75        let name = self.parse_str_lit()?;
76        let data = self.parse_yul_lit()?;
77        if !matches!(data.kind, LitKind::Str(StrKind::Str | StrKind::Hex, ..)) {
78            let msg = "only string and hex string literals are allowed in `data` segments";
79            return Err(self.dcx().err(msg).span(data.span));
80        }
81        let span = lo.to(self.prev_token.span);
82        Ok(Data { span, name, data })
83    }
84
85    fn parse_yul_lit(&mut self) -> PResult<'sess, Lit<'ast>> {
86        let (lit, subdenomination) = self.parse_lit(false)?;
87        assert!(subdenomination.is_none());
88        Ok(lit)
89    }
90
91    /// Parses a Yul statement.
92    pub fn parse_yul_stmt(&mut self) -> PResult<'sess, Stmt<'ast>> {
93        self.in_yul(Self::parse_yul_stmt)
94    }
95
96    /// Parses a Yul statement, without setting `in_yul`.
97    pub fn parse_yul_stmt_unchecked(&mut self) -> PResult<'sess, Stmt<'ast>> {
98        let docs = self.parse_doc_comments();
99        self.parse_spanned(Self::parse_yul_stmt_kind).map(|(span, kind)| Stmt { docs, span, kind })
100    }
101
102    /// Parses a Yul block.
103    pub fn parse_yul_block(&mut self) -> PResult<'sess, Block<'ast>> {
104        self.in_yul(Self::parse_yul_block_unchecked)
105    }
106
107    /// Parses a Yul block, without setting `in_yul`.
108    pub fn parse_yul_block_unchecked(&mut self) -> PResult<'sess, Block<'ast>> {
109        let lo = self.token.span;
110        self.parse_delim_seq(Delimiter::Brace, SeqSep::none(), true, Self::parse_yul_stmt_unchecked)
111            .map(|stmts| {
112                let span = lo.to(self.prev_token.span);
113                Block { span, stmts }
114            })
115    }
116
117    /// Parses a Yul statement kind.
118    fn parse_yul_stmt_kind(&mut self) -> PResult<'sess, StmtKind<'ast>> {
119        if self.eat_keyword(kw::Let) {
120            self.parse_yul_stmt_var_decl()
121        } else if self.eat_keyword(kw::Function) {
122            self.parse_yul_function()
123        } else if self.check(TokenKind::OpenDelim(Delimiter::Brace)) {
124            self.parse_yul_block_unchecked().map(StmtKind::Block)
125        } else if self.eat_keyword(kw::If) {
126            self.parse_yul_stmt_if()
127        } else if self.eat_keyword(kw::Switch) {
128            self.parse_yul_stmt_switch().map(StmtKind::Switch)
129        } else if self.eat_keyword(kw::For) {
130            self.parse_yul_stmt_for()
131        } else if self.eat_keyword(kw::Break) {
132            Ok(StmtKind::Break)
133        } else if self.eat_keyword(kw::Continue) {
134            Ok(StmtKind::Continue)
135        } else if self.eat_keyword(kw::Leave) {
136            Ok(StmtKind::Leave)
137        } else if self.check_ident() {
138            let path = self.parse_path_any()?;
139            if self.check(TokenKind::OpenDelim(Delimiter::Parenthesis)) {
140                let name = self.expect_single_ident_path(path);
141                self.parse_yul_expr_call_with(name).map(StmtKind::Expr)
142            } else if self.eat(TokenKind::Walrus) {
143                self.check_valid_path(path);
144                let expr = self.parse_yul_expr()?;
145                Ok(StmtKind::AssignSingle(path, expr))
146            } else if self.check(TokenKind::Comma) {
147                self.check_valid_path(path);
148                let mut paths = SmallVec::<[_; 4]>::new();
149                paths.push(path);
150                while self.eat(TokenKind::Comma) {
151                    paths.push(self.parse_yul_path()?);
152                }
153                let paths = self.alloc_smallvec(paths);
154                self.expect(TokenKind::Walrus)?;
155                let expr = self.parse_yul_expr()?;
156                let ExprKind::Call(expr) = expr.kind else {
157                    let msg = "only function calls are allowed in multi-assignment";
158                    return Err(self.dcx().err(msg).span(expr.span));
159                };
160                Ok(StmtKind::AssignMulti(paths, expr))
161            } else {
162                self.unexpected()
163            }
164        } else {
165            self.unexpected()
166        }
167    }
168
169    /// Parses a Yul variable declaration.
170    fn parse_yul_stmt_var_decl(&mut self) -> PResult<'sess, StmtKind<'ast>> {
171        let mut idents = SmallVec::<[_; 8]>::new();
172        loop {
173            idents.push(self.parse_ident()?);
174            if !self.eat(TokenKind::Comma) {
175                break;
176            }
177        }
178        let idents = self.alloc_smallvec(idents);
179        let expr = if self.eat(TokenKind::Walrus) { Some(self.parse_yul_expr()?) } else { None };
180        Ok(StmtKind::VarDecl(idents, expr))
181    }
182
183    /// Parses a Yul function definition.
184    fn parse_yul_function(&mut self) -> PResult<'sess, StmtKind<'ast>> {
185        let name = self.parse_ident()?;
186        let parameters = self.parse_paren_comma_seq(true, Self::parse_ident)?;
187        let returns = if self.eat(TokenKind::Arrow) {
188            self.parse_nodelim_comma_seq(
189                TokenKind::OpenDelim(Delimiter::Brace),
190                false,
191                Self::parse_ident,
192            )?
193        } else {
194            Default::default()
195        };
196        let body = self.parse_yul_block_unchecked()?;
197        Ok(StmtKind::FunctionDef(Function { name, parameters, returns, body }))
198    }
199
200    /// Parses a Yul if statement.
201    fn parse_yul_stmt_if(&mut self) -> PResult<'sess, StmtKind<'ast>> {
202        let cond = self.parse_yul_expr()?;
203        let body = self.parse_yul_block_unchecked()?;
204        Ok(StmtKind::If(cond, body))
205    }
206
207    /// Parses a Yul switch statement.
208    fn parse_yul_stmt_switch(&mut self) -> PResult<'sess, StmtSwitch<'ast>> {
209        let lo = self.prev_token.span;
210        let selector = self.parse_yul_expr()?;
211        let mut branches = Vec::new();
212        while self.eat_keyword(kw::Case) {
213            let constant = self.parse_yul_lit()?;
214            self.expect_no_subdenomination();
215            let body = self.parse_yul_block_unchecked()?;
216            branches.push(StmtSwitchCase { constant, body });
217        }
218        let branches = self.alloc_vec(branches);
219        let default_case = if self.eat_keyword(kw::Default) {
220            Some(self.parse_yul_block_unchecked()?)
221        } else {
222            None
223        };
224        if branches.is_empty() {
225            let span = lo.to(self.prev_token.span);
226            if default_case.is_none() {
227                self.dcx().err("`switch` statement has no cases").span(span).emit();
228            } else {
229                self.dcx()
230                    .warn("`switch` statement has only a default case")
231                    .span(span)
232                    .code(error_code!(9592))
233                    .emit();
234            }
235        }
236        Ok(StmtSwitch { selector, branches, default_case })
237    }
238
239    /// Parses a Yul for statement.
240    fn parse_yul_stmt_for(&mut self) -> PResult<'sess, StmtKind<'ast>> {
241        let init = self.parse_yul_block_unchecked()?;
242        let cond = self.parse_yul_expr()?;
243        let step = self.parse_yul_block_unchecked()?;
244        let body = self.parse_yul_block_unchecked()?;
245        Ok(StmtKind::For { init, cond, step, body })
246    }
247
248    /// Parses a Yul expression.
249    fn parse_yul_expr(&mut self) -> PResult<'sess, Expr<'ast>> {
250        self.parse_spanned(Self::parse_yul_expr_kind).map(|(span, kind)| Expr { span, kind })
251    }
252
253    /// Parses a Yul expression kind.
254    fn parse_yul_expr_kind(&mut self) -> PResult<'sess, ExprKind<'ast>> {
255        if self.check_lit() {
256            // NOTE: We can't `expect_no_subdenomination` because they're valid variable names.
257            self.parse_yul_lit().map(|lit| ExprKind::Lit(self.alloc(lit)))
258        } else if self.check_path() {
259            let path = self.parse_path_any()?;
260            if self.token.is_open_delim(Delimiter::Parenthesis) {
261                // Paths are not allowed in call expressions, but Solc parses them anyway.
262                let ident = self.expect_single_ident_path(path);
263                self.parse_yul_expr_call_with(ident).map(ExprKind::Call)
264            } else {
265                self.check_valid_path(path);
266                Ok(ExprKind::Path(path))
267            }
268        } else {
269            self.unexpected()
270        }
271    }
272
273    /// Parses a Yul function call expression with the given name.
274    fn parse_yul_expr_call_with(&mut self, name: Ident) -> PResult<'sess, ExprCall<'ast>> {
275        if !name.is_yul_evm_builtin() && name.is_reserved(true) {
276            self.expected_ident_found_other(name.into(), false).unwrap_err().emit();
277        }
278        let arguments = self.parse_paren_comma_seq(true, Self::parse_yul_expr)?;
279        Ok(ExprCall { name, arguments })
280    }
281
282    /// Expects a single identifier path and returns the identifier.
283    #[track_caller]
284    fn expect_single_ident_path(&mut self, path: AstPath<'_>) -> Ident {
285        if path.segments().len() > 1 {
286            self.dcx().err("fully-qualified paths aren't allowed here").span(path.span()).emit();
287        }
288        *path.last()
289    }
290
291    fn parse_yul_path(&mut self) -> PResult<'sess, AstPath<'ast>> {
292        let path = self.parse_path_any()?;
293        self.check_valid_path(path);
294        Ok(path)
295    }
296
297    // https://docs.soliditylang.org/en/latest/grammar.html#a4.SolidityParser.yulPath
298    #[track_caller]
299    fn check_valid_path(&mut self, path: &PathSlice) {
300        // We allow EVM builtins in any position if multiple segments are present:
301        // https://github.com/ethereum/solidity/issues/16054
302        let first = *path.first();
303        if first.is_yul_keyword() || (path.segments().len() == 1 && first.is_yul_evm_builtin()) {
304            self.expected_ident_found_other(first.into(), false).unwrap_err().emit();
305        }
306        for &ident in &path.segments()[1..] {
307            if ident.is_yul_keyword() {
308                self.expected_ident_found_other(ident.into(), false).unwrap_err().emit();
309            }
310        }
311    }
312}