Commit Graph

450 Commits

Author SHA1 Message Date
Nicholas Nethercote
41e4a3e086 Don't insert spaces before most semicolons in print_tts.
This gives better output for code produced by proc macros.
2024-01-22 20:14:59 +11:00
Lieselotte
7889e99b55
Add PatKind::Err 2024-01-17 03:14:16 +01:00
Bryanskiy
d69cd6473c Delegation implementation: step 1 2024-01-12 14:11:16 +03:00
bors
89e2160c4c Auto merge of #119105 - dtolnay:paren, r=WaffleLapkin
Fix parenthesization of subexprs containing statement boundary

This PR fixes a multitude of false negatives and false positives in the AST pretty printer's parenthesis insertion related to statement boundaries — statements which terminate unexpectedly early if there aren't parentheses.

Without this fix, the AST pretty printer (including both `stringify!` and `rustc -Zunpretty=expanded`) is prone to producing output which is not syntactically valid Rust. Invalid output is problematic because it means Rustfmt is unable to parse the output of `cargo expand`, for example, causing friction by forcing someone trying to debug a macro into reading poorly formatted code.

I believe the set of bugs fixed in this PR account for the most prevalent reason that `cargo expand` produces invalid output in real-world usage.

Fixes #98790.

## False negatives

The following is a correct program — `cargo check` succeeds.

```rust
macro_rules! m {
    ($e:expr) => {
        match () { _ => $e }
    };
}

fn main() {
    m!({ 1 } - 1);
}
```

But `rustc -Zunpretty=expanded main.rs` produces output that is invalid Rust syntax, because parenthesization is needed and not being done by the pretty printer.

```rust
fn main() { match () { _ => { 1 } - 1, }; }
```

Piping this expanded code to rustfmt, it fails to parse.

```console
error: unexpected `,` in pattern
 --> <stdin>:1:38
  |
1 | fn main() { match () { _ => { 1 } - 1, }; }
  |                                      ^
  |
help: try adding parentheses to match on a tuple...
  |
1 | fn main() { match () { _ => { 1 } (- 1,) }; }
  |                                   +    +
help: ...or a vertical bar to match on multiple alternatives
  |
1 | fn main() { match () { _ => { 1 } - 1 | }; }
  |                                   ~~~~~
```

Fixed output after this PR:

```rust
fn main() { match () { _ => ({ 1 }) - 1, }; }
```

## False positives

Less problematic, but worth fixing (just like #118726).

```rust
fn main() {
    let _ = match () { _ => 1 } - 1;
}
```

Output of `rustc -Zunpretty=expanded lib.rs` before this PR. There is no reason parentheses would need to be inserted there.

```rust
fn main() { let _ = (match () { _ => 1, }) - 1; }
```

After this PR:

```rust
fn main() { let _ = match () { _ => 1, } - 1; }
```

## Alternatives considered

In this PR I opted to parenthesize only the leading subexpression causing the statement boundary, rather than the entire statement. Example:

```rust
macro_rules! m {
    ($e:expr) => {
        $e
    };
}

fn main() {
    m!(loop { break [1]; }[0] - 1);
}
```

This PR produces the following pretty-printed contents for fn main:

```rust
(loop { break [1]; })[0] - 1;
```

A different equally correct output would be:

```rust
(loop { break [1]; }[0] - 1);
```

I chose the one I did because it is the *only* approach used by handwritten code in the standard library and compiler. There are 4 places where parenthesization is being used to prevent a statement boundary, and in all 4, the developer has chosen to parenthesize the smallest subexpression rather than the whole statement:

b37d43efd9/compiler/rustc_codegen_cranelift/example/alloc_system.rs (L102)

b37d43efd9/compiler/rustc_parse/src/errors.rs (L1021-L1029)

b37d43efd9/library/core/src/future/poll_fn.rs (L151)

b37d43efd9/library/core/src/ops/range.rs (L824-L828)
2023-12-27 21:27:26 +00:00
León Orell Valerian Liehr
3eb48a35c8
Introduce const Trait (always-const trait bounds) 2023-12-27 12:51:32 +01:00
Matthias Krüger
bdc4480914
Rollup merge of #119231 - aDotInTheVoid:PatKind-struct-bool-docs, r=compiler-errors
Clairify `ast::PatKind::Struct` presese of `..` by using an enum instead of a bool

The bool is mainly used for when a `..` is present, but it is also set on recovery to avoid errors. The doc comment not describes both of these cases.

See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.

r? ``@compiler-errors``
2023-12-23 16:23:54 +01:00
Alona Enraght-Moony
1349d86c72 bool->enum for ast::PatKind::Struct presence of ..
See cee794ee98/compiler/rustc_parse/src/parser/pat.rs (L890-L897) for the only place this is constructed.
2023-12-23 02:50:31 +00:00
Matthias Krüger
15dc9f5bee
Rollup merge of #119169 - fmease:pretty-yeet-syntactic-cruft, r=compiler-errors
Rid the AST & HIR pretty printer of cruft

Found while working on #119163.

For `trait Trait: ?Sized {}` (semantically malformed), we currently output `trait Trait for ? Sized {}` (sic!) / `trait Trait for ? Sized { }` (sic!) if `-Zunpretty=expanded` / `-Zunpretty=hir` is passed.

`trait Tr for Sized? {}` (#15521) and later also `trait Tr for ?Sized {}` (I guess, #20194) is former Rust syntax. Hence I'm removing these outdated branches.

~~This will conflict with #119163, therefore marking this PR as blocked.~~ Rebased
2023-12-22 19:01:26 +01:00
bors
208dd2032b Auto merge of #118847 - eholk:for-await, r=compiler-errors
Add support for `for await` loops

This adds support for `for await` loops. This includes parsing, desugaring in AST->HIR lowering, and adding some support functions to the library.

Given a loop like:
```rust
for await i in iter {
    ...
}
```
this is desugared to something like:
```rust
let mut iter = iter.into_async_iter();
while let Some(i) = loop {
    match core::pin::Pin::new(&mut iter).poll_next(cx) {
        Poll::Ready(i) => break i,
        Poll::Pending => yield,
    }
} {
    ...
}
```

This PR also adds a basic `IntoAsyncIterator` trait. This is partly for symmetry with the way `Iterator` and `IntoIterator` work. The other reason is that for async iterators it's helpful to have a place apart from the data structure being iterated over to store state. `IntoAsyncIterator` gives us a good place to do this.

I've gated this feature behind `async_for_loop` and opened #118898 as the feature tracking issue.

r? `@compiler-errors`
2023-12-22 14:17:10 +00:00
León Orell Valerian Liehr
b09889b959
Rid the AST & HIR pretty printers of syntactic cruft 2023-12-22 14:32:40 +01:00
bors
aaef5fe497 Auto merge of #119163 - fmease:refactor-ast-trait-bound-modifiers, r=compiler-errors
Refactor AST trait bound modifiers

Instead of having two types to represent trait bound modifiers in the parser / the AST (`parser::ty::BoundModifiers` & `ast::TraitBoundModifier`), only to map one to the other later, just use `parser::ty::BoundModifiers` (moved & renamed to `ast::TraitBoundModifiers`).

The struct type is more extensible and easier to deal with (see [here](https://github.com/rust-lang/rust/pull/119099/files#r1430749981) and [here](https://github.com/rust-lang/rust/pull/119099/files#r1430752116) for context) since it more closely models what it represents: A compound of two kinds of modifiers, constness and polarity. Modeling this as an enum (the now removed `ast::TraitBoundModifier`) meant one had to add a new variant per *combination* of modifier kind, which simply isn't scalable and which lead to a lot of explicit non-DRY matches.

NB: `hir::TraitBoundModifier` being an enum is fine since HIR doesn't need to worry representing invalid modifier kind combinations as those get rejected during AST validation thereby immensely cutting down the number of possibilities.
2023-12-22 02:00:55 +00:00
León Orell Valerian Liehr
5e4f12b41a
Refactor AST trait bound modifiers 2023-12-20 19:39:46 +01:00
Alona Enraght-Moony
11337805fb Give VariantData::Struct named fields, to clairfy recovered. 2023-12-20 00:07:34 +00:00
Eric Holk
27d6539a46
Plumb awaitness of for loops 2023-12-19 12:26:20 -08:00
David Tolnay
17239d9b64
Fix parenthesization of subexprs containing statement boundary 2023-12-18 22:40:48 -08:00
Ross Smyth
663bea5a96 Add better ICE messages for some undescriptive panics 2023-12-15 00:50:55 -05:00
Matthias Krüger
3a0562b93c
Rollup merge of #118726 - dtolnay:matchguardlet, r=compiler-errors
Do not parenthesize exterior struct lit inside match guards

Before this PR, the AST pretty-printer injects parentheses around expressions any time parens _could_ be needed depending on what else is in the code that surrounds that expression. But the pretty-printer did not pass around enough context to understand whether parentheses really _are_ needed on any particular expression. As a consequence, there are false positives where unneeded parentheses are being inserted.

Example:

```rust
#![feature(if_let_guard)]

macro_rules! pp {
    ($e:expr) => {
        stringify!($e)
    };
}

fn main() {
    println!("{}", pp!(match () { () if let _ = Struct {} => {} }));
}
```

**Before:**

```console
match () { () if let _ = (Struct {}) => {} }
```

**After:**

```console
match () { () if let _ = Struct {} => {} }
```

This PR introduces a bit of state that is passed across various expression printing methods to help understand accurately whether particular situations require parentheses injected by the pretty printer, and it fixes one such false positive involving match guards as shown above.

There are other parenthesization false positive cases not fixed by this PR. I intend to address these in follow-up PRs. For example here is one: the expression `{ let _ = match x {} + 1; }` is pretty-printed as `{ let _ = (match x {}) + 1; }` despite there being no reason for parentheses to appear there.
2023-12-11 20:46:49 +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
David Tolnay
8997215a24
Fix tidy ```ignore error
tidy error: /git/rust/compiler/rustc_ast_pretty/src/pprust/state.rs:1165: unexplained "```ignore" doctest; try one:

    * make the test actually pass, by adding necessary imports and declarations, or
    * use "```text", if the code is not Rust code, or
    * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
    * use "```should_panic", if the code is expected to fail at run time, or
    * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
    * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.

    tidy error: /git/rust/compiler/rustc_ast_pretty/src/pprust/state.rs:1176: unexplained "```ignore" doctest; try one:

    * make the test actually pass, by adding necessary imports and declarations, or
    * use "```text", if the code is not Rust code, or
    * use "```compile_fail,Ennnn", if the code is expected to fail at compile time, or
    * use "```should_panic", if the code is expected to fail at run time, or
    * use "```no_run", if the code should type-check but not necessary linkable/runnable, or
    * explain it like "```ignore (cannot-test-this-because-xxxx)", if the annotation cannot be avoided.
2023-12-08 15:15:44 -08:00
David Tolnay
6f1d7631fb
Do not parenthesize exterior struct lit inside match guards 2023-12-08 15:15:42 -08:00
David Tolnay
7f314acc34
Delete special handling of some expr kinds from print_let
In all four of Break, Closure, Ret, Yeet, the needs_par_as_let_scrutinee
is guaranteed to return true because the .precedence().order() of those
expr kinds is <= AssocOp::LAnd.precedence().

The relevant functions in rustc_ast::util::parser are:

    fn needs_par_as_let_scrutinee(order: i8) -> bool {
        order <= prec_let_scrutinee_needs_par() as i8
    }

    fn prec_let_scrutinee_needs_par() -> usize {
        AssocOp::LAnd.precedence()
    }

The .precedence().order() of Closure is PREC_CLOSURE (-40) and of Break,
Ret, Yeet is PREC_JUMP (-30).

The value of AssocOp::LAnd.precedence() is 6.

So this commit causes no change in behavior, only potentially
performance by doing a redundant call to contains_exterior_struct_lit in
those four cases. This is fine because Break, Closure, Ret, Yeet should
be exceedingly rare in the position of a let scrutinee.
2023-12-08 15:14:44 -08:00
David Tolnay
dc5ec724c0
Rearrange logic of needs_par computation in print_let
True || needs_par_as_let_scrutinee(...) is always true.
2023-12-08 15:14:44 -08:00
David Tolnay
8d64961589
Inline cond_needs_par into print_let 2023-12-08 15:14:44 -08:00
David Tolnay
d2b7bd4774
Inline npals closure 2023-12-08 15:14:44 -08: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
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
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
Nadrieril
80bdcbf50a Parse a pattern with no arm 2023-12-03 12:25:46 +01: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
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
Nicholas Nethercote
566df2722a Fix some backticks in comments. 2023-11-27 09:38:58 +11:00
Deadbeef
16040a1628 Add Span to TraitBoundModifier 2023-11-24 14:32:05 +00:00
bors
cc4bb0de20 Auto merge of #117928 - nnethercote:rustc_ast_pretty, r=fee1-dead
`rustc_ast_pretty` cleanups

Some improvements I found while looking at this code.

r? `@fee1-dead`
2023-11-22 05:09:33 +00:00
Nicholas Nethercote
9fe6bb4a10 Add some comments. 2023-11-22 11:06:16 +11:00
Nicholas Nethercote
10c8b56af1 Factor out common code in PrintState.
The AST and HIR versions of `State::print_ident` are textually
identical, but the types differ slightly. This commit factors out the
common code they both have by replacing `print_ident` with `ann_post`,
which is a smaller function that still captures the type difference.
2023-11-22 08:13:21 +11:00
Nicholas Nethercote
e16b52d4f0 Streamline PrintState.
`PrintState` is a trait containing code that can be used by both AST and
HIR pretty-printing. But several of its methods are only used by AST
printing.

This commit moves those methods out of the trait and into the AST
`State` impl, so they are not exposed unnecessarily. This commit also
removes four unused methods: `param_to_string`,
`foreign_item_to_string`, `assoc_item_to_string`, and
`print_inner_attributes_inline`.
2023-11-22 08:13:21 +11:00
Nicholas Nethercote
c6a9027102 Remove unused PrintState::generic_params_to_string method. 2023-11-22 08:13:21 +11:00
Nicholas Nethercote
d9443f71c7 Remove or downgrade unnecessary pub visibility markers. 2023-11-22 08:13:21 +11:00
Nicholas Nethercote
ce363bb6e6 Remove IterDelimited.
itertools has `with_position` which does the same thing.
2023-11-22 08:13:21 +11:00
Nicholas Nethercote
1d320ed387 Remove unnecessary derives. 2023-11-22 08:13:21 +11:00
Nicholas Nethercote
2f51f0b290 Remove unneeded features. 2023-11-22 08:13:21 +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
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
Nicholas Nethercote
783d4b8b26 Clarify space_between.
To avoid `!matches!(...)`, which is hard to think about. Instead every
case now uses direct pattern matching and returns true or false.

Also add a couple of cases to the `stringify.rs` test that currently
print badly.
2023-11-08 14:39:59 +11:00
Dinu Blanovschi
241a654c07 Fix remaining uses of CaptureBy::Value 2023-11-04 19:48:44 +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
Oli Scherer
621494382d Add gen blocks to ast and do some broken ast lowering 2023-10-27 13:05:48 +00:00
bors
631a116cd3 Auto merge of #116822 - notriddle:notriddle/rust-logo, r=fmease
docs: add Rust logo to more compiler crates

c6e6ecb1af added it to some of the compiler's crates, but avoided adding it to all of them to reduce bit-rot. This commit adds to more.

r? `@GuillaumeGomez`
2023-10-17 04:41:20 +00:00
Michael Howell
2ff2624722 docs: add Rust logo to more compiler crates
c6e6ecb1af added it to some of the
compiler's crates, but avoided adding it to all of them to reduce
bit-rot. This commit adds to more.
2023-10-16 15:38:08 -07:00
Paul Gey
587899e9ca Preserve unicode escapes in format string literals when pretty-printing AST 2023-10-16 21:20:21 +02:00
Nicholas Nethercote
66c2b77a4a Rename tt_prepend_space as space_between.
And reorder the arguments. I find it easier to think about this way.
2023-10-12 08:50:42 +11:00
Matthew Jasper
333388fd3c Move let expression checking to parsing
There was an incomplete version of the check in parsing and a second
version in AST validation. This meant that some, but not all, invalid
uses were allowed inside macros/disabled cfgs. It also means that later
passes have a hard time knowing when the let expression is in a valid
location, sometimes causing ICEs.

- Add a field to ExprKind::Let in AST/HIR to mark whether it's in a
  valid location.
- Suppress later errors and MIR construction for invalid let
  expressions.
2023-09-11 15:51:18 +00:00
bors
18be2728bd Auto merge of #115131 - frank-king:feature/unnamed-fields-lite, r=petrochenkov
Parse unnamed fields and anonymous structs or unions (no-recovery)

It is part of #114782 which implements #49804. Only parse anonymous structs or unions in struct field definition positions.

r? `@petrochenkov`
2023-08-24 12:52:35 +00:00
Frank King
868706d9b5 Parse unnamed fields and anonymous structs or unions
Anonymous structs or unions are only allowed in struct field
definitions.

Co-authored-by: carbotaniuman <41451839+carbotaniuman@users.noreply.github.com>
2023-08-24 11:17:54 +08:00
Nicholas Nethercote
3bb85b73b5 Add helpful comments to tt_prepend_space. 2023-08-17 09:01:05 +10:00
Nilstrieb
5706be1854 Improve spans for indexing expressions
Indexing is similar to method calls in having an arbitrary
left-hand-side and then something on the right, which is the main part
of the expression. Method calls already have a span for that right part,
but indexing does not. This means that long method chains that use
indexing have really bad spans, especially when the indexing panics and
that span in coverted into a panic location.

This does the same thing as method calls for the AST and HIR, storing an
extra span which is then put into the `fn_span` field in THIR.
2023-08-04 13:17:39 +02:00
Nicholas Nethercote
d75ee2a6bc Remove MacDelimiter.
It's the same as `Delimiter`, minus the `Invisible` variant. I'm
generally in favour of using types to make impossible states
unrepresentable, but this one feels very low-value, and the conversions
between the two types are annoying and confusing.

Look at the change in `src/tools/rustfmt/src/expr.rs` for an example:
the old code converted from `MacDelimiter` to `Delimiter` and back
again, for no good reason. This suggests the author was confused about
the types.
2023-08-03 09:03:30 +10:00
León Orell Valerian Liehr
afd009a8d8
Parse generic const items 2023-07-28 22:21:33 +02:00
Matthias Krüger
af2b370100 more clippy::style fixes:
get_first
single_char_add_str
unnecessary_mut_passed
manual_map
manual_is_ascii_check
2023-07-23 23:39:04 +02:00
Maybe Waffle
d7713feb99 Syntatically accept become expressions 2023-06-19 12:54:34 +00:00
许杰友 Jieyou Xu (Joe)
32ae8810fc
Fix suggestion for E0404 not dealing with multiple generics 2023-06-15 18:19:09 +08:00
est31
5eb29c7f49 Migrate offset_of from a macro to builtin # syntax 2023-05-05 21:44:13 +02:00
Dylan DPC
4891f02cff
Rollup merge of #108801 - fee1-dead-contrib:c-str, r=compiler-errors
Implement RFC 3348, `c"foo"` literals

RFC: https://github.com/rust-lang/rfcs/pull/3348
Tracking issue: #105723
2023-05-05 18:40:33 +05:30
Michael Goulet
6e01e910cb Implement negative bounds 2023-05-02 22:36:24 +00:00
Deadbeef
a49570fd20 fix TODO comments 2023-05-02 10:32:07 +00:00
Deadbeef
8ff3903643 initial step towards implementing C string literals 2023-05-02 10:30:09 +00:00
Nilstrieb
c63b6a437e Rip it out
My type ascription
Oh rip it out
Ah
If you think we live too much then
You can sacrifice diagnostics
Don't mix your garbage
Into my syntax
So many weird hacks keep diagnostics alive
Yet I don't even step outside
So many bad diagnostics keep tyasc alive
Yet tyasc doesn't even bother to survive!
2023-05-01 16:15:13 +08:00
Matthias Krüger
9de14d894b
Rollup merge of #111037 - Nilstrieb:close-the-offsetof, r=compiler-errors
Close parentheses for `offset_of` in AST pretty printing

HIR pretty printing already handles it correctly.

This will conflict with #110694 but it seems like that PR is gonna take bit more time.
2023-05-01 01:09:50 +02:00
Matthias Krüger
1b262b8b56
Rollup merge of #110823 - compiler-errors:tweak-await-span, r=b-naber
Tweak await span to not contain dot

Fixes a discrepancy between method calls and await expressions where the latter are desugared to have a span that *contains* the dot (i.e. `.await`) but method call identifiers don't contain the dot. This leads to weird suggestions suggestions in borrowck -- see linked issue.

Fixes #110761

This mostly touches a bunch of tests to tighten their `await` span.
2023-05-01 01:09:47 +02:00
Nilstrieb
0dbea7ad54 Close parentheses for offset_of in AST pretty printing
HIR pretty printing already handles it correctly.
2023-04-30 23:29:40 +02:00
Lukas Markeffsky
fc63926e18 remove unused muts 2023-04-28 20:19:48 +02:00
Michael Goulet
f0fc4f9acf Tweak await span 2023-04-27 17:18:11 +00:00
DrMeepster
3206960ec6 minor tweaks 2023-04-21 02:14:04 -07:00
DrMeepster
511e457c4b offset_of 2023-04-21 02:14:02 -07:00
Michael Goulet
24cbf81b85 Remove .. from return type notation 2023-04-10 22:19:46 +00:00
Nilstrieb
4b4948c2e3 Remove identity casts 2023-04-09 23:22:14 +02:00
Nilstrieb
81c320ea77 Fix some clippy::complexity 2023-04-09 23:22:14 +02:00
Oli Scherer
373807a95c Rename ast::Static to ast::StaticItem to match ast::ConstItem 2023-04-04 15:34:40 +00:00
Oli Scherer
4bebdd7104 box a bunch of large types 2023-04-04 13:58:50 +00:00
Oli Scherer
ec74653652 Split out ast::ItemKind::Const into its own struct 2023-04-04 09:44:50 +00:00
Oli Scherer
e3828777a6 rust-analyzer guided tuple field to named field 2023-04-04 09:44:50 +00:00
Oli Scherer
b08a557f80 rust-analyzer guided enum variant structification 2023-04-04 09:44:45 +00:00
Michael Goulet
8b592db27a Add (..) syntax for RTN 2023-03-28 01:14:28 +00:00
Arpad Borsos
c8ead2e693
Remove the NodeId of ast::ExprKind::Async 2023-03-19 19:01:31 +01:00
clubby789
0932452fa4 Remove box_syntax from AST and use in tools 2023-03-12 13:19:46 +00:00
bwmf2
832b33e6b1 Force parentheses around match expression in binary expression 2023-03-02 21:58:49 +01:00
Nicholas Nethercote
4143b101f9 Use ThinVec in various AST types.
This commit changes the sequence parsers to produce `ThinVec`, which
triggers numerous conversions.
2023-02-21 11:51:56 +11:00
Nicholas Nethercote
068db466e8 Use ThinVec in ast::WhereClause. 2023-02-21 11:51:55 +11:00
Nicholas Nethercote
dd7aff5cc5 Use ThinVec in ast::Generics and related types. 2023-02-21 11:51:55 +11:00
Michael Goulet
56bf28d4f4 Expand const-if-const trait bounds correctly 2023-02-07 21:00:12 +00:00
klensy
4f5f9f0a13 remove unused imports 2023-02-06 17:40:18 +03:00
Maybe Waffle
9fe8ae792e Rename rust_2015 => is_rust_2015 2023-02-02 08:17:13 +00:00
Maybe Waffle
fd5774a4d7 Use Edition methods a bit more 2023-01-31 10:09:22 +00:00
Mara Bos
0abf8a0617 Replace format flags u32 by enums and bools. 2023-01-27 08:53:39 +01:00
bors
3e97763872 Auto merge of #106745 - m-ou-se:format-args-ast, r=oli-obk
Move format_args!() into AST (and expand it during AST lowering)

Implements https://github.com/rust-lang/compiler-team/issues/541

This moves FormatArgs from rustc_builtin_macros to rustc_ast_lowering. For now, the end result is the same. But this allows for future changes to do smarter things with format_args!(). It also allows Clippy to directly access the ast::FormatArgs, making things a lot easier.

This change turns the format args types into lang items. The builtin macro used to refer to them by their path. After this change, the path is no longer relevant, making it easier to make changes in `core`.

This updates clippy to use the new language items, but this doesn't yet make clippy use the ast::FormatArgs structure that's now available. That should be done after this is merged.
2023-01-26 12:44:47 +00:00
Maybe Waffle
6a28fb42a8 Remove double spaces after dots in comments 2023-01-17 08:09:33 +00:00
Mara Bos
7b077307fd Fix ast_pretty for format_args for {:x?} and {:X?}.
They were accidentally swapped.
2023-01-14 14:16:26 +01:00
Mara Bos
0a1934a32c Add FIXME comments about asm and format_args ast_pretty. 2023-01-12 19:59:03 +01:00
Deadbeef
4fb10c0ce4 parse const closures 2023-01-12 02:28:37 +00:00
Mara Bos
a4dbcb525b Expand format_args!() in rust_ast_lowering. 2023-01-12 00:25:45 +01:00
nils
fd7a159710 Fix uninlined_format_args for some compiler crates
Convert all the crates that have had their diagnostic migration
completed (except save_analysis because that will be deleted soon and
apfloat because of the licensing problem).
2023-01-05 19:01:12 +01:00
Nilstrieb
9067e4417e Rename Rptr to Ref in AST and HIR
The name makes a lot more sense, and `ty::TyKind` calls it `Ref` already
as well.
2022-12-28 18:52:36 +01:00
bors
2cd2070af7 Auto merge of #105160 - nnethercote:rm-Lit-token_lit, r=petrochenkov
Remove `token::Lit` from `ast::MetaItemLit`.

Currently `ast::MetaItemLit` represents the literal kind twice. This PR removes that redundancy. Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-12 05:16:50 +00:00
Maybe Waffle
12ce0c2a89 Remove outdated syntax from trait alias pretty printing 2022-12-06 13:45:11 +00:00
Nicholas Nethercote
568e647047 Remove three uses of LitKind::synthesize_token_lit. 2022-12-05 16:33:20 +11:00
Matthias Krüger
1a2f79b82c
Rollup merge of #105050 - WaffleLapkin:uselessrefign, r=jyn514
Remove useless borrows and derefs

They are nothing more than noise.
<sub>These are not all of them, but my clippy started crashing (stack overflow), so rip :(</sub>
2022-12-03 17:37:42 +01:00
Matthias Krüger
c89bff29e5
Rollup merge of #104199 - SarthakSingh31:issue-97417-1, r=cjgillot
Keep track of the start of the argument block of a closure

This removes a call to `tcx.sess.source_map()` from [compiler/rustc_trait_selection/src/traits/error_reporting/mod.rs](https://github.com/rust-lang/rust/compare/master...SarthakSingh31:issue-97417-1?expand=1#diff-8406bbc0d0b43d84c91b1933305df896ecdba0d1f9269e6744f13d87a2ab268a) as required by #97417.

VsCode automatically applied `rustfmt` to the files I edited under `src/tools`. I can undo that if its a problem.

r? `@cjgillot`
2022-12-03 17:37:41 +01:00
Nicholas Nethercote
2fd364acff Remove token::Lit from ast::MetaItemLit.
`token::Lit` contains a `kind` field that indicates what kind of literal
it is. `ast::MetaItemLit` currently wraps a `token::Lit` but also has
its own `kind` field. This means that `ast::MetaItemLit` encodes the
literal kind in two different ways.

This commit changes `ast::MetaItemLit` so it no longer wraps
`token::Lit`. It now contains the `symbol` and `suffix` fields from
`token::Lit`, but not the `kind` field, eliminating the redundancy.
2022-12-02 13:49:19 +11:00
Nicholas Nethercote
a7f35c42d4 Add StrStyle to ast::LitKind::ByteStr.
This is required to distinguish between cooked and raw byte string
literals in an `ast::LitKind`, without referring to an adjacent
`token::Lit`. It's a prerequisite for the next commit.
2022-12-02 10:38:58 +11:00
Nicholas Nethercote
e658144586 Rename LitKind::to_token_lit as LitKind::synthesize_token_lit.
This makes it clearer that it's not a lossless conversion, which I find
helpful.
2022-12-02 10:23:44 +11:00
Maybe Waffle
f2b97a8bfe Remove useless borrows and derefs 2022-12-01 17:34:43 +00:00
Vadim Petrochenkov
b32a4edb20 rustc_ast_lowering: Stop lowering imports into multiple items
Lower them into a single item with multiple resolutions instead.
This also allows to remove additional `NodId`s and `DefId`s related to those additional items.
2022-12-01 18:51:20 +03:00
bors
d6c4de0fb2 Auto merge of #104861 - nnethercote:attr-cleanups, r=petrochenkov
Attribute cleanups

Best reviewed one commit at a time.

r? `@petrochenkov`
2022-12-01 07:13:45 +00:00
Waffle Maybe
1b4012e304
add FIXME: where it belongs
suggestion from a friend!! 🐸

Co-authored-by: Michael Goulet <michael@errs.io>
2022-11-29 22:01:49 +04:00
Maybe Waffle
56ae9a1746 rustc_ast_pretty: remove ref patterns 2022-11-29 08:10:59 +00:00
Nicholas Nethercote
ba1751a201 Avoid more MetaItem-to-Attribute conversions.
There is code for converting `Attribute` (syntactic) to `MetaItem`
(semantic). There is also code for the reverse direction. The reverse
direction isn't really necessary; it's currently only used when
generating attributes, e.g. in `derive` code.

This commit adds some new functions for creating `Attributes`s directly,
without involving `MetaItem`s: `mk_attr_word`, `mk_attr_name_value_str`,
`mk_attr_nested_word`, and
`ExtCtxt::attr_{word,name_value_str,nested_word}`.

These new methods replace the old functions for creating `Attribute`s:
`mk_attr_inner`, `mk_attr_outer`, and `ExtCtxt::attribute`. Those
functions took `MetaItem`s as input, and relied on many other functions
that created `MetaItems`, which are also removed: `mk_name_value_item`,
`mk_list_item`, `mk_word_item`, `mk_nested_word_item`,
`{MetaItem,MetaItemKind,NestedMetaItem}::token_trees`,
`MetaItemKind::attr_args`, `MetaItemLit::{from_lit_kind,to_token}`,
`ExtCtxt::meta_word`.

Overall this cuts more than 100 lines of code and makes thing simpler.
2022-11-29 18:43:53 +11:00
Sarthak Singh
8f705e2425 Keep track of the start of the argument block of a closure 2022-11-28 14:09:00 +05:30
Nicholas Nethercote
a60e337c88 Rename NestedMetaItem::[Ll]iteral as NestedMetaItem::[Ll]it.
We already use a mix of `Literal` and `Lit`. The latter is better
because it is shorter without causing any ambiguity.
2022-11-28 15:18:53 +11:00
Nicholas Nethercote
e4a9150872 Rename ast::Lit as ast::MetaItemLit. 2022-11-28 15:18:49 +11:00
Nicholas Nethercote
8cfc8153da Remove Lit::from_included_bytes.
`Lit::from_included_bytes` calls `Lit::from_lit_kind`, but the two call
sites only need the resulting `token::Lit`, not the full `ast::Lit`.

This commit changes those call sites to use `LitKind::to_token_lit`,
which means `from_included_bytes` can be removed.
2022-11-28 15:17:45 +11:00
Maybe Waffle
1d42936b18 Prefer doc comments over //-comments in compiler 2022-11-27 11:19:04 +00:00
Esteban Küber
9e72e35ceb Suggest .clone() or ref binding on E0382 2022-11-23 12:17:47 -08:00
Nicholas Nethercote
3e3a4192d8 Split MacArgs in two.
`MacArgs` is an enum with three variants: `Empty`, `Delimited`, and `Eq`. It's
used in two ways:
- For representing attribute macro arguments (e.g. in `AttrItem`), where all
  three variants are used.
- For representing function-like macros (e.g. in `MacCall` and `MacroDef`),
  where only the `Delimited` variant is used.

In other words, `MacArgs` is used in two quite different places due to them
having partial overlap. I find this makes the code hard to read. It also leads
to various unreachable code paths, and allows invalid values (such as
accidentally using `MacArgs::Empty` in a `MacCall`).

This commit splits `MacArgs` in two:
- `DelimArgs` is a new struct just for the "delimited arguments" case. It is
  now used in `MacCall` and `MacroDef`.
- `AttrArgs` is a renaming of the old `MacArgs` enum for the attribute macro
  case. Its `Delimited` variant now contains a `DelimArgs`.

Various other related things are renamed as well.

These changes make the code clearer, avoids several unreachable paths, and
disallows the invalid values.
2022-11-22 09:04:15 +11:00
Nicholas Nethercote
6b7ca2fcf2 Box ExprKind::{Closure,MethodCall}, and QSelf in expressions, types, and patterns. 2022-11-17 13:45:59 +11:00
Nicholas Nethercote
358a603f11 Use token::Lit in ast::ExprKind::Lit.
Instead of `ast::Lit`.

Literal lowering now happens at two different times. Expression literals
are lowered when HIR is crated. Attribute literals are lowered during
parsing.

This commit changes the language very slightly. Some programs that used
to not compile now will compile. This is because some invalid literals
that are removed by `cfg` or attribute macros will no longer trigger
errors. See this comment for more details:
https://github.com/rust-lang/rust/pull/102944#issuecomment-1277476773
2022-11-16 09:41:28 +11:00
clubby789
b2da155a9a Introduce ExprKind::IncludedBytes 2022-11-11 16:31:32 +00:00
Michael Goulet
d3bd6beb97 Rename AssocItemKind::TyAlias to AssocItemKind::Type 2022-10-10 02:31:37 +00:00
reez12g
9a4c5abe45 Remove from compiler/ crates 2022-09-29 16:49:04 +09:00
SparrowLii
1a3ecbdb6a make mk_attr_id part of ParseSess 2022-09-14 08:49:10 +08:00
bors
6c358c67d4 Auto merge of #101241 - camsteffen:refactor-binding-annotations, r=cjgillot
`BindingAnnotation` refactor

* `ast::BindingMode` is deleted and replaced with `hir::BindingAnnotation` (which is moved to `ast`)
* `BindingAnnotation` is changed from an enum to a tuple struct e.g. `BindingAnnotation(ByRef::No, Mutability::Mut)`
* Associated constants added for convenience `BindingAnnotation::{NONE, REF, MUT, REF_MUT}`

One goal is to make it more clear that `BindingAnnotation` merely represents syntax `ref mut` and not the actual binding mode. This was especially confusing since we had `ast::BindingMode`->`hir::BindingAnnotation`->`thir::BindingMode`.

I wish there were more symmetry between `ByRef` and `Mutability` (variant) naming (maybe `Mutable::Yes`?), and I also don't love how long the name `BindingAnnotation` is, but this seems like the best compromise. Ideas welcome.
2022-09-06 03:16:29 +00:00
Michael Goulet
e9b01c745d Fix global_asm macro pretty printing 2022-09-03 08:06:35 +00:00
Cameron Steffen
02ba216e3c Refactor and re-use BindingAnnotation 2022-09-02 12:55:05 -05:00
5225225
09ea9f0a87 Add diagnostic translation lints to crates that don't emit them 2022-08-18 19:29:02 +01:00
Matthias Krüger
d5dca26a94
Rollup merge of #100018 - nnethercote:clean-up-LitKind, r=petrochenkov
Clean up `LitKind`

r? ``@petrochenkov``
2022-08-17 12:32:49 +02:00
Nicholas Nethercote
5d3cc1713a Rename some things related to literals.
- Rename `ast::Lit::token` as `ast::Lit::token_lit`, because its type is
  `token::Lit`, which is not a token. (This has been confusing me for a
  long time.)
  reasonable because we have an `ast::token::Lit` inside an `ast::Lit`.
- Rename `LitKind::{from,to}_lit_token` as
  `LitKind::{from,to}_token_lit`, to match the above change and
  `token::Lit`.
2022-08-16 13:41:34 +10:00
Nicholas Nethercote
85a6cd6a47 Shrink ast::Attribute. 2022-08-16 11:10:13 +10:00
Matthias Krüger
6ae0414122
Rollup merge of #100350 - jhpratt:stringify-vis, r=cjgillot
Stringify non-shorthand visibility correctly

This makes `stringify!(pub(in crate))` evaluate to `pub(in crate)` rather than `pub(crate)`, matching the behavior before the `crate` shorthand was removed. Further, this changes `stringify!(pub(in super))` to evaluate to `pub(in super)` rather than the current `pub(super)`. If the latter is not desired (it is _technically_ breaking), it can be undone.

Fixes #99981

`@rustbot` label +C-bug +regression-from-stable-to-beta +T-compiler
2022-08-11 22:53:06 +02:00
Camille GILLOT
9701845287 Do not consider method call receiver as an argument in AST. 2022-08-10 18:34:54 +02:00
Jacob Pratt
be5672ecb2
Stringify non-shorthand visibility correctly 2022-08-09 23:31:45 -04:00
wcampbell
8dd44f1af4 Enable unused_parens for match arms 2022-08-04 07:16:39 -04:00
Nicholas Nethercote
332dffb1f9 Remove TreeAndSpacing.
A `TokenStream` contains a `Lrc<Vec<(TokenTree, Spacing)>>`. But this is
not quite right. `Spacing` makes sense for `TokenTree::Token`, but does
not make sense for `TokenTree::Delimited`, because a
`TokenTree::Delimited` cannot be joined with another `TokenTree`.

This commit fixes this problem, by adding `Spacing` to `TokenTree::Token`,
changing `TokenStream` to contain a `Lrc<Vec<TokenTree>>`, and removing the
`TreeAndSpacing` typedef.

The commit removes these two impls:
- `impl From<TokenTree> for TokenStream`
- `impl From<TokenTree> for TreeAndSpacing`

These were useful, but also resulted in code with many `.into()` calls
that was hard to read, particularly for anyone not highly familiar with
the relevant types. This commit makes some other changes to compensate:
- `TokenTree::token()` becomes `TokenTree::token_{alone,joint}()`.
- `TokenStream::token_{alone,joint}()` are added.
- `TokenStream::delimited` is added.

This results in things like this:
```rust
TokenTree::token(token::Semi, stmt.span).into()
```
changing to this:
```rust
TokenStream::token_alone(token::Semi, stmt.span)
```
This makes the type of the result, and its spacing, clearer.

These changes also simplifies `Cursor` and `CursorRef`, because they no longer
need to distinguish between `next` and `next_with_spacing`.
2022-07-29 15:52:15 +10:00
Maybe Waffle
40ae7b5b8e Parse closure binders
This is first step in implementing RFC 3216.
- Parse `for<'a>` before closures in ast
  - Error in lowering
- Add `closure_lifetime_binder` feature
2022-07-12 16:25:16 +04:00
Nixon Enraght-Moony
18ca2946e0 ast: Add span to Extern 2022-07-02 23:30:03 +01:00