1use crate::{PResult, Parser};
2use smallvec::SmallVec;
3use solar_ast::{
4 AstPath, Box, DocComments, Lit, LitKind, PathSlice, StrKind, StrLit, Symbol, token::*, yul::*,
5};
6use solar_interface::{Ident, error_code, kw, sym};
7
8impl<'sess, 'ast, 'cb> Parser<'sess, 'ast, 'cb> {
9 #[instrument(level = "debug", skip_all)]
14 pub fn parse_yul_file_object(&mut self) -> PResult<'sess, Object<'ast>> {
15 self.in_pure_yul(|this| {
16 let docs = this.parse_doc_comments();
17 let object = if this.check_keyword(sym::object) {
18 this.parse_yul_object(docs)
19 } else {
20 let lo = this.token.span;
21 this.parse_yul_block().map(|code| {
22 let span = lo.to(this.prev_token.span);
23 let name = StrLit { span, value: sym::object };
24 let code = CodeBlock { span, code };
25 Object {
26 docs,
27 span,
28 name,
29 code,
30 children: Box::default(),
31 data: Box::default(),
32 }
33 })
34 }?;
35 this.expect(TokenKind::Eof)?;
36 Ok(object)
37 })
38 }
39
40 pub fn parse_yul_object(&mut self, docs: DocComments<'ast>) -> PResult<'sess, Object<'ast>> {
44 let lo = self.token.span;
45 self.expect_keyword(sym::object)?;
46 let name = self.parse_str_lit()?;
47
48 self.expect(TokenKind::OpenDelim(Delimiter::Brace))?;
49 let code = self.parse_yul_code()?;
50 let mut children = Vec::new();
51 let mut data = Vec::new();
52 loop {
53 let docs = self.parse_doc_comments();
54 if self.check_keyword(sym::object) {
55 children.push(self.parse_yul_object(docs)?);
56 } else if self.check_keyword(sym::data) {
57 data.push(self.parse_yul_data()?);
58 } else {
59 break;
60 }
61 }
62 self.expect(TokenKind::CloseDelim(Delimiter::Brace))?;
63
64 let span = lo.to(self.prev_token.span);
65 let children = self.alloc_vec(children);
66 let data = self.alloc_vec(data);
67 Ok(Object { docs, span, name, code, children, data })
68 }
69
70 fn parse_yul_code(&mut self) -> PResult<'sess, CodeBlock<'ast>> {
72 let lo = self.token.span;
73 self.expect_keyword(sym::code)?;
74 let code = self.parse_yul_block()?;
75 let span = lo.to(self.prev_token.span);
76 Ok(CodeBlock { span, code })
77 }
78
79 fn parse_yul_data(&mut self) -> PResult<'sess, Data<'ast>> {
81 let lo = self.token.span;
82 self.expect_keyword(sym::data)?;
83 let name = self.parse_str_lit()?;
84 let data = self.parse_yul_lit()?;
85 if !matches!(data.kind, LitKind::Str(StrKind::Str | StrKind::Hex, ..)) {
86 let msg = "only string and hex string literals are allowed in `data` segments";
87 return Err(self.dcx().err(msg).span(data.span));
88 }
89 let span = lo.to(self.prev_token.span);
90 Ok(Data { span, name, data })
91 }
92
93 fn parse_yul_lit(&mut self) -> PResult<'sess, Lit<'ast>> {
94 let (mut lit, subdenomination) = self.parse_lit(false)?;
95 assert!(subdenomination.is_none());
96 if let LitKind::Rational(..) = lit.kind {
98 let guar = self
99 .dcx()
100 .err("invalid number literal")
101 .code(error_code!(4828))
102 .span(lit.span)
103 .emit();
104 lit.kind = LitKind::Err(guar);
105 }
106 Ok(lit)
107 }
108
109 pub fn parse_yul_stmt(&mut self) -> PResult<'sess, Stmt<'ast>> {
111 self.in_yul(Self::parse_yul_stmt_unchecked)
112 }
113
114 pub fn parse_yul_stmt_unchecked(&mut self) -> PResult<'sess, Stmt<'ast>> {
116 self.with_recursion_limit("Yul statement", |this| {
117 let docs = this.parse_doc_comments();
118 this.parse_spanned(Self::parse_yul_stmt_kind).map(|(span, kind)| Stmt {
119 docs,
120 span,
121 kind,
122 })
123 })
124 }
125
126 pub fn parse_yul_block(&mut self) -> PResult<'sess, Block<'ast>> {
128 self.in_yul(Self::parse_yul_block_unchecked)
129 }
130
131 pub fn parse_yul_block_unchecked(&mut self) -> PResult<'sess, Block<'ast>> {
133 let lo = self.token.span;
134 self.parse_block_seq(|this| &mut this.yul_stmts, Self::parse_yul_stmt_unchecked).map(
135 |stmts| {
136 let span = lo.to(self.prev_token.span);
137 Block { span, stmts }
138 },
139 )
140 }
141
142 fn parse_yul_stmt_kind(&mut self) -> PResult<'sess, StmtKind<'ast>> {
144 if self.eat_keyword(kw::Let) {
145 self.parse_yul_stmt_var_decl()
146 } else if self.eat_keyword(kw::Function) {
147 self.parse_yul_function()
148 } else if self.check(TokenKind::OpenDelim(Delimiter::Brace)) {
149 self.parse_yul_block_unchecked().map(StmtKind::Block)
150 } else if self.eat_keyword(kw::If) {
151 self.parse_yul_stmt_if()
152 } else if self.eat_keyword(kw::Switch) {
153 self.parse_yul_stmt_switch().map(StmtKind::Switch)
154 } else if self.eat_keyword(kw::For) {
155 self.parse_yul_stmt_for()
156 } else if self.eat_keyword(kw::Break) {
157 Ok(StmtKind::Break)
158 } else if self.eat_keyword(kw::Continue) {
159 Ok(StmtKind::Continue)
160 } else if self.eat_keyword(kw::Leave) {
161 Ok(StmtKind::Leave)
162 } else if self.check_ident() {
163 self.parse_yul_stmt_path()
164 } else {
165 self.unexpected()
166 }
167 }
168
169 #[inline(never)]
173 fn parse_yul_stmt_path(&mut self) -> PResult<'sess, StmtKind<'ast>> {
174 let lo = self.token.span;
175 let path = self.parse_path_any()?;
176 if self.check(TokenKind::OpenDelim(Delimiter::Parenthesis)) {
177 let name = self.expect_single_ident_path(path);
178 let (hi, call) = self.parse_spanned(|this| this.parse_yul_expr_call_with(name))?;
179 let span = lo.to(hi);
180 Ok(StmtKind::Expr(Expr { span, kind: ExprKind::Call(call) }))
181 } else if self.eat(TokenKind::Walrus) {
182 self.check_valid_path(&path);
183 let expr = self.parse_yul_expr()?;
184 Ok(StmtKind::AssignSingle(path, expr))
185 } else if self.check(TokenKind::Comma) {
186 self.check_valid_path(&path);
187 let mut paths = SmallVec::<[_; 4]>::new();
188 paths.push(path);
189 while self.eat(TokenKind::Comma) {
190 paths.push(self.parse_yul_path()?);
191 }
192 let paths = self.alloc_drain(&mut paths);
193 self.expect(TokenKind::Walrus)?;
194 let expr = self.parse_yul_expr()?;
195 let ExprKind::Call(_expr) = &expr.kind else {
196 let msg = "only function calls are allowed in multi-assignment";
197 return Err(self.dcx().err(msg).span(expr.span));
198 };
199 Ok(StmtKind::AssignMulti(paths, expr))
200 } else {
201 self.unexpected()
202 }
203 }
204
205 #[inline(never)]
209 fn parse_yul_stmt_var_decl(&mut self) -> PResult<'sess, StmtKind<'ast>> {
210 let mut idents = SmallVec::<[_; 8]>::new();
211 loop {
212 idents.push(self.parse_ident()?);
213 if !self.eat(TokenKind::Comma) {
214 break;
215 }
216 }
217 let idents = self.alloc_drain(&mut idents);
218 let expr = if self.eat(TokenKind::Walrus) { Some(self.parse_yul_expr()?) } else { None };
219 Ok(StmtKind::VarDecl(idents, expr))
220 }
221
222 #[inline(never)]
226 fn parse_yul_function(&mut self) -> PResult<'sess, StmtKind<'ast>> {
227 let name = self.parse_ident()?;
228 let parameters = self.parse_paren_comma_seq(true, Self::parse_ident)?;
229 let returns = if self.eat(TokenKind::Arrow) {
230 self.parse_nodelim_comma_seq(
231 TokenKind::OpenDelim(Delimiter::Brace),
232 false,
233 Self::parse_ident,
234 )?
235 } else {
236 Default::default()
237 };
238 let body = self.parse_yul_block_unchecked()?;
239 Ok(StmtKind::FunctionDef(Function { name, parameters, returns, body }))
240 }
241
242 fn parse_yul_stmt_if(&mut self) -> PResult<'sess, StmtKind<'ast>> {
244 let cond = self.parse_yul_expr()?;
245 let body = self.parse_yul_block_unchecked()?;
246 Ok(StmtKind::If(cond, body))
247 }
248
249 #[inline(never)]
253 fn parse_yul_stmt_switch(&mut self) -> PResult<'sess, StmtSwitch<'ast>> {
254 let lo = self.prev_token.span;
255 let selector = self.parse_yul_expr()?;
256 let mut cases = Vec::new();
257 let mut has_cases = false;
258 let mut has_default = false;
259 while !has_default {
261 let kw = if self.check_keyword(kw::Case) {
262 has_cases = true;
263 kw::Case
264 } else if self.check_keyword(kw::Default) {
265 has_default = true;
266 kw::Default
267 } else {
268 break;
269 };
270 self.parse_yul_stmt_switch_case(kw, &mut cases)?;
271 }
272 if !has_cases {
273 let span = lo.to(self.prev_token.span);
274 if !has_default {
275 self.dcx().emit_err(span, "`switch` statement has no cases");
276 } else {
277 self.dcx()
278 .warn("`switch` statement has only a default case")
279 .span(span)
280 .code(error_code!(9592))
281 .emit();
282 }
283 }
284 let cases = self.alloc_vec(cases);
285 Ok(StmtSwitch { selector, cases })
286 }
287
288 fn parse_yul_stmt_switch_case(
289 &mut self,
290 kw: Symbol,
291 cases: &mut Vec<StmtSwitchCase<'ast>>,
292 ) -> PResult<'sess, ()> {
293 let (span, ()) = self.parse_spanned(|this| {
294 this.parse_yul_stmt_switch_case_head(kw, cases)?;
295 let body = this.parse_yul_block_unchecked()?;
296 cases.last_mut().unwrap().body = body;
297 Ok(())
298 })?;
299 cases.last_mut().unwrap().span = span;
300 Ok(())
301 }
302
303 #[inline(never)]
307 fn parse_yul_stmt_switch_case_head(
308 &mut self,
309 kw: Symbol,
310 cases: &mut Vec<StmtSwitchCase<'ast>>,
311 ) -> PResult<'sess, ()> {
312 debug_assert!(self.token.is_keyword(kw));
313 let lo = self.token.span;
314 self.bump();
315 let constant = if kw == kw::Case {
316 let lit = self.parse_yul_lit()?;
317 self.expect_no_subdenomination();
318 Some(lit)
319 } else {
320 None
321 };
322 let body = Block { span: lo, stmts: Default::default() };
323 cases.push(StmtSwitchCase { span: lo, constant, body });
324 Ok(())
325 }
326
327 #[inline(never)]
331 fn parse_yul_stmt_for(&mut self) -> PResult<'sess, StmtKind<'ast>> {
332 let init = self.parse_yul_block_unchecked()?;
333 let cond = self.parse_yul_expr()?;
334 let step = self.parse_yul_block_unchecked()?;
335 let body = self.parse_yul_block_unchecked()?;
336 Ok(StmtKind::For(self.alloc(StmtFor { init, cond, step, body })))
337 }
338
339 fn parse_yul_expr(&mut self) -> PResult<'sess, Expr<'ast>> {
341 self.parse_spanned(Self::parse_yul_expr_kind).map(|(span, kind)| Expr { span, kind })
342 }
343
344 fn parse_yul_expr_kind(&mut self) -> PResult<'sess, ExprKind<'ast>> {
346 if self.check_lit() {
347 self.parse_yul_lit_expr()
348 } else if self.check_path() {
349 let path = self.parse_path_any()?;
350 if self.token.is_open_delim(Delimiter::Parenthesis) {
351 let ident = self.expect_single_ident_path(path);
353 self.parse_yul_expr_call_with(ident).map(ExprKind::Call)
354 } else if path.segments().len() == 1 && self.is_reserved_yul_expr_ident(*path.first()) {
355 let name = path.first();
356 self.dcx()
357 .emit_err(path.span(), format!("builtin function `{name}` must be called"));
358 Ok(ExprKind::Path(path))
359 } else {
360 self.check_valid_path(&path);
361 Ok(ExprKind::Path(path))
362 }
363 } else {
364 self.unexpected()
365 }
366 }
367
368 #[inline(never)]
372 fn parse_yul_lit_expr(&mut self) -> PResult<'sess, ExprKind<'ast>> {
373 self.parse_yul_lit().map(|lit| ExprKind::Lit(self.alloc(lit)))
375 }
376
377 fn parse_yul_expr_call_with(&mut self, name: Ident) -> PResult<'sess, ExprCall<'ast>> {
379 if !name.is_yul_builtin() && self.is_reserved_yul_ident(name) {
380 self.expected_ident_found_other(name.into(), false).unwrap_err().emit();
381 }
382 let arguments = self.parse_paren_comma_seq(true, Self::parse_yul_expr)?;
383 Ok(ExprCall { name, arguments })
384 }
385
386 #[track_caller]
388 fn expect_single_ident_path(&mut self, path: AstPath<'_>) -> Ident {
389 if path.segments().len() > 1 {
390 self.dcx().emit_err(path.span(), "fully-qualified paths aren't allowed here");
391 }
392 *path.last()
393 }
394
395 fn parse_yul_path(&mut self) -> PResult<'sess, AstPath<'ast>> {
396 let path = self.parse_path_any()?;
397 self.check_valid_path(&path);
398 Ok(path)
399 }
400
401 #[track_caller]
403 fn check_valid_path(&mut self, path: &PathSlice) {
404 let first = *path.first();
407 if first.is_yul_keyword()
408 || (path.segments().len() == 1 && self.is_reserved_yul_expr_ident(first))
409 {
410 self.expected_ident_found_other(first.into(), false).unwrap_err().emit();
411 }
412 for &ident in &path.segments()[1..] {
413 if ident.is_yul_keyword() {
414 self.expected_ident_found_other(ident.into(), false).unwrap_err().emit();
415 }
416 }
417 }
418
419 fn is_reserved_yul_expr_ident(&self, ident: Ident) -> bool {
420 self.is_reserved_yul_ident(ident)
421 && !(ident.name == kw::Difficulty && self.sess.opts.evm_version.has_prev_randao())
422 }
423}