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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
use super::diagnostics::Error;
use super::expr::LhsExpr;
use super::pat::GateOr;
use super::path::PathStyle;
use super::{BlockMode, Parser, PrevTokenKind, Restrictions, SemiColonMode};
use crate::maybe_whole;
use crate::DirectoryOwnership;

use rustc_errors::{Applicability, PResult};
use rustc_span::source_map::{respan, Span};
use rustc_span::symbol::{kw, sym, Symbol};
use syntax::ast;
use syntax::ast::{AttrStyle, AttrVec, Attribute, Mac, MacStmtStyle, VisibilityKind};
use syntax::ast::{Block, BlockCheckMode, Expr, ExprKind, Local, Stmt, StmtKind, DUMMY_NODE_ID};
use syntax::ptr::P;
use syntax::token;
use syntax::util::classify;

use std::mem;

impl<'a> Parser<'a> {
    /// Parses a statement. This stops just before trailing semicolons on everything but items.
    /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
    pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
        Ok(self.parse_stmt_without_recovery(true).unwrap_or_else(|mut e| {
            e.emit();
            self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
            None
        }))
    }

    fn parse_stmt_without_recovery(
        &mut self,
        macro_legacy_warnings: bool,
    ) -> PResult<'a, Option<Stmt>> {
        maybe_whole!(self, NtStmt, |x| Some(x));

        let attrs = self.parse_outer_attributes()?;
        let lo = self.token.span;

        if self.eat_keyword(kw::Let) {
            return self.parse_local_mk(lo, attrs.into()).map(Some);
        }
        if self.is_kw_followed_by_ident(kw::Mut) {
            return self.recover_stmt_local(lo, attrs.into(), "missing keyword", "let mut");
        }
        if self.is_kw_followed_by_ident(kw::Auto) {
            self.bump(); // `auto`
            let msg = "write `let` instead of `auto` to introduce a new variable";
            return self.recover_stmt_local(lo, attrs.into(), msg, "let");
        }
        if self.is_kw_followed_by_ident(sym::var) {
            self.bump(); // `var`
            let msg = "write `let` instead of `var` to introduce a new variable";
            return self.recover_stmt_local(lo, attrs.into(), msg, "let");
        }

        let mac_vis = respan(lo, VisibilityKind::Inherited);
        if let Some(macro_def) = self.eat_macro_def(&attrs, &mac_vis, lo)? {
            return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Item(macro_def))));
        }

        // Starts like a simple path, being careful to avoid contextual keywords
        // such as a union items, item with `crate` visibility or auto trait items.
        // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
        // like a path (1 token), but it fact not a path.
        if self.token.is_path_start()
            && !self.token.is_qpath_start()
            && !self.is_union_item() // `union::b::c` - path, `union U { ... }` - not a path.
            && !self.is_crate_vis() // `crate::b::c` - path, `crate struct S;` - not a path.
            && !self.is_auto_trait_item()
            && !self.is_async_fn()
        {
            let path = self.parse_path(PathStyle::Expr)?;

            if self.eat(&token::Not) {
                return self.parse_stmt_mac(lo, attrs.into(), path, macro_legacy_warnings);
            }

            let expr = if self.check(&token::OpenDelim(token::Brace)) {
                self.parse_struct_expr(lo, path, AttrVec::new())?
            } else {
                let hi = self.prev_span;
                self.mk_expr(lo.to(hi), ExprKind::Path(None, path), AttrVec::new())
            };

            let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
                let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
                this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
            })?;
            return Ok(Some(self.mk_stmt(lo.to(self.prev_span), StmtKind::Expr(expr))));
        }

        // FIXME: Bad copy of attrs
        let old_directory_ownership =
            mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
        let item = self.parse_item_(attrs.clone(), false, true)?;
        self.directory.ownership = old_directory_ownership;

        if let Some(item) = item {
            return Ok(Some(self.mk_stmt(lo.to(item.span), StmtKind::Item(item))));
        }

        // Do not attempt to parse an expression if we're done here.
        if self.token == token::Semi {
            self.error_outer_attrs(&attrs);
            self.bump();
            let mut last_semi = lo;
            while self.token == token::Semi {
                last_semi = self.token.span;
                self.bump();
            }
            // We are encoding a string of semicolons as an an empty tuple that spans
            // the excess semicolons to preserve this info until the lint stage.
            let kind = StmtKind::Semi(self.mk_expr(
                lo.to(last_semi),
                ExprKind::Tup(Vec::new()),
                AttrVec::new(),
            ));
            return Ok(Some(self.mk_stmt(lo.to(last_semi), kind)));
        }

        if self.token == token::CloseDelim(token::Brace) {
            self.error_outer_attrs(&attrs);
            return Ok(None);
        }

        // Remainder are line-expr stmts.
        let e = self.parse_expr_res(Restrictions::STMT_EXPR, Some(attrs.into()))?;
        Ok(Some(self.mk_stmt(lo.to(e.span), StmtKind::Expr(e))))
    }

    /// Parses a statement macro `mac!(args)` provided a `path` representing `mac`.
    /// At this point, the `!` token after the path has already been eaten.
    fn parse_stmt_mac(
        &mut self,
        lo: Span,
        attrs: AttrVec,
        path: ast::Path,
        legacy_warnings: bool,
    ) -> PResult<'a, Option<Stmt>> {
        let args = self.parse_mac_args()?;
        let delim = args.delim();
        let hi = self.prev_span;

        let style =
            if delim == token::Brace { MacStmtStyle::Braces } else { MacStmtStyle::NoBraces };

        let mac = Mac { path, args, prior_type_ascription: self.last_type_ascription };

        let kind = if delim == token::Brace || self.token == token::Semi || self.token == token::Eof
        {
            StmtKind::Mac(P((mac, style, attrs.into())))
        }
        // We used to incorrectly stop parsing macro-expanded statements here.
        // If the next token will be an error anyway but could have parsed with the
        // earlier behavior, stop parsing here and emit a warning to avoid breakage.
        else if legacy_warnings
            && self.token.can_begin_expr()
            && match self.token.kind {
                // These can continue an expression, so we can't stop parsing and warn.
                token::OpenDelim(token::Paren)
                | token::OpenDelim(token::Bracket)
                | token::BinOp(token::Minus)
                | token::BinOp(token::Star)
                | token::BinOp(token::And)
                | token::BinOp(token::Or)
                | token::AndAnd
                | token::OrOr
                | token::DotDot
                | token::DotDotDot
                | token::DotDotEq => false,
                _ => true,
            }
        {
            self.warn_missing_semicolon();
            StmtKind::Mac(P((mac, style, attrs)))
        } else {
            // Since none of the above applied, this is an expression statement macro.
            let e = self.mk_expr(lo.to(hi), ExprKind::Mac(mac), AttrVec::new());
            let e = self.maybe_recover_from_bad_qpath(e, true)?;
            let e = self.parse_dot_or_call_expr_with(e, lo, attrs)?;
            let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
            StmtKind::Expr(e)
        };
        Ok(Some(self.mk_stmt(lo.to(hi), kind)))
    }

    /// Error on outer attributes in this context.
    /// Also error if the previous token was a doc comment.
    fn error_outer_attrs(&self, attrs: &[Attribute]) {
        if !attrs.is_empty() {
            if self.prev_token_kind == PrevTokenKind::DocComment {
                self.span_fatal_err(self.prev_span, Error::UselessDocComment).emit();
            } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
                self.struct_span_err(self.token.span, "expected statement after outer attribute")
                    .emit();
            }
        }
    }

    fn is_kw_followed_by_ident(&self, kw: Symbol) -> bool {
        self.token.is_keyword(kw) && self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
    }

    fn recover_stmt_local(
        &mut self,
        lo: Span,
        attrs: AttrVec,
        msg: &str,
        sugg: &str,
    ) -> PResult<'a, Option<Stmt>> {
        let stmt = self.parse_local_mk(lo, attrs)?;
        self.struct_span_err(lo, "invalid variable declaration")
            .span_suggestion(lo, msg, sugg.to_string(), Applicability::MachineApplicable)
            .emit();
        Ok(Some(stmt))
    }

    fn parse_local_mk(&mut self, lo: Span, attrs: AttrVec) -> PResult<'a, Stmt> {
        let local = self.parse_local(attrs.into())?;
        Ok(self.mk_stmt(lo.to(self.prev_span), StmtKind::Local(local)))
    }

    /// Parses a local variable declaration.
    fn parse_local(&mut self, attrs: AttrVec) -> PResult<'a, P<Local>> {
        let lo = self.prev_span;
        let pat = self.parse_top_pat(GateOr::Yes)?;

        let (err, ty) = if self.eat(&token::Colon) {
            // Save the state of the parser before parsing type normally, in case there is a `:`
            // instead of an `=` typo.
            let parser_snapshot_before_type = self.clone();
            let colon_sp = self.prev_span;
            match self.parse_ty() {
                Ok(ty) => (None, Some(ty)),
                Err(mut err) => {
                    // Rewind to before attempting to parse the type and continue parsing.
                    let parser_snapshot_after_type = self.clone();
                    mem::replace(self, parser_snapshot_before_type);

                    let snippet = self.span_to_snippet(pat.span).unwrap();
                    err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
                    (Some((parser_snapshot_after_type, colon_sp, err)), None)
                }
            }
        } else {
            (None, None)
        };
        let init = match (self.parse_initializer(err.is_some()), err) {
            (Ok(init), None) => {
                // init parsed, ty parsed
                init
            }
            (Ok(init), Some((_, colon_sp, mut err))) => {
                // init parsed, ty error
                // Could parse the type as if it were the initializer, it is likely there was a
                // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
                err.span_suggestion_short(
                    colon_sp,
                    "use `=` if you meant to assign",
                    " =".to_string(),
                    Applicability::MachineApplicable,
                );
                err.emit();
                // As this was parsed successfully, continue as if the code has been fixed for the
                // rest of the file. It will still fail due to the emitted error, but we avoid
                // extra noise.
                init
            }
            (Err(mut init_err), Some((snapshot, _, ty_err))) => {
                // init error, ty error
                init_err.cancel();
                // Couldn't parse the type nor the initializer, only raise the type error and
                // return to the parser state before parsing the type as the initializer.
                // let x: <parse_error>;
                mem::replace(self, snapshot);
                return Err(ty_err);
            }
            (Err(err), None) => {
                // init error, ty parsed
                // Couldn't parse the initializer and we're not attempting to recover a failed
                // parse of the type, return the error.
                return Err(err);
            }
        };
        let hi = if self.token == token::Semi { self.token.span } else { self.prev_span };
        Ok(P(ast::Local { ty, pat, init, id: DUMMY_NODE_ID, span: lo.to(hi), attrs }))
    }

    /// Parses the RHS of a local variable declaration (e.g., '= 14;').
    fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
        if self.eat(&token::Eq) {
            Ok(Some(self.parse_expr()?))
        } else if skip_eq {
            Ok(Some(self.parse_expr()?))
        } else {
            Ok(None)
        }
    }

    fn is_auto_trait_item(&self) -> bool {
        // auto trait
        (self.token.is_keyword(kw::Auto) &&
            self.is_keyword_ahead(1, &[kw::Trait]))
        || // unsafe auto trait
        (self.token.is_keyword(kw::Unsafe) &&
         self.is_keyword_ahead(1, &[kw::Auto]) &&
         self.is_keyword_ahead(2, &[kw::Trait]))
    }

    /// Parses a block. No inner attributes are allowed.
    pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
        maybe_whole!(self, NtBlock, |x| x);

        let lo = self.token.span;

        if !self.eat(&token::OpenDelim(token::Brace)) {
            return self.error_block_no_opening_brace();
        }

        self.parse_block_tail(lo, BlockCheckMode::Default)
    }

    fn error_block_no_opening_brace<T>(&mut self) -> PResult<'a, T> {
        let sp = self.token.span;
        let tok = super::token_descr(&self.token);
        let mut e = self.struct_span_err(sp, &format!("expected `{{`, found {}", tok));
        let do_not_suggest_help = self.token.is_keyword(kw::In) || self.token == token::Colon;

        // Check to see if the user has written something like
        //
        //    if (cond)
        //      bar;
        //
        // which is valid in other languages, but not Rust.
        match self.parse_stmt_without_recovery(false) {
            Ok(Some(stmt)) => {
                if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
                    || do_not_suggest_help
                {
                    // If the next token is an open brace (e.g., `if a b {`), the place-
                    // inside-a-block suggestion would be more likely wrong than right.
                    e.span_label(sp, "expected `{`");
                    return Err(e);
                }
                let stmt_span = if self.eat(&token::Semi) {
                    // Expand the span to include the semicolon.
                    stmt.span.with_hi(self.prev_span.hi())
                } else {
                    stmt.span
                };
                if let Ok(snippet) = self.span_to_snippet(stmt_span) {
                    e.span_suggestion(
                        stmt_span,
                        "try placing this code inside a block",
                        format!("{{ {} }}", snippet),
                        // Speculative; has been misleading in the past (#46836).
                        Applicability::MaybeIncorrect,
                    );
                }
            }
            Err(mut e) => {
                self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
                e.cancel();
            }
            _ => {}
        }
        e.span_label(sp, "expected `{`");
        return Err(e);
    }

    /// Parses a block. Inner attributes are allowed.
    pub(super) fn parse_inner_attrs_and_block(
        &mut self,
    ) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
        maybe_whole!(self, NtBlock, |x| (Vec::new(), x));

        let lo = self.token.span;
        self.expect(&token::OpenDelim(token::Brace))?;
        Ok((self.parse_inner_attributes()?, self.parse_block_tail(lo, BlockCheckMode::Default)?))
    }

    /// Parses the rest of a block expression or function body.
    /// Precondition: already parsed the '{'.
    pub(super) fn parse_block_tail(
        &mut self,
        lo: Span,
        s: BlockCheckMode,
    ) -> PResult<'a, P<Block>> {
        let mut stmts = vec![];
        while !self.eat(&token::CloseDelim(token::Brace)) {
            if self.token == token::Eof {
                break;
            }
            let stmt = match self.parse_full_stmt(false) {
                Err(mut err) => {
                    self.maybe_annotate_with_ascription(&mut err, false);
                    err.emit();
                    self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
                    Some(self.mk_stmt_err(self.token.span))
                }
                Ok(stmt) => stmt,
            };
            if let Some(stmt) = stmt {
                stmts.push(stmt);
            } else {
                // Found only `;` or `}`.
                continue;
            };
        }
        Ok(self.mk_block(stmts, s, lo.to(self.prev_span)))
    }

    /// Parses a statement, including the trailing semicolon.
    pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
        // Skip looking for a trailing semicolon when we have an interpolated statement.
        maybe_whole!(self, NtStmt, |x| Some(x));

        let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
            Some(stmt) => stmt,
            None => return Ok(None),
        };

        let mut eat_semi = true;
        match stmt.kind {
            StmtKind::Expr(ref expr) if self.token != token::Eof => {
                // expression without semicolon
                if classify::expr_requires_semi_to_be_stmt(expr) {
                    // Just check for errors and recover; do not eat semicolon yet.
                    if let Err(mut e) =
                        self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
                    {
                        e.emit();
                        self.recover_stmt();
                        // Don't complain about type errors in body tail after parse error (#57383).
                        let sp = expr.span.to(self.prev_span);
                        stmt.kind = StmtKind::Expr(self.mk_expr_err(sp));
                    }
                }
            }
            StmtKind::Local(..) => {
                // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
                if macro_legacy_warnings && self.token != token::Semi {
                    self.warn_missing_semicolon();
                } else {
                    self.expect_semi()?;
                    eat_semi = false;
                }
            }
            _ => {}
        }

        if eat_semi && self.eat(&token::Semi) {
            stmt = stmt.add_trailing_semicolon();
        }
        stmt.span = stmt.span.to(self.prev_span);
        Ok(Some(stmt))
    }

    fn warn_missing_semicolon(&self) {
        self.diagnostic()
            .struct_span_warn(self.token.span, {
                &format!("expected `;`, found {}", super::token_descr(&self.token))
            })
            .note({
                "this was erroneously allowed and will become a hard error in a future release"
            })
            .emit();
    }

    pub(super) fn mk_block(&self, stmts: Vec<Stmt>, rules: BlockCheckMode, span: Span) -> P<Block> {
        P(Block { stmts, id: DUMMY_NODE_ID, rules, span })
    }

    pub(super) fn mk_stmt(&self, span: Span, kind: StmtKind) -> Stmt {
        Stmt { id: DUMMY_NODE_ID, kind, span }
    }

    fn mk_stmt_err(&self, span: Span) -> Stmt {
        self.mk_stmt(span, StmtKind::Expr(self.mk_expr_err(span)))
    }

    pub(super) fn mk_block_err(&self, span: Span) -> P<Block> {
        self.mk_block(vec![self.mk_stmt_err(span)], BlockCheckMode::Default, span)
    }
}