]>
Commit | Line | Data |
---|---|---|
ba9703b0 | 1 | use super::attr::DEFAULT_INNER_ATTR_FORBIDDEN; |
29967ef6 | 2 | use super::diagnostics::{AttemptLocalParseRecovery, Error}; |
416331ca | 3 | use super::expr::LhsExpr; |
cdc7bbd5 | 4 | use super::pat::RecoverComma; |
dfeec247 | 5 | use super::path::PathStyle; |
6a06907d | 6 | use super::TrailingToken; |
a2a8927a XL |
7 | use super::{ |
8 | AttrWrapper, BlockMode, FnParseMode, ForceCollect, Parser, Restrictions, SemiColonMode, | |
9 | }; | |
6a06907d | 10 | use crate::maybe_whole; |
60c5eb7d | 11 | |
3dfed10e | 12 | use rustc_ast as ast; |
74b04a01 | 13 | use rustc_ast::ptr::P; |
04454e1e | 14 | use rustc_ast::token::{self, Delimiter, TokenKind}; |
74b04a01 | 15 | use rustc_ast::util::classify; |
04454e1e FG |
16 | use rustc_ast::{AttrStyle, AttrVec, Attribute, LocalKind, MacCall, MacCallStmt, MacStmtStyle}; |
17 | use rustc_ast::{Block, BlockCheckMode, Expr, ExprKind, HasAttrs, Local, Stmt}; | |
6a06907d | 18 | use rustc_ast::{StmtKind, DUMMY_NODE_ID}; |
5e7ed085 | 19 | use rustc_errors::{Applicability, DiagnosticBuilder, ErrorGuaranteed, PResult}; |
74b04a01 XL |
20 | use rustc_span::source_map::{BytePos, Span}; |
21 | use rustc_span::symbol::{kw, sym}; | |
416331ca XL |
22 | |
23 | use std::mem; | |
416331ca XL |
24 | |
25 | impl<'a> Parser<'a> { | |
e1599b0c | 26 | /// Parses a statement. This stops just before trailing semicolons on everything but items. |
416331ca | 27 | /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed. |
1b1a35ee | 28 | // Public for rustfmt usage. |
5869c6ff XL |
29 | pub fn parse_stmt(&mut self, force_collect: ForceCollect) -> PResult<'a, Option<Stmt>> { |
30 | Ok(self.parse_stmt_without_recovery(false, force_collect).unwrap_or_else(|mut e| { | |
416331ca XL |
31 | e.emit(); |
32 | self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); | |
33 | None | |
dfeec247 | 34 | })) |
416331ca XL |
35 | } |
36 | ||
5869c6ff XL |
37 | /// If `force_capture` is true, forces collection of tokens regardless of whether |
38 | /// or not we have attributes | |
923072b8 | 39 | pub(crate) fn parse_stmt_without_recovery( |
5869c6ff XL |
40 | &mut self, |
41 | capture_semi: bool, | |
42 | force_collect: ForceCollect, | |
43 | ) -> PResult<'a, Option<Stmt>> { | |
6a06907d | 44 | let attrs = self.parse_outer_attributes()?; |
416331ca XL |
45 | let lo = self.token.span; |
46 | ||
6a06907d XL |
47 | // Don't use `maybe_whole` so that we have precise control |
48 | // over when we bump the parser | |
5e7ed085 FG |
49 | if let token::Interpolated(nt) = &self.token.kind && let token::NtStmt(stmt) = &**nt { |
50 | let mut stmt = stmt.clone(); | |
51 | self.bump(); | |
52 | stmt.visit_attrs(|stmt_attrs| { | |
53 | attrs.prepend_to_nt_inner(stmt_attrs); | |
54 | }); | |
04454e1e | 55 | return Ok(Some(stmt.into_inner())); |
6a06907d | 56 | } |
fc512014 | 57 | |
5869c6ff | 58 | Ok(Some(if self.token.is_keyword(kw::Let) { |
6a06907d | 59 | self.parse_local_mk(lo, attrs, capture_semi, force_collect)? |
5869c6ff | 60 | } else if self.is_kw_followed_by_ident(kw::Mut) { |
cdc7bbd5 | 61 | self.recover_stmt_local(lo, attrs, "missing keyword", "let mut")? |
5869c6ff XL |
62 | } else if self.is_kw_followed_by_ident(kw::Auto) { |
63 | self.bump(); // `auto` | |
64 | let msg = "write `let` instead of `auto` to introduce a new variable"; | |
cdc7bbd5 | 65 | self.recover_stmt_local(lo, attrs, msg, "let")? |
5869c6ff XL |
66 | } else if self.is_kw_followed_by_ident(sym::var) { |
67 | self.bump(); // `var` | |
68 | let msg = "write `let` instead of `var` to introduce a new variable"; | |
cdc7bbd5 | 69 | self.recover_stmt_local(lo, attrs, msg, "let")? |
5869c6ff XL |
70 | } else if self.check_path() && !self.token.is_qpath_start() && !self.is_path_start_item() { |
71 | // We have avoided contextual keywords like `union`, items with `crate` visibility, | |
72 | // or `auto trait` items. We aim to parse an arbitrary path `a::b` but not something | |
73 | // that starts like a path (1 token), but it fact not a path. | |
74 | // Also, we avoid stealing syntax from `parse_item_`. | |
17df50a5 XL |
75 | if force_collect == ForceCollect::Yes { |
76 | self.collect_tokens_no_attrs(|this| this.parse_stmt_path_start(lo, attrs)) | |
77 | } else { | |
78 | self.parse_stmt_path_start(lo, attrs) | |
79 | }? | |
a2a8927a XL |
80 | } else if let Some(item) = self.parse_item_common( |
81 | attrs.clone(), | |
82 | false, | |
83 | true, | |
84 | FnParseMode { req_name: |_| true, req_body: true }, | |
85 | force_collect, | |
86 | )? { | |
5869c6ff XL |
87 | // FIXME: Bad copy of attrs |
88 | self.mk_stmt(lo.to(item.span), StmtKind::Item(P(item))) | |
89 | } else if self.eat(&token::Semi) { | |
90 | // Do not attempt to parse an expression if we're done here. | |
6a06907d | 91 | self.error_outer_attrs(&attrs.take_for_recovery()); |
5869c6ff | 92 | self.mk_stmt(lo, StmtKind::Empty) |
04454e1e | 93 | } else if self.token != token::CloseDelim(Delimiter::Brace) { |
5869c6ff | 94 | // Remainder are line-expr stmts. |
17df50a5 XL |
95 | let e = if force_collect == ForceCollect::Yes { |
96 | self.collect_tokens_no_attrs(|this| { | |
97 | this.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs)) | |
98 | }) | |
99 | } else { | |
100 | self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs)) | |
101 | }?; | |
5e7ed085 FG |
102 | if matches!(e.kind, ExprKind::Assign(..)) && self.eat_keyword(kw::Else) { |
103 | let bl = self.parse_block()?; | |
104 | // Destructuring assignment ... else. | |
105 | // This is not allowed, but point it out in a nice way. | |
106 | let mut err = self.struct_span_err( | |
107 | e.span.to(bl.span), | |
108 | "<assignment> ... else { ... } is not allowed", | |
109 | ); | |
110 | err.emit(); | |
111 | } | |
5869c6ff | 112 | self.mk_stmt(lo.to(e.span), StmtKind::Expr(e)) |
74b04a01 | 113 | } else { |
6a06907d | 114 | self.error_outer_attrs(&attrs.take_for_recovery()); |
5869c6ff XL |
115 | return Ok(None); |
116 | })) | |
74b04a01 | 117 | } |
dfeec247 | 118 | |
17df50a5 XL |
119 | fn parse_stmt_path_start(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> { |
120 | let stmt = self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| { | |
5869c6ff | 121 | let path = this.parse_path(PathStyle::Expr)?; |
dfeec247 | 122 | |
5869c6ff XL |
123 | if this.eat(&token::Not) { |
124 | let stmt_mac = this.parse_stmt_mac(lo, attrs.into(), path)?; | |
125 | if this.token == token::Semi { | |
126 | return Ok((stmt_mac, TrailingToken::Semi)); | |
127 | } else { | |
128 | return Ok((stmt_mac, TrailingToken::None)); | |
129 | } | |
130 | } | |
dfeec247 | 131 | |
04454e1e | 132 | let expr = if this.eat(&token::OpenDelim(Delimiter::Brace)) { |
17df50a5 | 133 | this.parse_struct_expr(None, path, AttrVec::new(), true)? |
5869c6ff XL |
134 | } else { |
135 | let hi = this.prev_token.span; | |
136 | this.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new()) | |
137 | }; | |
dfeec247 | 138 | |
5869c6ff | 139 | let expr = this.with_res(Restrictions::STMT_EXPR, |this| { |
cdc7bbd5 XL |
140 | this.parse_dot_or_call_expr_with(expr, lo, attrs) |
141 | })?; | |
142 | // `DUMMY_SP` will get overwritten later in this function | |
143 | Ok((this.mk_stmt(rustc_span::DUMMY_SP, StmtKind::Expr(expr)), TrailingToken::None)) | |
144 | })?; | |
145 | ||
146 | if let StmtKind::Expr(expr) = stmt.kind { | |
147 | // Perform this outside of the `collect_tokens_trailing_token` closure, | |
148 | // since our outer attributes do not apply to this part of the expression | |
149 | let expr = self.with_res(Restrictions::STMT_EXPR, |this| { | |
5869c6ff XL |
150 | this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr)) |
151 | })?; | |
cdc7bbd5 XL |
152 | Ok(self.mk_stmt(lo.to(self.prev_token.span), StmtKind::Expr(expr))) |
153 | } else { | |
154 | Ok(stmt) | |
155 | } | |
dfeec247 XL |
156 | } |
157 | ||
158 | /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`. | |
159 | /// At this point, the `!` token after the path has already been eaten. | |
74b04a01 | 160 | fn parse_stmt_mac(&mut self, lo: Span, attrs: AttrVec, path: ast::Path) -> PResult<'a, Stmt> { |
dfeec247 XL |
161 | let args = self.parse_mac_args()?; |
162 | let delim = args.delim(); | |
74b04a01 | 163 | let hi = self.prev_token.span; |
dfeec247 | 164 | |
04454e1e FG |
165 | let style = match delim { |
166 | Some(Delimiter::Brace) => MacStmtStyle::Braces, | |
167 | Some(_) => MacStmtStyle::NoBraces, | |
168 | None => unreachable!(), | |
169 | }; | |
dfeec247 | 170 | |
ba9703b0 | 171 | let mac = MacCall { path, args, prior_type_ascription: self.last_type_ascription }; |
dfeec247 | 172 | |
04454e1e FG |
173 | let kind = if (style == MacStmtStyle::Braces |
174 | && self.token != token::Dot | |
175 | && self.token != token::Question) | |
176 | || self.token == token::Semi | |
177 | || self.token == token::Eof | |
178 | { | |
179 | StmtKind::MacCall(P(MacCallStmt { mac, style, attrs, tokens: None })) | |
180 | } else { | |
181 | // Since none of the above applied, this is an expression statement macro. | |
182 | let e = self.mk_expr(lo.to(hi), ExprKind::MacCall(mac), AttrVec::new()); | |
923072b8 | 183 | let e = self.maybe_recover_from_bad_qpath(e)?; |
04454e1e FG |
184 | let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?; |
185 | let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?; | |
186 | StmtKind::Expr(e) | |
187 | }; | |
74b04a01 | 188 | Ok(self.mk_stmt(lo.to(hi), kind)) |
dfeec247 | 189 | } |
416331ca | 190 | |
dfeec247 XL |
191 | /// Error on outer attributes in this context. |
192 | /// Also error if the previous token was a doc comment. | |
193 | fn error_outer_attrs(&self, attrs: &[Attribute]) { | |
74b04a01 XL |
194 | if let [.., last] = attrs { |
195 | if last.is_doc_comment() { | |
17df50a5 | 196 | self.span_err(last.span, Error::UselessDocComment).emit(); |
dfeec247 | 197 | } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) { |
74b04a01 | 198 | self.struct_span_err(last.span, "expected statement after outer attribute").emit(); |
416331ca | 199 | } |
dfeec247 XL |
200 | } |
201 | } | |
202 | ||
dfeec247 XL |
203 | fn recover_stmt_local( |
204 | &mut self, | |
205 | lo: Span, | |
cdc7bbd5 | 206 | attrs: AttrWrapper, |
dfeec247 XL |
207 | msg: &str, |
208 | sugg: &str, | |
74b04a01 | 209 | ) -> PResult<'a, Stmt> { |
5869c6ff | 210 | let stmt = self.recover_local_after_let(lo, attrs)?; |
dfeec247 | 211 | self.struct_span_err(lo, "invalid variable declaration") |
923072b8 | 212 | .span_suggestion(lo, msg, sugg, Applicability::MachineApplicable) |
dfeec247 | 213 | .emit(); |
74b04a01 | 214 | Ok(stmt) |
dfeec247 XL |
215 | } |
216 | ||
5869c6ff XL |
217 | fn parse_local_mk( |
218 | &mut self, | |
219 | lo: Span, | |
6a06907d | 220 | attrs: AttrWrapper, |
5869c6ff XL |
221 | capture_semi: bool, |
222 | force_collect: ForceCollect, | |
223 | ) -> PResult<'a, Stmt> { | |
6a06907d | 224 | self.collect_tokens_trailing_token(attrs, force_collect, |this, attrs| { |
5869c6ff XL |
225 | this.expect_keyword(kw::Let)?; |
226 | let local = this.parse_local(attrs.into())?; | |
227 | let trailing = if capture_semi && this.token.kind == token::Semi { | |
228 | TrailingToken::Semi | |
229 | } else { | |
230 | TrailingToken::None | |
231 | }; | |
232 | Ok((this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), trailing)) | |
233 | }) | |
234 | } | |
235 | ||
cdc7bbd5 XL |
236 | fn recover_local_after_let(&mut self, lo: Span, attrs: AttrWrapper) -> PResult<'a, Stmt> { |
237 | self.collect_tokens_trailing_token(attrs, ForceCollect::No, |this, attrs| { | |
238 | let local = this.parse_local(attrs.into())?; | |
239 | // FIXME - maybe capture semicolon in recovery? | |
240 | Ok(( | |
241 | this.mk_stmt(lo.to(this.prev_token.span), StmtKind::Local(local)), | |
242 | TrailingToken::None, | |
243 | )) | |
244 | }) | |
416331ca XL |
245 | } |
246 | ||
247 | /// Parses a local variable declaration. | |
dfeec247 | 248 | fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> { |
74b04a01 | 249 | let lo = self.prev_token.span; |
cdc7bbd5 | 250 | let (pat, colon) = self.parse_pat_before_ty(None, RecoverComma::Yes, "`let` bindings")?; |
416331ca | 251 | |
6a06907d | 252 | let (err, ty) = if colon { |
416331ca XL |
253 | // Save the state of the parser before parsing type normally, in case there is a `:` |
254 | // instead of an `=` typo. | |
255 | let parser_snapshot_before_type = self.clone(); | |
74b04a01 | 256 | let colon_sp = self.prev_token.span; |
416331ca XL |
257 | match self.parse_ty() { |
258 | Ok(ty) => (None, Some(ty)), | |
259 | Err(mut err) => { | |
ba9703b0 XL |
260 | if let Ok(snip) = self.span_to_snippet(pat.span) { |
261 | err.span_label(pat.span, format!("while parsing the type for `{}`", snip)); | |
262 | } | |
923072b8 FG |
263 | // we use noexpect here because we don't actually expect Eq to be here |
264 | // but we are still checking for it in order to be able to handle it if | |
265 | // it is there | |
266 | let err = if self.check_noexpect(&token::Eq) { | |
3dfed10e XL |
267 | err.emit(); |
268 | None | |
269 | } else { | |
270 | // Rewind to before attempting to parse the type and continue parsing. | |
271 | let parser_snapshot_after_type = | |
272 | mem::replace(self, parser_snapshot_before_type); | |
273 | Some((parser_snapshot_after_type, colon_sp, err)) | |
274 | }; | |
275 | (err, None) | |
416331ca XL |
276 | } |
277 | } | |
278 | } else { | |
279 | (None, None) | |
280 | }; | |
281 | let init = match (self.parse_initializer(err.is_some()), err) { | |
dfeec247 XL |
282 | (Ok(init), None) => { |
283 | // init parsed, ty parsed | |
416331ca XL |
284 | init |
285 | } | |
dfeec247 XL |
286 | (Ok(init), Some((_, colon_sp, mut err))) => { |
287 | // init parsed, ty error | |
416331ca XL |
288 | // Could parse the type as if it were the initializer, it is likely there was a |
289 | // typo in the code: `:` instead of `=`. Add suggestion and emit the error. | |
290 | err.span_suggestion_short( | |
291 | colon_sp, | |
292 | "use `=` if you meant to assign", | |
923072b8 | 293 | " =", |
dfeec247 | 294 | Applicability::MachineApplicable, |
416331ca XL |
295 | ); |
296 | err.emit(); | |
297 | // As this was parsed successfully, continue as if the code has been fixed for the | |
298 | // rest of the file. It will still fail due to the emitted error, but we avoid | |
299 | // extra noise. | |
300 | init | |
301 | } | |
5e7ed085 | 302 | (Err(init_err), Some((snapshot, _, ty_err))) => { |
dfeec247 | 303 | // init error, ty error |
416331ca XL |
304 | init_err.cancel(); |
305 | // Couldn't parse the type nor the initializer, only raise the type error and | |
306 | // return to the parser state before parsing the type as the initializer. | |
307 | // let x: <parse_error>; | |
f9f354fc | 308 | *self = snapshot; |
416331ca XL |
309 | return Err(ty_err); |
310 | } | |
dfeec247 XL |
311 | (Err(err), None) => { |
312 | // init error, ty parsed | |
416331ca XL |
313 | // Couldn't parse the initializer and we're not attempting to recover a failed |
314 | // parse of the type, return the error. | |
315 | return Err(err); | |
316 | } | |
317 | }; | |
94222f64 XL |
318 | let kind = match init { |
319 | None => LocalKind::Decl, | |
320 | Some(init) => { | |
321 | if self.eat_keyword(kw::Else) { | |
3c0e092e XL |
322 | if self.token.is_keyword(kw::If) { |
323 | // `let...else if`. Emit the same error that `parse_block()` would, | |
324 | // but explicitly point out that this pattern is not allowed. | |
325 | let msg = "conditional `else if` is not supported for `let...else`"; | |
326 | return Err(self.error_block_no_opening_brace_msg(msg)); | |
327 | } | |
94222f64 XL |
328 | let els = self.parse_block()?; |
329 | self.check_let_else_init_bool_expr(&init); | |
330 | self.check_let_else_init_trailing_brace(&init); | |
331 | LocalKind::InitElse(init, els) | |
332 | } else { | |
333 | LocalKind::Init(init) | |
334 | } | |
335 | } | |
336 | }; | |
74b04a01 | 337 | let hi = if self.token == token::Semi { self.token.span } else { self.prev_token.span }; |
94222f64 XL |
338 | Ok(P(ast::Local { ty, pat, kind, id: DUMMY_NODE_ID, span: lo.to(hi), attrs, tokens: None })) |
339 | } | |
340 | ||
341 | fn check_let_else_init_bool_expr(&self, init: &ast::Expr) { | |
342 | if let ast::ExprKind::Binary(op, ..) = init.kind { | |
343 | if op.node.lazy() { | |
344 | let suggs = vec![ | |
345 | (init.span.shrink_to_lo(), "(".to_string()), | |
346 | (init.span.shrink_to_hi(), ")".to_string()), | |
347 | ]; | |
348 | self.struct_span_err( | |
349 | init.span, | |
350 | &format!( | |
351 | "a `{}` expression cannot be directly assigned in `let...else`", | |
352 | op.node.to_string() | |
353 | ), | |
354 | ) | |
355 | .multipart_suggestion( | |
3c0e092e | 356 | "wrap the expression in parentheses", |
94222f64 XL |
357 | suggs, |
358 | Applicability::MachineApplicable, | |
359 | ) | |
360 | .emit(); | |
361 | } | |
362 | } | |
363 | } | |
364 | ||
365 | fn check_let_else_init_trailing_brace(&self, init: &ast::Expr) { | |
366 | if let Some(trailing) = classify::expr_trailing_brace(init) { | |
367 | let err_span = trailing.span.with_lo(trailing.span.hi() - BytePos(1)); | |
368 | let suggs = vec![ | |
369 | (trailing.span.shrink_to_lo(), "(".to_string()), | |
370 | (trailing.span.shrink_to_hi(), ")".to_string()), | |
371 | ]; | |
372 | self.struct_span_err( | |
373 | err_span, | |
374 | "right curly brace `}` before `else` in a `let...else` statement not allowed", | |
375 | ) | |
376 | .multipart_suggestion( | |
3c0e092e | 377 | "try wrapping the expression in parentheses", |
94222f64 XL |
378 | suggs, |
379 | Applicability::MachineApplicable, | |
380 | ) | |
381 | .emit(); | |
382 | } | |
416331ca XL |
383 | } |
384 | ||
6a06907d | 385 | /// Parses the RHS of a local variable declaration (e.g., `= 14;`). |
f035d41b XL |
386 | fn parse_initializer(&mut self, eq_optional: bool) -> PResult<'a, Option<P<Expr>>> { |
387 | let eq_consumed = match self.token.kind { | |
388 | token::BinOpEq(..) => { | |
389 | // Recover `let x <op>= 1` as `let x = 1` | |
390 | self.struct_span_err( | |
391 | self.token.span, | |
392 | "can't reassign to an uninitialized variable", | |
393 | ) | |
394 | .span_suggestion_short( | |
395 | self.token.span, | |
396 | "initialize the variable", | |
923072b8 | 397 | "=", |
f035d41b XL |
398 | Applicability::MaybeIncorrect, |
399 | ) | |
6a06907d | 400 | .help("if you meant to overwrite, remove the `let` binding") |
f035d41b XL |
401 | .emit(); |
402 | self.bump(); | |
403 | true | |
404 | } | |
405 | _ => self.eat(&token::Eq), | |
406 | }; | |
407 | ||
408 | Ok(if eq_consumed || eq_optional { Some(self.parse_expr()?) } else { None }) | |
416331ca XL |
409 | } |
410 | ||
416331ca | 411 | /// Parses a block. No inner attributes are allowed. |
3dfed10e | 412 | pub(super) fn parse_block(&mut self) -> PResult<'a, P<Block>> { |
ba9703b0 XL |
413 | let (attrs, block) = self.parse_inner_attrs_and_block()?; |
414 | if let [.., last] = &*attrs { | |
415 | self.error_on_forbidden_inner_attr(last.span, DEFAULT_INNER_ATTR_FORBIDDEN); | |
dfeec247 | 416 | } |
ba9703b0 | 417 | Ok(block) |
dfeec247 XL |
418 | } |
419 | ||
5e7ed085 FG |
420 | fn error_block_no_opening_brace_msg( |
421 | &mut self, | |
422 | msg: &str, | |
423 | ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { | |
dfeec247 | 424 | let sp = self.token.span; |
3c0e092e | 425 | let mut e = self.struct_span_err(sp, msg); |
dfeec247 XL |
426 | let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon; |
427 | ||
428 | // Check to see if the user has written something like | |
429 | // | |
430 | // if (cond) | |
431 | // bar; | |
432 | // | |
433 | // which is valid in other languages, but not Rust. | |
5869c6ff | 434 | match self.parse_stmt_without_recovery(false, ForceCollect::No) { |
923072b8 FG |
435 | // If the next token is an open brace, e.g., we have: |
436 | // | |
437 | // if expr other_expr { | |
438 | // ^ ^ ^- lookahead(1) is a brace | |
439 | // | |- current token is not "else" | |
440 | // |- (statement we just parsed) | |
441 | // | |
442 | // the place-inside-a-block suggestion would be more likely wrong than right. | |
443 | // | |
444 | // FIXME(compiler-errors): this should probably parse an arbitrary expr and not | |
445 | // just lookahead one token, so we can see if there's a brace after _that_, | |
446 | // since we want to protect against: | |
447 | // `if 1 1 + 1 {` being suggested as `if { 1 } 1 + 1 {` | |
448 | // + + | |
ba9703b0 | 449 | Ok(Some(_)) |
923072b8 FG |
450 | if (!self.token.is_keyword(kw::Else) |
451 | && self.look_ahead(1, |t| t == &token::OpenDelim(Delimiter::Brace))) | |
ba9703b0 | 452 | || do_not_suggest_help => {} |
5e7ed085 FG |
453 | // Do not suggest `if foo println!("") {;}` (as would be seen in test for #46836). |
454 | Ok(Some(Stmt { kind: StmtKind::Empty, .. })) => {} | |
ba9703b0 XL |
455 | Ok(Some(stmt)) => { |
456 | let stmt_own_line = self.sess.source_map().is_line_before_span_empty(sp); | |
457 | let stmt_span = if stmt_own_line && self.eat(&token::Semi) { | |
dfeec247 | 458 | // Expand the span to include the semicolon. |
74b04a01 | 459 | stmt.span.with_hi(self.prev_token.span.hi()) |
dfeec247 XL |
460 | } else { |
461 | stmt.span | |
462 | }; | |
5e7ed085 FG |
463 | e.multipart_suggestion( |
464 | "try placing this code inside a block", | |
465 | vec![ | |
466 | (stmt_span.shrink_to_lo(), "{ ".to_string()), | |
467 | (stmt_span.shrink_to_hi(), " }".to_string()), | |
468 | ], | |
469 | // Speculative; has been misleading in the past (#46836). | |
470 | Applicability::MaybeIncorrect, | |
471 | ); | |
416331ca | 472 | } |
5e7ed085 | 473 | Err(e) => { |
dfeec247 XL |
474 | self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore); |
475 | e.cancel(); | |
476 | } | |
477 | _ => {} | |
416331ca | 478 | } |
dfeec247 | 479 | e.span_label(sp, "expected `{`"); |
3c0e092e XL |
480 | e |
481 | } | |
482 | ||
483 | fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> { | |
484 | let tok = super::token_descr(&self.token); | |
485 | let msg = format!("expected `{{`, found {}", tok); | |
486 | Err(self.error_block_no_opening_brace_msg(&msg)) | |
416331ca XL |
487 | } |
488 | ||
489 | /// Parses a block. Inner attributes are allowed. | |
e74abb32 | 490 | pub(super) fn parse_inner_attrs_and_block( |
dfeec247 | 491 | &mut self, |
ba9703b0 XL |
492 | ) -> PResult<'a, (Vec<Attribute>, P<Block>)> { |
493 | self.parse_block_common(self.token.span, BlockCheckMode::Default) | |
494 | } | |
495 | ||
496 | /// Parses a block. Inner attributes are allowed. | |
497 | pub(super) fn parse_block_common( | |
498 | &mut self, | |
499 | lo: Span, | |
500 | blk_mode: BlockCheckMode, | |
e74abb32 | 501 | ) -> PResult<'a, (Vec<Attribute>, P<Block>)> { |
416331ca XL |
502 | maybe_whole!(self, NtBlock, |x| (Vec::new(), x)); |
503 | ||
5e7ed085 | 504 | self.maybe_recover_unexpected_block_label(); |
04454e1e | 505 | if !self.eat(&token::OpenDelim(Delimiter::Brace)) { |
ba9703b0 XL |
506 | return self.error_block_no_opening_brace(); |
507 | } | |
508 | ||
29967ef6 | 509 | let attrs = self.parse_inner_attributes()?; |
5e7ed085 FG |
510 | let tail = match self.maybe_suggest_struct_literal(lo, blk_mode) { |
511 | Some(tail) => tail?, | |
512 | None => self.parse_block_tail(lo, blk_mode, AttemptLocalParseRecovery::Yes)?, | |
29967ef6 XL |
513 | }; |
514 | Ok((attrs, tail)) | |
416331ca XL |
515 | } |
516 | ||
517 | /// Parses the rest of a block expression or function body. | |
518 | /// Precondition: already parsed the '{'. | |
923072b8 | 519 | pub(crate) fn parse_block_tail( |
29967ef6 XL |
520 | &mut self, |
521 | lo: Span, | |
522 | s: BlockCheckMode, | |
523 | recover: AttemptLocalParseRecovery, | |
524 | ) -> PResult<'a, P<Block>> { | |
416331ca | 525 | let mut stmts = vec![]; |
04454e1e | 526 | while !self.eat(&token::CloseDelim(Delimiter::Brace)) { |
416331ca XL |
527 | if self.token == token::Eof { |
528 | break; | |
529 | } | |
29967ef6 XL |
530 | let stmt = match self.parse_full_stmt(recover) { |
531 | Err(mut err) if recover.yes() => { | |
60c5eb7d | 532 | self.maybe_annotate_with_ascription(&mut err, false); |
416331ca XL |
533 | err.emit(); |
534 | self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore); | |
dfeec247 | 535 | Some(self.mk_stmt_err(self.token.span)) |
416331ca XL |
536 | } |
537 | Ok(stmt) => stmt, | |
29967ef6 | 538 | Err(err) => return Err(err), |
416331ca XL |
539 | }; |
540 | if let Some(stmt) = stmt { | |
541 | stmts.push(stmt); | |
542 | } else { | |
543 | // Found only `;` or `}`. | |
544 | continue; | |
545 | }; | |
546 | } | |
74b04a01 | 547 | Ok(self.mk_block(stmts, s, lo.to(self.prev_token.span))) |
416331ca XL |
548 | } |
549 | ||
550 | /// Parses a statement, including the trailing semicolon. | |
29967ef6 XL |
551 | pub fn parse_full_stmt( |
552 | &mut self, | |
553 | recover: AttemptLocalParseRecovery, | |
554 | ) -> PResult<'a, Option<Stmt>> { | |
e1599b0c | 555 | // Skip looking for a trailing semicolon when we have an interpolated statement. |
04454e1e | 556 | maybe_whole!(self, NtStmt, |x| Some(x.into_inner())); |
416331ca | 557 | |
5e7ed085 FG |
558 | let Some(mut stmt) = self.parse_stmt_without_recovery(true, ForceCollect::No)? else { |
559 | return Ok(None); | |
416331ca XL |
560 | }; |
561 | ||
e74abb32 XL |
562 | let mut eat_semi = true; |
563 | match stmt.kind { | |
74b04a01 | 564 | // Expression without semicolon. |
1b1a35ee | 565 | StmtKind::Expr(ref mut expr) |
74b04a01 XL |
566 | if self.token != token::Eof && classify::expr_requires_semi_to_be_stmt(expr) => |
567 | { | |
568 | // Just check for errors and recover; do not eat semicolon yet. | |
569 | if let Err(mut e) = | |
04454e1e | 570 | self.expect_one_of(&[], &[token::Semi, token::CloseDelim(Delimiter::Brace)]) |
74b04a01 XL |
571 | { |
572 | if let TokenKind::DocComment(..) = self.token.kind { | |
573 | if let Ok(snippet) = self.span_to_snippet(self.token.span) { | |
574 | let sp = self.token.span; | |
575 | let marker = &snippet[..3]; | |
576 | let (comment_marker, doc_comment_marker) = marker.split_at(2); | |
577 | ||
578 | e.span_suggestion( | |
579 | sp.with_hi(sp.lo() + BytePos(marker.len() as u32)), | |
580 | &format!( | |
581 | "add a space before `{}` to use a regular comment", | |
582 | doc_comment_marker, | |
583 | ), | |
584 | format!("{} {}", comment_marker, doc_comment_marker), | |
585 | Applicability::MaybeIncorrect, | |
586 | ); | |
587 | } | |
416331ca | 588 | } |
1b1a35ee XL |
589 | if let Err(mut e) = |
590 | self.check_mistyped_turbofish_with_multiple_type_params(e, expr) | |
591 | { | |
29967ef6 XL |
592 | if recover.no() { |
593 | return Err(e); | |
594 | } | |
1b1a35ee XL |
595 | e.emit(); |
596 | self.recover_stmt(); | |
597 | } | |
74b04a01 XL |
598 | // Don't complain about type errors in body tail after parse error (#57383). |
599 | let sp = expr.span.to(self.prev_token.span); | |
1b1a35ee | 600 | *expr = self.mk_expr_err(sp); |
416331ca XL |
601 | } |
602 | } | |
fc512014 | 603 | StmtKind::Expr(_) | StmtKind::MacCall(_) => {} |
94222f64 XL |
604 | StmtKind::Local(ref mut local) if let Err(e) = self.expect_semi() => { |
605 | // We might be at the `,` in `let x = foo<bar, baz>;`. Try to recover. | |
606 | match &mut local.kind { | |
607 | LocalKind::Init(expr) | LocalKind::InitElse(expr, _) => { | |
5e7ed085 FG |
608 | self.check_mistyped_turbofish_with_multiple_type_params(e, expr)?; |
609 | // We found `foo<bar, baz>`, have we fully recovered? | |
610 | self.expect_semi()?; | |
611 | } | |
612 | LocalKind::Decl => return Err(e), | |
1b1a35ee | 613 | } |
74b04a01 | 614 | eat_semi = false; |
416331ca | 615 | } |
94222f64 | 616 | StmtKind::Empty | StmtKind::Item(_) | StmtKind::Local(_) | StmtKind::Semi(_) => eat_semi = false, |
416331ca XL |
617 | } |
618 | ||
e74abb32 | 619 | if eat_semi && self.eat(&token::Semi) { |
416331ca XL |
620 | stmt = stmt.add_trailing_semicolon(); |
621 | } | |
74b04a01 | 622 | stmt.span = stmt.span.to(self.prev_token.span); |
416331ca XL |
623 | Ok(Some(stmt)) |
624 | } | |
625 | ||
dfeec247 | 626 | pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> { |
94222f64 XL |
627 | P(Block { |
628 | stmts, | |
629 | id: DUMMY_NODE_ID, | |
630 | rules, | |
631 | span, | |
632 | tokens: None, | |
633 | could_be_bare_literal: false, | |
634 | }) | |
dfeec247 XL |
635 | } |
636 | ||
637 | pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt { | |
fc512014 | 638 | Stmt { id: DUMMY_NODE_ID, kind, span } |
dfeec247 XL |
639 | } |
640 | ||
29967ef6 | 641 | pub(super) fn mk_stmt_err(&self, span: Span) -> Stmt { |
dfeec247 XL |
642 | self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span))) |
643 | } | |
644 | ||
645 | pub(super) fn mk_block_err(&self, span: Span) -> P<Block> { | |
646 | self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span) | |
416331ca XL |
647 | } |
648 | } |