about summary refs log tree commit diff
path: root/compiler/rustc_parse/src/parser/expr.rs
AgeCommit message (Collapse)AuthorLines
2025-04-02Fix problem causing `rusqlite` compilation to OOM.Nicholas Nethercote-1/+3
This makes the expression re-parsing more like how it's originally done in `parse_nonterminal`.
2025-04-02Remove `Token::uninterpolated_span`.Nicholas Nethercote-7/+7
In favour of the similar method on `Parser`, which works on things other than identifiers and lifetimes.
2025-04-02Remove `NtExpr` and `NtLiteral`.Nicholas Nethercote-80/+140
Notes about tests: - tests/ui/rfcs/rfc-2294-if-let-guard/feature-gate.rs: some messages are now duplicated due to repeated parsing. - tests/ui/rfcs/rfc-2497-if-let-chains/disallowed-positions.rs: ditto. - `tests/ui/proc-macro/macro-rules-derive-cfg.rs`: the diff looks large but the only difference is the insertion of a single invisible-delimited group around a metavar. - `tests/ui/attributes/nonterminal-expansion.rs`: a slight span degradation, somehow related to the recent massive attr parsing rewrite (#135726). I couldn't work out exactly what is going wrong, but I don't think it's worth holding things up for a single slightly suboptimal error message.
2025-03-31Rollup merge of #138749 - compiler-errors:closure-recovery, r=fmeaseMatthias Krüger-9/+52
Fix closure recovery for missing block when return type is specified Firstly, fix the `is_array_like_block` condition to make sure we're actually recovering a mistyped *block* rather than some other delimited expression. This fixes #138748. Secondly, split out the recovery of missing braces on a closure body into a separate recovery. Right now, the suggestion `"you might have meant to write this as part of a block"` originates from `suggest_fixes_misparsed_for_loop_head`, which feels kinda brittle and coincidental since AFAICT that recovery wasn't ever really intended to fix this. We also can make this `MachineApplicable` in this case. Fixes #138748 r? `@fmease` or reassign if you're busy/don't wanna review this
2025-03-25Remove now unreachable parse recovery codeLeón Orell Valerian Liehr-1/+1
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-25Brace-ident-colon can certainly no longer start a blockLeón Orell Valerian Liehr-12/+2
thanks to the removal of type ascription.
2025-03-20Make dedicated recovery for missing braces on closure with returnMichael Goulet-6/+47
2025-03-20Fix diagnostic struct typo, make sure is_array_like_block checks that it's a ↵Michael Goulet-3/+5
block
2025-03-20Rollup merge of #138435 - eholk:prefix-yield, r=oli-obkMatthias Krüger-1/+11
Add support for postfix yield expressions We've been having a discussion about whether we want postfix yield, or want to stick with prefix yield, or have both. I figured it's easy enough to support both for now and let us play around with them while the feature is still experimental. This PR treats `yield x` and `x.yield` as semantically equivalent. There was a suggestion to make `yield x` have a `()` type (so it only works in coroutines with `Resume = ()`. I think that'd be worth trying, either in a later PR, or before this one merges, depending on people's opinions. #43122
2025-03-18Refactor YieldKind so postfix yield must have an expressionEric Holk-4/+5
2025-03-18Apply suggestions from code reviewEric Holk-1/+1
Co-authored-by: Travis Cross <tc@traviscross.com>
2025-03-17Teach rustfmt to handle postfix yieldEric Holk-3/+2
This involved fixing the span when parsing .yield
2025-03-17If a label is placed on the block of a loop instead of the header, suggest ↵Zachary S-11/+25
moving it to the header.
2025-03-14Preserve yield position during pretty printingEric Holk-3/+6
2025-03-14Add support for postfix yield expressionsEric Holk-0/+7
We had a discussion[1] today about whether postfix yield would make sense. It's easy enough to support both in the parser, so we might as well have both and see how people use it while the feature is experimental. [1]: https://rust-lang.zulipchat.com/#narrow/channel/481571-t-lang.2Fgen/topic/postfix-yield/with/505231568
2025-03-14Make `Parser::parse_expr_cond` public.Moritz Hedtke-1/+2
This allows usage in rustfmt and rustfmt forks.
2025-03-12Auto merge of #138083 - nnethercote:rm-NtItem-NtStmt, r=petrochenkovbors-2/+1
Remove `NtItem` and `NtStmt` Another piece of #124141. r? `@petrochenkov`
2025-03-07Remove `NtItem` and `NtStmt`.Nicholas Nethercote-2/+1
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-06Use closure parse codeSantiago Pastorino-2/+13
2025-03-06Implement .use keyword as an alias of cloneSantiago Pastorino-0/+15
2025-03-04Auto merge of #137959 - matthiaskrgr:rollup-62vjvwr, r=matthiaskrgrbors-22/+18
Rollup of 12 pull requests Successful merges: - #135767 (Future incompatibility warning `unsupported_fn_ptr_calling_conventions`: Also warn in dependencies) - #137852 (Remove layouting dead code for non-array SIMD types.) - #137863 (Fix pretty printing of unsafe binders) - #137882 (do not build additional stage on compiler paths) - #137894 (Revert "store ScalarPair via memset when one side is undef and the other side can be memset") - #137902 (Make `ast::TokenKind` more like `lexer::TokenKind`) - #137921 (Subtree update of `rust-analyzer`) - #137922 (A few cleanups after the removal of `cfg(not(parallel))`) - #137939 (fix order on shl impl) - #137946 (Fix docker run-local docs) - #137955 (Always allow rustdoc-json tests to contain long lines) - #137958 (triagebot.toml: Don't label `test/rustdoc-json` as A-rustdoc-search) r? `@ghost` `@rustbot` modify labels: rollup
2025-03-03Rollup merge of #134900 - dtolnay:unoprange, r=compiler-errors,davidtwcoMatthias Krüger-1/+5
Fix parsing of ranges after unary operators Fixes https://github.com/rust-lang/rust/issues/134899. This PR aligns the parsing for unary `!` and `-` and `*` with how unary `&` is already parsed [here](https://github.com/rust-lang/rust/blob/5c0a6e68cfdad859615c2888de76505f13e6f01b/compiler/rustc_parse/src/parser/expr.rs#L848-L854).
2025-03-03Rename `ast::TokenKind::Not` as `ast::TokenKind::Bang`.Nicholas Nethercote-2/+2
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-20/+16
`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-28Auto merge of #137517 - nnethercote:rm-NtPat-NtItem-NtStmt, r=petrochenkovbors-6/+6
Remove `NtPat`, `NtMeta`, and `NtPath` Another part of #124141. r? `@petrochenkov`
2025-02-28Remove `NtPath`.Nicholas Nethercote-6/+6
2025-02-27Rename `AssocOp::As` as `AssocOp::Cast`.Nicholas Nethercote-2/+2
To match `ExprKind::Cast`, and because a semantic name makes more sense here than a syntactic name.
2025-02-27Replace `AssocOp::DotDot{,Eq}` with `AssocOp::Range`.Nicholas Nethercote-9/+6
It makes `AssocOp` more similar to `ExprKind` and makes things a little simpler. And the semantic names make more sense here than the syntactic names.
2025-02-27Introduce `AssocOp::Binary`.Nicholas Nethercote-42/+19
It mirrors `ExprKind::Binary`, and contains a `BinOpKind`. This makes `AssocOp` more like `ExprKind`. Note that the variants removed from `AssocOp` are all named differently to `BinOpToken`, e.g. `Multiply` instead of `Mul`, so that's an inconsistency removed. The commit adds `precedence` and `fixity` methods to `BinOpKind`, and calls them from the corresponding methods in `AssocOp`. This avoids the need to create an `AssocOp` from a `BinOpKind` in a bunch of places, and `AssocOp::from_ast_binop` is removed. `AssocOp::to_ast_binop` is also no longer needed. Overall things are shorter and nicer.
2025-02-27In `AssocOp::AssignOp`, use `BinOpKind` instead of `BinOpToken`Nicholas Nethercote-14/+2
`AssocOp::AssignOp` contains a `BinOpToken`. `ExprKind::AssignOp` contains a `BinOpKind`. Given that `AssocOp` is basically a cut-down version of `ExprKind`, it makes sense to make `AssocOp` more like `ExprKind`. Especially given that `AssocOp` and `BinOpKind` use semantic operation names (e.g. `Mul`, `Div`), but `BinOpToken` uses syntactic names (e.g. `Star`, `Slash`). This results in more concise code, and removes the need for various conversions. (Note that the removed functions `hirbinop2assignop` and `astbinop2assignop` are semantically identical, because `hir::BinOp` is just a synonum for `ast::BinOp`!) The only downside to this is that it allows the possibility of some nonsensical combinations, such as `AssocOp::AssignOp(BinOpKind::Lt)`. But `ExprKind::AssignOp` already has that problem. The problem can be fixed for both types in the future with some effort, by introducing an `AssignOpKind` type.
2025-02-23not lint break with label and unsafe blockMu001999-6/+8
2025-02-22Fix "missing match arm body" suggestion involving `!`Esteban Küber-1/+2
Include the match arm guard in the gated span, so that the suggestion to add a body is correct instead of inserting the body before the guard. Make the suggestion verbose. ``` error: `match` arm with no body --> $DIR/feature-gate-never_patterns.rs:43:9 | LL | Some(_) if false, | ^^^^^^^^^^^^^^^^ | help: add a body after the pattern | LL | Some(_) if false => { todo!() }, | ++++++++++++++ ```
2025-02-08Rustfmtbjorn3-18/+18
2025-01-30Rollup merge of #135882 - hkBst:master, r=estebankMatthias Krüger-3/+2
simplify `similar_tokens` from `Option<Vec<_>>` to `&[_]` All uses immediately invoke contains, so maybe a further simplification is possible.
2025-01-27Use identifiers in diagnostics more oftenMichael Goulet-1/+1
2025-01-23simplify similar_tokens from Vec<_> to &[_]Marijn Schouten-2/+2
2025-01-23simplify similar_tokens from Option<Vec<_>> to Vec<_>Marijn Schouten-2/+1
2025-01-19Run `clippy --fix` for `unnecessary_map_or` lintYotam Ofek-1/+1
2024-12-29Fix parsing of ranges after unary operatorsDavid Tolnay-1/+5
2024-12-20Change comparison operators to have Fixity::NoneDavid Tolnay-10/+2
2024-12-19Speed up `Parser::expected_token_types`.Nicholas Nethercote-157/+151
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-19Rename `Parser::expected_tokens` as `Parser::expected_token_types`.Nicholas Nethercote-1/+1
Because the `Token` type is similar to but different to the `TokenType` type, and the difference is important, so we want to avoid confusion.
2024-12-18Rollup merge of #134161 - nnethercote:overhaul-token-cursors, r=spastorino许杰友 Jieyou Xu (Joe)-1/+3
Overhaul token cursors Some nice cleanups here. r? `````@davidtwco`````
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-12-18Overhaul `TokenTreeCursor`.Nicholas Nethercote-1/+3
- Move it to `rustc_parse`, which is the only crate that uses it. This lets us remove all the `pub` markers from it. - Change `next_ref` and `look_ahead` to `get` and `bump`, which work better for the `rustc_parse` uses. - This requires adding a `TokenStream::get` method, which is simple. - In `TokenCursor`, we currently duplicate the `DelimSpan`/`DelimSpacing`/`Delimiter` from the surrounding `TokenTree::Delimited` in the stack. This isn't necessary so long as we don't prematurely move past the `Delimited`, and is a small perf win on a very hot code path. - In `parse_token_tree`, we clone the relevant `TokenTree::Delimited` instead of constructing an identical one from pieces.
2024-12-13Rollup merge of #134140 - compiler-errors:unsafe-binders-ast, r=oli-obkMatthias Krüger-2/+21
Add AST support for unsafe binders I'm splitting up #130514 into pieces. It's impossible for me to keep up with a huge PR like that. I'll land type system support for this next, probably w/o MIR lowering, which will come later. r? `@oli-obk` cc `@BoxyUwU` and `@lcnr` who also may want to look at this, though this PR doesn't do too much yet
2024-12-13Stabilize async closuresMichael Goulet-4/+1
2024-12-12Add unwrap_unsafe_binder and wrap_unsafe_binder macro operatorsMichael Goulet-2/+21
2024-12-11Don't emit "field expressions may not have generic arguments" if it's a ↵Orion Gonzalez-2/+5
method call without ()
2024-12-09Introduce `default_field_values` featureEsteban Küber-1/+1
Initial implementation of `#[feature(default_field_values]`, proposed in https://github.com/rust-lang/rfcs/pull/3681. Support default fields in enum struct variant Allow default values in an enum struct variant definition: ```rust pub enum Bar { Foo { bar: S = S, baz: i32 = 42 + 3, } } ``` Allow using `..` without a base on an enum struct variant ```rust Bar::Foo { .. } ``` `#[derive(Default)]` doesn't account for these as it is still gating `#[default]` only being allowed on unit variants. Support `#[derive(Default)]` on enum struct variants with all defaulted fields ```rust pub enum Bar { #[default] Foo { bar: S = S, baz: i32 = 42 + 3, } } ``` Check for missing fields in typeck instead of mir_build. Expand test with `const` param case (needs `generic_const_exprs` enabled). Properly instantiate MIR const The following works: ```rust struct S<A> { a: Vec<A> = Vec::new(), } S::<i32> { .. } ``` Add lint for default fields that will always fail const-eval We *allow* this to happen for API writers that might want to rely on users' getting a compile error when using the default field, different to the error that they would get when the field isn't default. We could change this to *always* error instead of being a lint, if we wanted. This will *not* catch errors for partially evaluated consts, like when the expression relies on a const parameter. Suggestions when encountering `Foo { .. }` without `#[feature(default_field_values)]`: - Suggest adding a base expression if there are missing fields. - Suggest enabling the feature if all the missing fields have optional values. - Suggest removing `..` if there are no missing fields.