about summary refs log tree commit diff
path: root/compiler/rustc_parse/src/parser/stmt.rs
AgeCommit message (Collapse)AuthorLines
2025-06-26Add Ident::is_non_reserved_identMichael Goulet-1/+1
2025-06-03Add `iter` macroOli Scherer-1/+1
This adds an `iter!` macro that can be used to create movable generators. This also adds a yield_expr feature so the `yield` keyword can be used within iter! macro bodies. This was needed because several unstable features each need `yield` expressions, so this allows us to stabilize them separately from any individual feature. Co-authored-by: Oli Scherer <github35764891676564198441@oli-obk.de> Co-authored-by: Jieyou Xu <jieyouxu@outlook.com> Co-authored-by: Travis Cross <tc@traviscross.com>
2025-05-28Fix ICE in tokenstream with contracts from parser recoveryyukang-7/+6
2025-05-14Improve ternary operator recoveryJamie-1/+6
2025-04-21Remove `token::{Open,Close}Delim`.Nicholas Nethercote-20/+13
By replacing them with `{Open,Close}{Param,Brace,Bracket,Invisible}`. PR #137902 made `ast::TokenKind` more like `lexer::TokenKind` by replacing the compound `BinOp{,Eq}(BinOpToken)` variants with fieldless variants `Plus`, `Minus`, `Star`, etc. This commit does a similar thing with delimiters. It also makes `ast::TokenKind` more similar to `parser::TokenType`. This requires a few new methods: - `TokenKind::is_{,open_,close_}delim()` replace various kinds of pattern matches. - `Delimiter::as_{open,close}_token_kind` are used to convert `Delimiter` values to `TokenKind`. Despite these additions, it's a net reduction in lines of code. This is because e.g. `token::OpenParen` is so much shorter than `token::OpenDelim(Delimiter::Parenthesis)` that many multi-line forms reduce to single line forms. And many places where the number of lines doesn't change are still easier to read, just because the names are shorter, e.g.: ``` - } else if self.token != token::CloseDelim(Delimiter::Brace) { + } else if self.token != token::CloseBrace { ```
2025-04-16Remove old diagnostic notes for type ascription syntaxZalathar-4/+0
Type ascription syntax was removed in 2023.
2025-04-14Rollup merge of #139392 - compiler-errors:raw-expr, r=oli-obkMatthias Krüger-1/+5
Detect and provide suggestion for `&raw EXPR` When emitting an error in the parser, and we detect that the previous token was `raw` and we *could* have consumed `const`/`mut`, suggest that this may have been a mistyped raw ref expr. To do this, we add `const`/`mut` to the expected token set when parsing `&raw` as an expression (which does not affect the "good path" of parsing, for the record). This is kind of a rudimentary error improvement, since it doesn't actually attempt to recover anything, leading to some other knock-on errors b/c we still treat `&raw` as the expression that was parsed... but at least we add the suggestion! I don't think the parser grammar means we can faithfully recover `&raw EXPR` early, i.e. during `parse_expr_borrow`. Fixes #133231
2025-04-14Auto merge of #124141 - ↵bors-5/+7
nnethercote:rm-Nonterminal-and-TokenKind-Interpolated, r=petrochenkov Remove `Nonterminal` and `TokenKind::Interpolated` A third attempt at this; the first attempt was #96724 and the second was #114647. r? `@ghost`
2025-04-04Detect and provide suggestion for `&raw EXPR`Michael Goulet-1/+5
2025-04-04Implement `super let`.Mara Bos-6/+8
2025-04-02Impl `Copy` for `Token` and `TokenKind`.Nicholas Nethercote-1/+1
2025-04-02Remove `NtBlock`, `Nonterminal`, and `TokenKind::Interpolated`.Nicholas Nethercote-4/+6
`NtBlock` is the last remaining variant of `Nonterminal`, so once it is gone then `Nonterminal` can be removed as well.
2025-03-28Add the feature gate for the `super let` experiment.Mara Bos-1/+14
2025-03-25Remove now unreachable parse recovery codeLeón Orell Valerian Liehr-8/+2
StructLiteralNeedingParens is no longer reachable always giving precedence to StructLiteralNotAllowedHere. As an aside: The former error struct shouldn't've existed in the first place. We should've just used the latter in this branch.
2025-03-24Remove fields that are dead since the removal of type ascription syntaxLeón Orell Valerian Liehr-8/+1
Since `{ ident: ident }` is a parse error, these fields are dead.
2025-03-17If a label is placed on the block of a loop instead of the header, suggest ↵Zachary S-6/+16
moving it to the header.
2025-03-07Remove `NtItem` and `NtStmt`.Nicholas Nethercote-18/+42
This involves replacing `nt_pretty_printing_compatibility_hack` with `stream_pretty_printing_compatibility_hack`. The handling of statements in `transcribe` is slightly different to other nonterminal kinds, due to the lack of `from_ast` implementation for empty statements. Notable test changes: - `tests/ui/proc-macro/expand-to-derive.rs`: the diff looks large but the only difference is the insertion of a single invisible-delimited group around a metavar.
2025-03-03Rename `ast::TokenKind::Not` as `ast::TokenKind::Bang`.Nicholas Nethercote-1/+1
For consistency with `rustc_lexer::TokenKind::Bang`, and because other `ast::TokenKind` variants generally have syntactic names instead of semantic names (e.g. `Star` and `DotDot` instead of `Mul` and `Range`).
2025-03-03Replace `ast::TokenKind::BinOp{,Eq}` and remove `BinOpToken`.Nicholas Nethercote-2/+11
`BinOpToken` is badly named, because it only covers the assignable binary ops and excludes comparisons and `&&`/`||`. Its use in `ast::TokenKind` does allow a small amount of code sharing, but it's a clumsy factoring. This commit removes `ast::TokenKind::BinOp{,Eq}`, replacing each one with 10 individual variants. This makes `ast::TokenKind` more similar to `rustc_lexer::TokenKind`, which has individual variants for all operators. Although the number of lines of code increases, the number of chars decreases due to the frequent use of shorter names like `token::Plus` instead of `token::BinOp(BinOpToken::Plus)`.
2025-02-08Rustfmtbjorn3-8/+14
2024-12-21Do not suggest `foo.Bar`Esteban Küber-1/+6
2024-12-21Account for missing `.` in macros to avoid incorrect suggestionEsteban Küber-0/+4
2024-12-21Detect missing `.` in method chain in let bindings and statementsEsteban Küber-2/+44
On parse errors where an ident is found where one wasn't expected, see if the next elements might have been meant as method call or field access. ``` error: expected one of `.`, `;`, `?`, `else`, or an operator, found `map` --> $DIR/missing-dot-on-statement-expression.rs:7:29 | LL | let _ = [1, 2, 3].iter()map(|x| x); | ^^^ expected one of `.`, `;`, `?`, `else`, or an operator | help: you might have meant to write a method call | LL | let _ = [1, 2, 3].iter().map(|x| x); | + ```
2024-12-19Speed up `Parser::expected_token_types`.Nicholas Nethercote-14/+13
The parser pushes a `TokenType` to `Parser::expected_token_types` on every call to the various `check`/`eat` methods, and clears it on every call to `bump`. Some of those `TokenType` values are full tokens that require cloning and dropping. This is a *lot* of work for something that is only used in error messages and it accounts for a significant fraction of parsing execution time. This commit overhauls `TokenType` so that `Parser::expected_token_types` can be implemented as a bitset. This requires changing `TokenType` to a C-style parameterless enum, and adding `TokenTypeSet` which uses a `u128` for the bits. (The new `TokenType` has 105 variants.) The new types `ExpTokenPair` and `ExpKeywordPair` are now arguments to the `check`/`eat` methods. This is for maximum speed. The elements in the pairs are always statically known; e.g. a `token::BinOp(token::Star)` is always paired with a `TokenType::Star`. So we now compute `TokenType`s in advance and pass them in to `check`/`eat` rather than the current approach of constructing them on insertion into `expected_token_types`. Values of these pair types can be produced by the new `exp!` macro, which is used at every `check`/`eat` call site. The macro is for convenience, allowing any pair to be generated from a single identifier. The ident/keyword filtering in `expected_one_of_not_found` is no longer necessary. It was there to account for some sloppiness in `TokenKind`/`TokenType` comparisons. The existing `TokenType` is moved to a new file `token_type.rs`, and all its new infrastructure is added to that file. There is more boilerplate code than I would like, but I can't see how to make it shorter.
2024-12-18Re-export more `rustc_span::symbol` things from `rustc_span`.Nicholas Nethercote-2/+1
`rustc_span::symbol` defines some things that are re-exported from `rustc_span`, such as `Symbol` and `sym`. But it doesn't re-export some closely related things such as `Ident` and `kw`. So you can do `use rustc_span::{Symbol, sym}` but you have to do `use rustc_span::symbol::{Ident, kw}`, which is inconsistent for no good reason. This commit re-exports `Ident`, `kw`, and `MacroRulesNormalizedIdent`, and changes many `rustc_span::symbol::` qualifiers in `compiler/` to `rustc_span::`. This is a 200+ net line of code reduction, mostly because many files with two `use rustc_span` items can be reduced to one.
2024-11-30Eliminate precedence arithmetic from rustc_parseDavid Tolnay-2/+3
2024-11-16review comment: move logic to new methodEsteban Küber-88/+103
2024-11-16Reword suggestion messageEsteban Küber-2/+2
2024-11-16Increase accuracy of `if` condition misparse suggestionEsteban Küber-9/+89
Look at the expression that was parsed when trying to recover from a bad `if` condition to determine what was likely intended by the user beyond "maybe this was meant to be an `else` body". ``` error: expected `{`, found `map` --> $DIR/missing-dot-on-if-condition-expression-fixable.rs:4:30 | LL | for _ in [1, 2, 3].iter()map(|x| x) {} | ^^^ expected `{` | help: you might have meant to write a method call | LL | for _ in [1, 2, 3].iter().map(|x| x) {} | + ```
2024-09-22Reformat using the new identifier sorting from rustfmtMichael Goulet-18/+12
2024-09-18Add suggestions for expressions in patternsLieselotte-2/+8
2024-08-24Rollup merge of #128524 - ↵Trevor Gross-0/+5
chenyukang:yukang-fix-127930-invalid-outer-style-sugg, r=cjgillot Don't suggest turning crate-level attributes into outer style Fixes #127930
2024-08-16Overhaul token collection.Nicholas Nethercote-17/+45
This commit does the following. - Renames `collect_tokens_trailing_token` as `collect_tokens`, because (a) it's annoying long, and (b) the `_trailing_token` bit is less accurate now that its types have changed. - In `collect_tokens`, adds a `Option<CollectPos>` argument and a `UsePreAttrPos` in the return type of `f`. These are used in `parse_expr_force_collect` (for vanilla expressions) and in `parse_stmt_without_recovery` (for two different cases of expression statements). Together these ensure are enough to fix all the problems with token collection and assoc expressions. The changes to the `stringify.rs` test demonstrate some of these. - Adds a new test. The code in this test was causing an assertion failure prior to this commit, due to an invalid `NodeRange`. The extra complexity is annoying, but necessary to fix the existing problems.
2024-08-16Convert a bool to `Trailing`.Nicholas Nethercote-6/+7
This pre-existing type is suitable for use with the return value of the `f` parameter in `collect_tokens_trailing_token`. The more descriptive name will be useful because the next commit will add another boolean value to the return value of `f`.
2024-08-14Use `impl PartialEq<TokenKind> for Token` more.Nicholas Nethercote-2/+2
This lets us compare a `Token` with a `TokenKind`. It's used a lot, but can be used even more, avoiding the need for some `.kind` uses.
2024-08-11Rollup merge of #128762 - fmease:use-more-slice-pats, r=compiler-errorsMatthias Krüger-3/+3
Use more slice patterns inside the compiler Nothing super noteworthy. Just replacing the common 'fragile' pattern of "length check followed by indexing or unwrap" with slice patterns for legibility and 'robustness'. r? ghost
2024-08-09parser: ensure let stmt compound assignment removal suggestion respect ↵许杰友 Jieyou Xu (Joe)-2/+6
codepoint boundaries Previously we would try to issue a suggestion for `let x <op>= 1`, i.e. a compound assignment within a `let` binding, to remove the `<op>`. The suggestion code unfortunately incorrectly assumed that the `<op>` is an exactly-1-byte ASCII character, but this assumption is incorrect because we also recover Unicode-confusables like `➖=` as `-=`. In this example, the suggestion code used a `+ BytePos(1)` to calculate the span of the `<op>` codepoint that looks like `-` but the mult-byte Unicode look-alike would cause the suggested removal span to be inside a multi-byte codepoint boundary, triggering a codepoint boundary assertion. Issue: <https://github.com/rust-lang/rust/issues/128845>
2024-08-07Use more slice patterns inside the compilerLeón Orell Valerian Liehr-3/+3
2024-08-04don't suggest turning crate-level attributes into outer styleyukang-0/+5
2024-08-01Move a comment to a better spot.Nicholas Nethercote-2/+1
2024-07-31Remove `LhsExpr`.Nicholas Nethercote-4/+2
`parse_expr_assoc_with` has an awkward structure -- sometimes the lhs is already parsed. This commit splits the post-lhs part into a new method `parse_expr_assoc_rest_with`, which makes everything shorter and simpler.
2024-07-31Inline and remove `parse_local_mk`.Nicholas Nethercote-16/+6
It has a single use. This makes the `let` handling case in `parse_stmt_without_recovery` more similar to the statement path and statement expression cases.
2024-07-29Reformat `use` declarations.Nicholas Nethercote-17/+17
The previous commit updated `rustfmt.toml` appropriately. This commit is the outcome of running `x fmt --all` with the new formatting options.
2024-07-19Only check `force_collect` in `collect_tokens_trailing_token`.Nicholas Nethercote-16/+17
There are three places where we currently check `force_collect` and call `collect_tokens_no_attrs` for `ForceCollect::Yes` and a vanilla parsing function for `ForceCollect::No`. But we can instead just pass in `force_collect` and let `collect_tokens_trailing_token` do the appropriate thing.
2024-07-19Don't always force collect tokens in `recover_stmt_local_after_let`.Nicholas Nethercote-6/+9
Use a parameter to decide whether to force collect, as is done for the closely related `parse_local_mk` method.
2024-07-18Remove `TrailingToken`.Nicholas Nethercote-16/+4
It's used in `Parser::collect_tokens_trailing_token` to decide whether to capture a trailing token. But the callers actually know whether to capture a trailing token, so it's simpler for them to just pass in a bool. Also, the `TrailingToken::Gt` case was weird, because it didn't result in a trailing token being captured. It could have been subsumed by the `TrailingToken::MaybeComma` case, and it effectively is in the new code.
2024-07-17Rollup merge of #127806 - nnethercote:parser-improvements, r=spastorinoTrevor Gross-2/+2
Some parser improvements I was looking closely at attribute handling in the parser while debugging some issues relating to #124141, and found a few small improvements. ``@spastorino``
2024-07-16Reorder `Parser::parse_expr_dot_or_call_with` arguments.Nicholas Nethercote-2/+2
Put `attrs` before `e0` because that matches the order in the source code, where outer attributes appear before expressions.
2024-07-12Make parse error suggestions verbose and fix spansEsteban Küber-3/+5
Go over all structured parser suggestions and make them verbose style. When suggesting to add or remove delimiters, turn them into multiple suggestion parts.
2024-06-19Refactor `parse_expr_res`.Nicholas Nethercote-2/+2
This removes the final `Option<AttrWrapper>` argument.