Commit Graph

736 Commits

Author SHA1 Message Date
Nadrieril 19e0c984d3 Don't gate the feature twice 2023-12-12 14:52:05 +01:00
Nicholas Nethercote 4cfdbd328b Add spacing information to delimiters.
This is an extension of the previous commit. It means the output of
something like this:
```
stringify!(let a: Vec<u32> = vec![];)
```
goes from this:
```
let a: Vec<u32> = vec![] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![];
```
2023-12-11 09:36:40 +11:00
Nicholas Nethercote 925f7fad57 Improve `print_tts` by changing `tokenstream::Spacing`.
`tokenstream::Spacing` appears on all `TokenTree::Token` instances,
both punct and non-punct. Its current usage:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `Alone` means "cannot join with the next token *or* can join with the
  next token but that token is not a punct".

The fact that `Alone` is used for two different cases is awkward.
This commit augments `tokenstream::Spacing` with a new variant
`JointHidden`, resulting in:
- `Joint` means "can join with the next token *and* that token is a
  punct".
- `JointHidden` means "can join with the next token *and* that token is a
  not a punct".
- `Alone` means "cannot join with the next token".

This *drastically* improves the output of `print_tts`. For example,
this:
```
stringify!(let a: Vec<u32> = vec![];)
```
currently produces this string:
```
let a : Vec < u32 > = vec! [] ;
```
With this PR, it now produces this string:
```
let a: Vec<u32> = vec![] ;
```
(The space after the `]` is because `TokenTree::Delimited` currently
doesn't have spacing information. The subsequent commit fixes this.)

The new `print_tts` doesn't replicate original code perfectly. E.g.
multiple space characters will be condensed into a single space
character. But it's much improved.

`print_tts` still produces the old, uglier output for code produced by
proc macros. Because we have to translate the generated code from
`proc_macro::Spacing` to the more expressive `token::Spacing`, which
results in too much `proc_macro::Along` usage and no
`proc_macro::JointHidden` usage. So `space_between` still exists and
is used by `print_tts` in conjunction with the `Spacing` field.

This change will also help with the removal of `Token::Interpolated`.
Currently interpolated tokens are pretty-printed nicely via AST pretty
printing. `Token::Interpolated` removal will mean they get printed with
`print_tts`. Without this change, that would result in much uglier
output for code produced by decl macro expansions. With this change, AST
pretty printing and `print_tts` produce similar results.

The commit also tweaks the comments on `proc_macro::Spacing`. In
particular, it refers to "compound tokens" rather than "multi-char
operators" because lifetimes aren't operators.
2023-12-11 09:19:09 +11:00
surechen 40ae34194c remove redundant imports
detects redundant imports that can be eliminated.

for #117772 :

In order to facilitate review and modification, split the checking code and
removing redundant imports code into two PR.
2023-12-10 10:56:22 +08:00
Michael Goulet 8361a7288e Introduce closure_id method on CoroutineKind 2023-12-08 21:46:39 +00:00
bors f967532a47 Auto merge of #118420 - compiler-errors:async-gen, r=eholk
Introduce support for `async gen` blocks

I'm delighted to demonstrate that `async gen` block are not very difficult to support. They're simply coroutines that yield `Poll<Option<T>>` and return `()`.

**This PR is WIP and in draft mode for now** -- I'm mostly putting it up to show folks that it's possible. This PR needs a lang-team experiment associated with it or possible an RFC, since I don't think it falls under the jurisdiction of the `gen` RFC that was recently authored by oli (https://github.com/rust-lang/rfcs/pull/3513, https://github.com/rust-lang/rust/issues/117078).

### Technical note on the pre-generator-transform yield type:

The reason that the underlying coroutines yield `Poll<Option<T>>` and not `Poll<T>` (which would make more sense, IMO, for the pre-transformed coroutine), is because the `TransformVisitor` that is used to turn coroutines into built-in state machine functions would have to destructure and reconstruct the latter into the former, which requires at least inserting a new basic block (for a `switchInt` terminator, to match on the `Poll` discriminant).

This does mean that the desugaring (at the `rustc_ast_lowering` level) of `async gen` blocks is a bit more involved. However, since we already need to intercept both `.await` and `yield` operators, I don't consider it much of a technical burden.

r? `@ghost`
2023-12-08 19:13:57 +00:00
Michael Goulet a208bae00e Support async gen fn 2023-12-08 17:23:26 +00:00
Michael Goulet 2806c2df7b coro_kind -> coroutine_kind 2023-12-08 17:23:25 +00:00
Michael Goulet 96bb542a31 Implement `async gen` blocks 2023-12-08 17:23:25 +00:00
bors 2b399b5275 Auto merge of #118527 - Nadrieril:never_patterns_parse, r=compiler-errors
never_patterns: Parse match arms with no body

Never patterns are meant to signal unreachable cases, and thus don't take bodies:
```rust
let ptr: *const Option<!> = ...;
match *ptr {
    None => { foo(); }
    Some(!),
}
```
This PR makes rustc accept the above, and enforces that an arm has a body xor is a never pattern. This affects parsing of match arms even with the feature off, so this is delicate. (Plus this is my first non-trivial change to the parser).

~~The last commit is optional; it introduces a bit of churn to allow the new suggestions to be machine-applicable. There may be a better solution? I'm not sure.~~ EDIT: I removed that commit

r? `@compiler-errors`
2023-12-08 17:08:52 +00:00
Eric Holk 50ef8006eb
Address code review feedback 2023-12-04 14:33:46 -08:00
Eric Holk f9d1f922dc
Option<CoroutineKind> 2023-12-04 13:03:37 -08:00
Eric Holk 48d5f1f0f2
Merge Async and Gen into CoroutineKind 2023-12-04 12:48:01 -08:00
Eric Holk bc0d10d4b0
Add genness to FnHeader 2023-12-04 11:22:49 -08:00
Nadrieril a2dcb3a6d9 Disallow an arm without a body (except for never patterns)
Parsing now accepts a match arm without a body, so we must make sure to
only accept that if the pattern is a never pattern.
2023-12-03 12:25:46 +01:00
Nadrieril 80bdcbf50a Parse a pattern with no arm 2023-12-03 12:25:46 +01:00
bors 4e3dc976e7 Auto merge of #117912 - GeorgeWort:master, r=petrochenkov
Name explicit registers in conflict register errors for inline assembly
2023-12-02 13:38:47 +00:00
Matthias Krüger c03f8917ee
Rollup merge of #118157 - Nadrieril:never_pat-feature-gate, r=compiler-errors
Add `never_patterns` feature gate

This PR adds the feature gate and most basic parsing for the experimental `never_patterns` feature. See the tracking issue (https://github.com/rust-lang/rust/issues/118155) for details on the experiment.

`@scottmcm` has agreed to be my lang-team liaison for this experiment.
2023-11-29 12:34:47 +01:00
Matthias Krüger 20473eba0b
Rollup merge of #118394 - nnethercote:rm-hir-Ops, r=cjgillot
Remove HIR opkinds

`hir::BinOp`, `hir::BinOpKind`, and `hir::UnOp` are identical to `ast::BinOp`, `ast::BinOpKind`, and `ast::UnOp`, respectively. This seems silly, so this PR removes the HIR ones. (A re-export lets the AST ones be referred to using a `hir::` qualifier, which avoids renaming churn.)

r? `@cjgillot`
2023-11-29 04:23:23 +01:00
Nadrieril a3838c8550 Add `never_patterns` feature gate 2023-11-29 03:58:29 +01:00
George Wort e0bfb615da Name explicit registers in conflict register errors for inline assembly 2023-11-28 10:37:19 +00:00
Nicholas Nethercote d9fef774e3 Remove `hir::BinOp`, `hir::BinOpKind`, and `hir::UnOp`.
They're identical to the same-named types from `ast`. I find it silly
(and inefficient) to have all this boilerplate code to convert one type
to an identical type.

There is already a small amount of type sharing between the AST and HIR,
e.g. `Attribute`, `MacroDef`.

The commit adds a `pub use` to `rustc_hir` so that, for example,
`ast::BinOp` can also be referred to as `hir::BinOp`. This is so the
many existing `hir`-qualified mentions of these types don't need to
change.

The commit also moves a couple of operations from the (removed) HIR
types to the AST types, e.g. `is_by_value`.
2023-11-28 12:14:25 +11:00
Nicholas Nethercote 705b484922 Rename `BinOpKind::lazy` as `BinOpKind::is_lazy`.
To match `BinOpKind::is_comparison` and `hir::BinOpKind::is_lazy`.
2023-11-28 09:45:40 +11:00
Nicholas Nethercote 0efd2a9d8f Rework `ast::BinOpKind::to_string` and `ast::UnOp::to_string`.
- Rename them both `as_str`, which is the typical name for a function
  that returns a `&str`. (`to_string` is appropriate for functions
  returning `String` or maybe `Cow<'a, str>`.)
- Change `UnOp::as_str` from an associated function (weird!) to a
  method.
- Avoid needless `self` dereferences.
2023-11-28 09:42:07 +11:00
Hirochika Matsumoto e65c060d78 Detect Python-like slicing and suggest how to fix
Fix #108215
2023-11-27 21:48:10 +09:00
Deadbeef 16040a1628 Add `Span` to `TraitBoundModifier` 2023-11-24 14:32:05 +00:00
Nicholas Nethercote 7060fc8327 Replace `no_ord_impl` with `orderable`.
Similar to the previous commit, this replaces `newtype_index`'s opt-out
`no_ord_impl` attribute with the opt-in `orderable` attribute.
2023-11-22 18:38:17 +11:00
Nicholas Nethercote 3ef9d4d0ed Replace `custom_encodable` with `encodable`.
By default, `newtype_index!` types get a default `Encodable`/`Decodable`
impl. You can opt out of this with `custom_encodable`. Opting out is the
opposite to how Rust normally works with autogenerated (derived) impls.

This commit inverts the behaviour, replacing `custom_encodable` with
`encodable` which opts into the default `Encodable`/`Decodable` impl.
Only 23 of the 59 `newtype_index!` occurrences need `encodable`.

Even better, there were eight crates with a dependency on
`rustc_serialize` just from unused default `Encodable`/`Decodable`
impls. This commit removes that dependency from those eight crates.
2023-11-22 18:37:14 +11:00
Nilstrieb 21a870515b Fix `clippy::needless_borrow` in the compiler
`x clippy compiler -Aclippy::all -Wclippy::needless_borrow --fix`.

Then I had to remove a few unnecessary parens and muts that were exposed
now.
2023-11-21 20:13:40 +01:00
Michael Goulet 426bc70ad6 Add HashStable_NoContext to simplify HashStable implementations in rustc_type_ir 2023-11-21 05:49:44 +00:00
bors 2831701757 Auto merge of #114292 - estebank:issue-71039, r=b-naber
More detail when expecting expression but encountering bad macro argument

On nested macro invocations where the same macro fragment changes fragment type from one to the next, point at the chain of invocations and at the macro fragment definition place, explaining that the change has occurred.

Fix #71039.

```
error: expected expression, found pattern `1 + 1`
  --> $DIR/trace_faulty_macros.rs:49:37
   |
LL |     (let $p:pat = $e:expr) => {test!(($p,$e))};
   |                   -------                -- this is interpreted as expression, but it is expected to be pattern
   |                   |
   |                   this macro fragment matcher is expression
...
LL |     (($p:pat, $e:pat)) => {let $p = $e;};
   |               ------                ^^ expected expression
   |               |
   |               this macro fragment matcher is pattern
...
LL |     test!(let x = 1+1);
   |     ------------------
   |     |             |
   |     |             this is expected to be expression
   |     in this macro invocation
   |
   = note: when forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type, not the underlying tokens
   = note: this error originates in the macro `test` (in Nightly builds, run with -Z macro-backtrace for more info)
```
2023-11-17 20:57:12 +00:00
Matthias Krüger 92aba63d6b
Rollup merge of #117892 - estebank:fat-arrow-typo, r=compiler-errors
Detect more `=>` typos

Handle and recover `match expr { pat >= { arm } }`.
2023-11-17 00:41:22 +01:00
Esteban Küber 4e418805da More detail when expecting expression but encountering bad macro argument
Partially address #71039.
2023-11-16 16:19:04 +00:00
Mark Rousskov db3e2bacb6 Bump cfg(bootstrap)s 2023-11-15 19:41:28 -05:00
Esteban Küber f830fe313b Detect more `=>` typos
Handle and recover `match expr { pat >= { arm } }`.
2023-11-14 00:46:37 +00:00
Sleep_AllDay 8c0ae83723
Fix comment
Gt => Greater than => `>`
Ge => Greater equal => `>=`
2023-11-13 13:15:55 +08:00
Dinu Blanovschi 876f698790 Add the vis.visit_capture_by() in noop_visit_expr 2023-11-04 21:11:03 +01:00
Dinu Blanovschi 54ce0346c0 add `fn visit_capture_by` to MutVisitor and fix pprust-expr-roundtrip.rs 2023-11-04 21:04:54 +01:00
Dinu Blanovschi df85b28b72 fixes for rustfmt + ast visitor 2023-11-04 20:39:15 +01:00
Dinu Blanovschi 8de489918b feat(hir): Store the `Span` of the `move` keyword 2023-11-04 19:39:32 +01:00
Nicholas Nethercote 8ff624a9f2 Clean up `rustc_*/Cargo.toml`.
- Sort dependencies and features sections.
- Add `tidy` markers to the sorted sections so they stay sorted.
- Remove empty `[lib`] sections.
- Remove "See more keys..." comments.

Excluded files:
- rustc_codegen_{cranelift,gcc}, because they're external.
- rustc_lexer, because it has external use.
- stable_mir, because it has external use.
2023-10-30 08:46:02 +11:00
bors 2cad938a81 Auto merge of #116447 - oli-obk:gen_fn, r=compiler-errors
Implement `gen` blocks in the 2024 edition

Coroutines tracking issue https://github.com/rust-lang/rust/issues/43122
`gen` block tracking issue https://github.com/rust-lang/rust/issues/117078

This PR implements `gen` blocks that implement `Iterator`. Most of the logic with `async` blocks is shared, and thus I renamed various types that were referring to `async` specifically.

An example usage of `gen` blocks is

```rust
fn foo() -> impl Iterator<Item = i32> {
    gen {
        yield 42;
        for i in 5..18 {
            if i.is_even() { continue }
            yield i * 2;
        }
    }
}
```

The limitations (to be resolved) of the implementation are listed in the tracking issue
2023-10-29 00:03:52 +00:00
Oli Scherer 621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
Matthias Krüger a8f7acd8f8
Rollup merge of #117114 - nnethercote:improve-stringify-test, r=petrochenkov
Improve `stringify.rs` test

Best reviewed one commit at a time.

r? `@petrochenkov`
2023-10-26 22:26:11 +02:00
Oli Scherer a61cf673cd Reserve `gen` keyword for `gen {}` blocks and `gen fn` in 2024 edition 2023-10-26 06:49:17 +00:00
Nicholas Nethercote 2e2e7806ab Augment `stringify.rs` test.
By adding tests (or placeholders, or comments) for missing AST variants.
2023-10-24 16:00:45 +11:00
bohan 482275b194 use visibility to check unused imports and delete some stmts 2023-10-22 21:27:46 +08:00
Michael Goulet e8e9f6a32a Uplift movability and mutability, the simple way 2023-10-19 16:42:58 +00:00
bors a48396984a Auto merge of #116688 - compiler-errors:rustfmt-up, r=WaffleLapkin,Nilstrieb
Format all the let-chains in compiler crates

Since rust-lang/rustfmt#5910 has landed, soon we will have support for formatting let-chains (as soon as rustfmt syncs and beta gets bumped).

This PR applies the changes [from master rustfmt to rust-lang/rust eagerly](https://rust-lang.zulipchat.com/#narrow/stream/122651-general/topic/out.20formatting.20of.20prs/near/374997516), so that the next beta bump does not have to deal with a 200+ file diff and can remain concerned with other things like `cfg(bootstrap)` -- #113637 was a pain to land, for example, because of let-else.

I will also add this commit to the ignore list after it has landed.

The commands that were run -- I'm not great at bash-foo, but this applies rustfmt to every compiler crate, and then reverts the two crates that should probably be formatted out-of-tree.
```
~/rustfmt $ ls -1d ~/rust/compiler/* | xargs -I@ cargo run --bin rustfmt -- `@/src/lib.rs` --config-path ~/rust --edition=2021 # format all of the compiler crates
~/rust $ git checkout HEAD -- compiler/rustc_codegen_{gcc,cranelift} # revert changes to cg-gcc and cg-clif
```

cc `@rust-lang/rustfmt`
r? `@WaffleLapkin` or `@Nilstrieb` who said they may be able to review this purely mechanical PR :>

cc `@Mark-Simulacrum` and `@petrochenkov,` who had some thoughts on the order of operations with big formatting changes in https://github.com/rust-lang/rust/pull/95262#issue-1178993801. I think the situation has changed since then, given that let-chains support exists on master rustfmt now, and I'm fairly confident that this formatting PR should land even if *bootstrap* rustfmt doesn't yet format let-chains in order to lessen the burden of the next beta bump.
2023-10-15 13:23:55 +00:00
Matthias Krüger 6fef4f089f
Rollup merge of #116696 - c410-f3r:in-doc, r=petrochenkov
Misc improvements

cc https://github.com/rust-lang/rust/pull/116323#discussion_r1355282195

r? `@petrochenkov`
2023-10-14 13:36:28 +02:00