Commit Graph

1643 Commits

Author SHA1 Message Date
Matthew Jasper
26f48b4cba Stabilize THIR unsafeck 2024-01-05 10:00:59 +00:00
Matthias Krüger
a919d97aaa
Rollup merge of #119325 - RalfJung:custom-mir, r=compiler-errors
custom mir: make it clear what the return block is

Custom MIR recently got support for specifying the "unwind action", so now there's two things coming after the actual call part of `Call` terminators. That's not very self-explaining so I propose we change the syntax to imitate keyword arguments:
```
Call(popped = Vec::pop(v), ReturnTo(drop), UnwindContinue())
```

Also fix some outdated docs and add some docs to `Call` and `Drop`.
2024-01-04 15:33:58 +01:00
Michael Goulet
1d48f69d65 Check yield terminator's resume type in borrowck 2024-01-04 01:47:56 +00:00
Nicholas Nethercote
505c1371d0 Rename some Diagnostic setters.
`Diagnostic` has 40 methods that return `&mut Self` and could be
considered setters. Four of them have a `set_` prefix. This doesn't seem
necessary for a type that implements the builder pattern. This commit
removes the `set_` prefixes on those four methods.
2024-01-03 19:40:20 +11:00
Nadrieril
c35272058d Statically enforce revealing of opaques 2024-01-01 23:10:03 +01:00
Michael Goulet
e24da8ea19 Movability doesn't need to be a query anymore 2023-12-28 16:35:01 +00:00
Michael Goulet
fcb42b42d6 Remove movability from TyKind::Coroutine 2023-12-28 16:35:01 +00:00
Nadrieril
fc0be3c921 Keep reference to the original Pat in DeconstructedPat 2023-12-26 23:14:23 +01:00
Ralf Jung
0f9baa8a31 custom mir: make it clear what the return block is 2023-12-26 20:15:26 +01:00
Michael Goulet
e1be642b41
Rollup merge of #119307 - compiler-errors:pat-lifetimes, r=Nadrieril
Clean up some lifetimes in `rustc_pattern_analysis`

This PR removes some redundant lifetimes. I figured out that we were shortening the lifetime of an arena-allocated `&'p DeconstructedPat<'p>` to `'a DeconstructedPat<'p>`, which forced us to carry both lifetimes when we could otherwise carry just one.

This PR also removes and elides some unnecessary lifetimes.

I also cherry-picked 0292eb9bb9b897f5c0926c6a8530877f67e7cc9b, and then simplified more lifetimes in `MatchVisitor`, which should make #119233 a very simple PR!

r? Nadrieril
2023-12-26 13:29:14 -05:00
Michael Goulet
48d089a800 Merge 'thir and 'p 2023-12-26 03:15:41 +00:00
Nadrieril
2b4f84f2b2 thir::Visitor only needs to visit &'thir data 2023-12-26 03:15:18 +00:00
bors
2271c26e4a Auto merge of #119146 - nnethercote:rm-DiagCtxt-api-duplication, r=compiler-errors
Remove `DiagCtxt` API duplication

`DiagCtxt` defines the internal API for creating and emitting diagnostics: methods like `struct_err`, `struct_span_warn`, `note`, `create_fatal`, `emit_bug`. There are over 50 methods.

Some of these methods are then duplicated across several other types: `Session`, `ParseSess`, `Parser`, `ExtCtxt`, and `MirBorrowckCtxt`. `Session` duplicates the most, though half the ones it does are unused. Each duplicated method just calls forward to the corresponding method in `DiagCtxt`. So this duplication exists to (in the best case) shorten chains like `ecx.tcx.sess.parse_sess.dcx.emit_err()` to `ecx.emit_err()`.

This API duplication is ugly and has been bugging me for a while. And it's inconsistent: there's no real logic about which methods are duplicated, and the use of `#[rustc_lint_diagnostic]` and `#[track_caller]` attributes vary across the duplicates.

This PR removes the duplicated API methods and makes all diagnostic creation and emission go through `DiagCtxt`. It also adds `dcx` getter methods to several types to shorten chains. This approach scales *much* better than API duplication; indeed, the PR adds `dcx()` to numerous types that didn't have API duplication: `TyCtxt`, `LoweringCtxt`, `ConstCx`, `FnCtxt`, `TypeErrCtxt`, `InferCtxt`, `CrateLoader`, `CheckAttrVisitor`, and `Resolver`. These result in a lot of changes from `foo.tcx.sess.emit_err()` to `foo.dcx().emit_err()`. (You could do this with more types, but it gets into diminishing returns territory for types that don't emit many diagnostics.)

After all these changes, some call sites are more verbose, some are less verbose, and many are the same. The total number of lines is reduced, mostly because of the removed API duplication. And consistency is increased, because calls to `emit_err` and friends are always preceded with `.dcx()` or `.dcx`.

r? `@compiler-errors`
2023-12-26 02:24:39 +00:00
bors
f2348fb29a Auto merge of #119122 - matthewjasper:if-let-guard-scoping, r=TaKO8Ki
Give temporaries in if let guards correct scopes

Temporaries in if-let guards have scopes that escape the match arm, this causes problems because the drops might be for temporaries that are not storage live. This PR changes the scope of temporaries in if-let guards to be limited to the arm:

```rust
_ if let Some(s) = std::convert::identity(&Some(String::new())) => {}
//                Temporary for Some(String::new()) is dropped here ^
```

We also now deduplicate temporaries between copies of the guard created for or-patterns:

```rust
// Only create a single Some(String::new()) temporary variable
_ | _ if let Some(s) = std::convert::identity(&Some(String::new())) => {}
```

This changes MIR building to pass around `ExprId`s rather than `Expr`s so that we have a way to index different expressions.

cc #51114
Closes #116079
2023-12-25 04:06:58 +00:00
Nicholas Nethercote
99472c7049 Remove Session methods that duplicate DiagCtxt methods.
Also add some `dcx` methods to types that wrap `TyCtxt`, for easier
access.
2023-12-24 08:05:28 +11:00
Michael Goulet
8c50e3eaee
Rollup merge of #119230 - Nadrieril:librarify-even-further, r=compiler-errors
Exhaustiveness: clean up after librarification

This cleans up some things that weren't done nicely by https://github.com/rust-lang/rust/pull/118842.

r? `@compiler-errors`
2023-12-22 21:41:05 -05:00
Nicholas Nethercote
757d6f6ef8 Give DiagnosticBuilder a default type.
`IntoDiagnostic` defaults to `ErrorGuaranteed`, because errors are the
most common diagnostic level. It makes sense to do likewise for the
closely-related (and much more widely used) `DiagnosticBuilder` type,
letting us write `DiagnosticBuilder<'a, ErrorGuaranteed>` as just
`DiagnosticBuilder<'a>`. This cuts over 200 lines of code due to many
multi-line things becoming single line things.
2023-12-23 13:23:10 +11:00
Nadrieril
5fccaee59c Clarify the situation with dummy patterns and PatData
Use an explicit `Option` instead of requiring a `Default` bound
2023-12-23 00:08:38 +01:00
bors
c1fc1d18cd Auto merge of #116821 - Nadrieril:fix-opaque-ice, r=compiler-errors
Exhaustiveness: reveal opaque types properly

Previously, exhaustiveness had no clear policy around opaque types. In this PR I propose the following policy: within the body of an item that defines the hidden type of some opaque type, exhaustiveness checking on a value of that opaque type is performed using the concrete hidden type inferred in this body.

I'm not sure how consistent this is with other operations allowed on opaque types; I believe this will require FCP.

From what I can tell, this doesn't change anything for non-empty types.

The observable changes are:
- when the real type is uninhabited, matches within the defining scopes can now rely on that for exhaustiveness, e.g.:

```rust
#[derive(Copy, Clone)]
enum Void {}
fn return_never_rpit(x: Void) -> impl Copy {
    if false {
        match return_never_rpit(x) {}
    }
    x
}
```
- this properly fixes ICEs like https://github.com/rust-lang/rust/issues/117100 that occurred because a same match could have some patterns where the type is revealed and some where it is not.

Bonus subtle point: if `x` is opaque, a match like `match x { ("", "") => {} ... }` will constrain its type ([playground](https://play.rust-lang.org/?version=nightly&mode=debug&edition=2021&gist=901d715330eac40339b4016ac566d6c3)). This is not the case for `match x {}`: this will not constain the type, and will only compile if something else constrains the type to be empty.

Fixes https://github.com/rust-lang/rust/issues/117100

r? `@oli-obk`

Edited for precision of the wording

[Included](https://github.com/rust-lang/rust/pull/116821#issuecomment-1813171764) in the FCP on this PR is this rule:

> Within the body of an item that defines the hidden type of some opaque type, exhaustiveness checking on a value of that opaque type is performed using the concrete hidden type inferred in this body.
2023-12-22 12:12:12 +00:00
bors
cee794ee98 Auto merge of #119097 - nnethercote:fix-EmissionGuarantee, r=compiler-errors
Fix `EmissionGuarantee`

There are some problems with the `DiagCtxt` API related to `EmissionGuarantee`. This PR fixes them.

r? `@compiler-errors`
2023-12-22 00:03:57 +00:00
Matthew Jasper
d437a111f5 Give temporaries in if let guards correct scopes
- Make temporaries in if-let guards be the same variable in MIR when
  the guard is duplicated due to or-patterns.
- Change the "destruction scope" for match arms to be the arm scope rather
  than the arm body scope.
- Add tests.
2023-12-21 13:35:56 +00:00
Nadrieril
2a87bae48d Reveal opaque types in exhaustiveness checking 2023-12-20 14:43:00 +01:00
bors
f704f3b93b Auto merge of #119112 - Nadrieril:remove-target_blocks-hack, r=matthewjasper
match lowering: Remove the `make_target_blocks` hack

This hack was introduced 4 years ago in [`a1d0266` (#60730)](a1d0266878) to improve LLVM optimization time, specifically noticed in the `encoding` benchmark. Measurements today indicate it is no longer needed.

r? `@matthewjasper`
2023-12-19 21:15:31 +00:00
bors
3a539c0889 Auto merge of #118842 - Nadrieril:librarify-further, r=compiler-errors
Make exhaustiveness usable outside of rustc

With this PR, `rustc_pattern_analysis` compiles on stable (with the `stable` feature)! `rust-analyzer` will be able to use it to provide match-related diagnostics and refactors.

Two questions:
- Should I name the feature `nightly` instead of `rustc` for consistency with other crates? `rustc` makes more sense imo.
- `typed-arena` is an optional dependency but tidy made me add it to the allow-list anyway. Can I avoid that somehow?

r? `@compiler-errors`
2023-12-19 17:15:04 +00:00
Nadrieril
31bad13f82 Remove the make_target_blocks hack
It was introduced 4 years ago in a1d0266878 to improve LLVM
optimization time. Measurements today indicate it is no longer needed.
2023-12-19 11:37:39 +01:00
Nicholas Nethercote
e7724a2e31 Add level arg to into_diagnostic.
And make all hand-written `IntoDiagnostic` impls generic, by using
`DiagnosticBuilder::new(dcx, level, ...)` instead of e.g.
`dcx.struct_err(...)`.

This means the `create_*` functions are the source of the error level.
This change will let us remove `struct_diagnostic`.

Note: `#[rustc_lint_diagnostics]` is added to `DiagnosticBuilder::new`,
it's necessary to pass diagnostics tests now that it's used in
`into_diagnostic` functions.
2023-12-19 09:19:25 +11:00
Matthew Jasper
68d684cbff Pass THIR ExprIds in MIR building 2023-12-18 16:54:58 +00:00
Nicholas Nethercote
f422dca3ae Rename many DiagCtxt arguments. 2023-12-18 16:06:22 +11:00
Nicholas Nethercote
09af8a667c Rename Session::span_diagnostic as Session::dcx. 2023-12-18 16:06:21 +11:00
Nicholas Nethercote
cde19c016e Rename Handler as DiagCtxt. 2023-12-18 16:06:19 +11:00
Nadrieril
1e89a38423 pattern_analysis doesn't need to know what spans are 2023-12-15 16:58:38 +01:00
Nadrieril
e10b165775 s/RustcCtxt/RustcMatchCheckCtxt/ 2023-12-15 16:58:38 +01:00
Nadrieril
42f4393824 Iron out last rustc-specific details 2023-12-15 16:58:37 +01:00
Nadrieril
cb622f3994 Name rustc-specific things "rustc" 2023-12-15 16:58:37 +01:00
Nadrieril
3d7c4df326 Abstract MatchCheckCtxt into a trait 2023-12-15 16:58:36 +01:00
Nadrieril
3ad76f9325 Disentangle the arena from MatchCheckCtxt 2023-12-15 16:57:36 +01:00
Nadrieril
b111b2e839 Split Single ctor into more specific variants 2023-12-15 16:57:36 +01:00
Matthias Krüger
2f8867e03c
Rollup merge of #118962 - compiler-errors:bugs, r=TaKO8Ki
Annotate some bugs

Gives a semi-helpful message to some `bug!()`/`unreachable!()`/`panic!()`. This also works around some other bugs/panics/etc that weren't needed, and also makes some of them into `span_bug!`s so they also have a useful span.

Note to reviewer: best to disable whitespace when comparing for some cases where indentation changed.

cc #118955
2023-12-15 15:53:51 +01:00
Michael Goulet
1cc0d7d56c Annotate some more bugs 2023-12-15 14:45:06 +00:00
Guillaume Gomez
d3d0287330
Rollup merge of #118863 - Enselic:rustc_mir-build-query-stability, r=michaelwoerister
rustc_mir_build: Enforce `rustc::potential_query_instability` lint

Stop allowing `rustc::potential_query_instability` on all of `rustc_mir_build` and instead allow it on a case-by-case basis if it is safe to do so. In this crate there was only one instance of the lint, and it was safe to allow.

Part of https://github.com/rust-lang/rust/issues/84447 which is E-help-wanted.
2023-12-15 11:51:24 +01:00
Martin Nordholts
5644a53426 rustc_mir_build: Enforce rustc::potential_query_instability lint
Stop allowing `rustc::potential_query_instability` on all of
`rustc_mir_build` and instead allow it on a case-by-case basis if it is
safe to do so. In this crate there was no instance of the lint
remaining.
2023-12-14 17:31:21 +01:00
Martin Nordholts
4287f5a777 rustc_mir_build: Make non-exhaustive non-empty match diagnotics deterministic 2023-12-14 17:30:41 +01:00
bors
56d25ba5ea Auto merge of #118500 - ZetaNumbers:tcx_hir_refactor, r=petrochenkov
Move some methods from `tcx.hir()` to `tcx`

https://github.com/rust-lang/rust/pull/118256#issuecomment-1826442834

Renamed:
- find -> opt_hir_node
- get -> hir_node
- find_by_def_id -> opt_hir_node_by_def_id
- get_by_def_id -> hir_node_by_def_id
2023-12-13 10:31:56 +00:00
Matthias Krüger
3795cc8eb0 more clippy::complexity fixes
redundant_guards
      redundant_slicing
      filter_next
      needless_borrowed_reference
      useless_format
2023-12-12 20:41:51 +01:00
zetanumbers
24f009c5e5 Move some methods from tcx.hir() to tcx
Renamings:
- find -> opt_hir_node
- get -> hir_node
- find_by_def_id -> opt_hir_node_by_def_id
- get_by_def_id -> hir_node_by_def_id

Fix rebase changes using removed methods

Use `tcx.hir_node_by_def_id()` whenever possible in compiler

Fix clippy errors

Fix compiler

Apply suggestions from code review

Co-authored-by: Vadim Petrochenkov <vadim.petrochenkov@gmail.com>

Add FIXME for `tcx.hir()` returned type about its removal

Simplify with with `tcx.hir_node_by_def_id`
2023-12-12 06:40:29 -08:00
Matthias Krüger
dd0887c75c
Rollup merge of #118822 - Nadrieril:librarify, r=compiler-errors
Extract exhaustiveness into its own crate

It now makes sense to extract exhaustiveness into its own crate! This was much-requested by rust-analyzer (they currently maintain by hand a copy of the algorithm), and I hope this can serve other projects e.g. clippy.

This is the churny PR: it exclusively moves code around. It's not yet useable outside of rustc but I wanted the churny parts to be out of the way.

r? `@compiler-errors`
2023-12-11 20:46:50 +01:00
Nadrieril
24adca0a26 Move lints to their own module 2023-12-11 11:20:55 +01:00
Nadrieril
3691a0aee5 Gather rustc-specific functions around MatchCheckCtxt 2023-12-11 11:20:55 +01:00
Nadrieril
281002d42c Extract exhaustiveness into its own crate 2023-12-11 11:20:55 +01:00
bors
84f6130fe3 Auto merge of #118692 - surechen:remove_unused_imports, r=petrochenkov
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.

r? `@petrochenkov`
2023-12-10 11:55:48 +00:00
bors
42dfac5e08 Auto merge of #118788 - compiler-errors:const-pretty, r=fee1-dead
Don't print host effect param in pretty `path_generic_args`

Make `own_args_no_defaults` pass back the `GenericParamDef`, so that we can pass both the args *and* param definitions into `path_generic_args`. That allows us to use the `GenericParamDef` to filter out effect params.

This allows us to filter out the host param regardless of whether it's `sym::host` or `true`/`false`.

This also renames a couple of `const_effect_param` -> `host_effect_param`, and restores `~const` pretty printing to `TraitPredPrintModifiersAndPath`.

cc #118785
r? `@fee1-dead` cc `@oli-obk`
2023-12-10 06:59:25 +00: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
bors
06e02d5b25 Auto merge of #118308 - Nadrieril:sound-exhaustive-patterns-take-3, r=compiler-errors
Don't warn an empty pattern unreachable if we're not sure the data is valid

Exhaustiveness checking used to be naive about the possibility of a place containing invalid data. This could cause it to emit an "unreachable pattern" lint on an arm that was in fact reachable, as in https://github.com/rust-lang/rust/issues/117119.

This PR fixes that. We now track whether a place that is matched on may hold invalid data. This also forced me to be extra precise about how exhaustiveness manages empty types.

Note that this now errs in the opposite direction: the following arm is truly unreachable (because the binding causes a read of the value) but not linted as such. I'd rather not recommend writing a `match ... {}` that has the implicit side-effect of loading the value. [Never patterns](https://github.com/rust-lang/rust/issues/118155) will solve this cleanly.
```rust
match union.value {
    _x => unreachable!(),
}
```

I recommend reviewing commit by commit. I went all-in on the test suite because this went through a lot of iterations and I kept everything. The bit I'm least confident in is `is_known_valid_scrutinee` in `check_match.rs`.

Fixes https://github.com/rust-lang/rust/issues/117119.
2023-12-09 19:03:03 +00:00
Michael Goulet
7467c3a45c s/const_effect/host_effect 2023-12-09 17:43:08 +00:00
bors
1dfb2283d7 Auto merge of #116170 - matthewjasper:remove-thir-destruction-scopes, r=cjgillot
Don't include destruction scopes in THIR

They are not used by anyone, and add memory/performance overhead.
2023-12-09 12:38:32 +00:00
Nadrieril
c3df51a976 Some types cannot show up as the type of a pattern 2023-12-09 01:22:28 +01:00
Nadrieril
ddef5b61f1 Don't warn an empty pattern unreachable if we're not sure the data is valid 2023-12-09 00:44:49 +01:00
Nadrieril
f5dbb54648 Track place validity 2023-12-09 00:40:00 +01:00
Nadrieril
2186f98f16 Correctly handle empty constructors
- `ConstructorSet` knows about both empty and nonempty constructors;
- If an empty constructor is present in the column, we output it in
    `split().present`.
2023-12-09 00:40:00 +01:00
Nadrieril
9aafc0b815 Be precise about usefulness vs reachability 2023-12-09 00:39:59 +01:00
Zalathar
d90fd027c8 coverage: Use SpanMarker to mark the full condition of if !
When MIR is built for an if-not expression, the `!` part of the condition
doesn't correspond to any MIR statement, so coverage instrumentation normally
can't see it.

We can fix that by deliberately injecting a dummy statement whose sole purpose
is to associate that span with its enclosing block.
2023-12-08 22:40:49 +11:00
Zalathar
98166358a9 coverage: Use SpanMarker to mark continue expressions.
This replaces the previous workaround, which was to inject a dummy `Assign`
statement.
2023-12-08 22:40:49 +11:00
Zalathar
44b47aa976 coverage: Add CoverageKind::SpanMarker for including extra spans in MIR
There are cases where coverage instrumentation wants to show a span for some
syntax element, but there is no MIR node that naturally carries that span, so
the instrumentor can't see it.

MIR building can now use this new kind of coverage statement to deliberately
include those spans in MIR, attached to a dummy statement that has no other
effect.
2023-12-08 22:40:49 +11:00
Matthias Krüger
81b6263dd0
Rollup merge of #118598 - Nadrieril:remove_precise_pointer_size_matching, r=davidtwco
Remove the `precise_pointer_size_matching` feature gate

`usize` and `isize` are special for pattern matching because their range might depend on the platform. To make code portable across platforms, the following is never considered exhaustive:
```rust
let x: usize = ...;
match x {
    0..=18446744073709551615 => {}
}
```
Because of how rust handles constants, this also unfortunately counts `0..=usize::MAX` as non-exhaustive. The [`precise_pointer_size_matching`](https://github.com/rust-lang/rust/issues/56354) feature gate was introduced both for this convenience and for the possibility that the lang team could decide to allow the above.

Since then, [half-open range patterns](https://github.com/rust-lang/rust/issues/67264) have been implemented, and since #116692 they correctly support `usize`/`isize`:
```rust
match 0usize { // exhaustive!
    0..5 => {}
    5.. => {}
}
```
I believe this subsumes all the use cases of the feature gate. Moreover no attempt has been made to stabilize it in the 5 years of its existence. I therefore propose we retire this feature gate.

Closes https://github.com/rust-lang/rust/issues/56354
2023-12-05 16:08:35 +01:00
Matthew Jasper
43adf41ca6 Don't include destruction scopes in THIR
They are not used by anyone, and add memory/performance overhead.
2023-12-04 16:31:13 +00:00
Nadrieril
5e470db05c Remove the precise_pointer_size_matching feature gate 2023-12-04 11:56:21 +01:00
bors
cf8d81213c Auto merge of #118490 - Nadrieril:arena-alloc-matrix, r=nnethercote
Exhaustiveness: allocate memory better

Exhaustiveness is a recursive algorithm that allocates a bunch of slices at every step. Let's see if I can improve performance by improving allocations.

Already just using `Vec::with_capacity` is showing impressive improvements on my local measurements.

r? `@ghost`
2023-12-04 07:06:36 +00:00
Nadrieril
7058df2f4e Anticipate allocation sizes 2023-12-02 03:23:49 +01:00
Nicholas Nethercote
5d1d384443 Rename HandlerInner::delay_span_bug as HandlerInner::span_delayed_bug.
Because the corresponding `Level` is `DelayedBug` and `span_delayed_bug`
follows the pattern used everywhere else: `span_err`, `span_warning`,
etc.
2023-12-02 09:01:19 +11:00
bors
e55544c804 Auto merge of #118379 - compiler-errors:const-params-for-partialeq, r=fee1-dead
Fix `PartialEq` args when `#[const_trait]` is enabled

This is based off of your PR that enforces effects on all methods, so just see the last commits.

r? fee1-dead
2023-11-30 05:24:53 +00:00
Matthias Krüger
911a5ee7ff
Rollup merge of #118333 - eduardosm:print-missing-target-features, r=est31
Print list of missing target features when calling a function with target features outside an unsafe block

Fixes https://github.com/rust-lang/rust/issues/108680

Supersedes https://github.com/rust-lang/rust/pull/109710. I used the same wording for the messages, but the implementation is different.

r? `@est31`
2023-11-29 12:34:50 +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
Nadrieril
a3838c8550 Add never_patterns feature gate 2023-11-29 03:58:29 +01:00
Michael Goulet
d3404d2b98 Add with_opt_const_effect_param helper, simplify 2023-11-28 21:17:55 +00:00
Michael Goulet
82a9e872d8 Fix PartialEq args when #[const_trait] is enabled 2023-11-28 21:17:19 +00:00
Eduardo Sánchez Muñoz
6b066a9305 thir-unsafeck: print list of missing target features when calling a function with target features outside an unsafe block 2023-11-28 20:37:02 +01:00
bors
46a24ed2f4 Auto merge of #118405 - matthiaskrgr:rollup-3a2eevc, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #115331 (optimize str::iter::Chars::advance_by)
 - #118236 (Update mod comment)
 - #118299 (Update `OnceLock` documentation to give a concrete 'lazy static' example, and expand on the existing example.)
 - #118314 (Rename `{collections=>alloc}{tests,benches}`)
 - #118341 (Simplify indenting in THIR printing)
 - #118366 (Detect and reject malformed `repr(Rust)` hints)
 - #118397 (Fix comments for unsigned non-zero `checked_add`, `saturating_add`)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-28 10:21:41 +00:00
bors
e06c94d6cb Auto merge of #118282 - fee1-dead-contrib:enforce-more, r=compiler-errors
effects: Run `enforce_context_effects` for all method calls

So that we also perform checks when overloaded `PartialEq`s are called.

r? `@compiler-errors`
2023-11-28 08:23:47 +00:00
Mark Rousskov
8375fe4710 Simplify indenting in THIR printing
This cuts >100kb from a local librustc_driver.so build, and seems just
obviously simpler.
2023-11-26 18:44:16 -05:00
Guillaume Gomez
c6d20d70b4
Rollup merge of #118311 - bvanjoi:merge_coroutinue_into_closure, r=petrochenkov
merge `DefKind::Coroutine` into `Defkind::Closure`

Related to #118188

We no longer need to be concerned about the precise type whether it's `DefKind::Closure` or `DefKind::Coroutine`.

Furthermore, thanks for the great work done by `@petrochenkov` on investigating https://rust-lang.zulipchat.com/#narrow/stream/182449-t-compiler.2Fhelp/topic/Why.20does.20it.20hang.20when.20querying.20.EF.BB.BF.60opt_def_kind.60.3F

r? `@petrochenkov`
2023-11-26 15:44:54 +01:00
Guillaume Gomez
c67613bef9
Rollup merge of #118302 - mu001999:dead_code/clean, r=cjgillot
Clean dead codes

Clean dead codes detected by #118257
2023-11-26 15:44:54 +01:00
bohan
f23befe6c1 merge DefKind::Coroutine into DefKind::Closure 2023-11-26 21:05:08 +08:00
Vadim Petrochenkov
c697927f44 rustc: hir().local_def_id_to_hir_id() -> tcx.local_def_id_to_hir_id() cleanup 2023-11-26 12:41:21 +03:00
bors
33f6af8052 Auto merge of #118300 - compiler-errors:rollup-cm3i8fg, r=compiler-errors
Rollup of 7 pull requests

Successful merges:

 - #117651 (coverage: Simplify building coverage expressions based on sums)
 - #117968 (Stabilize `ptr::addr_eq`)
 - #118158 (Reduce fluent boilerplate)
 - #118201 (Miscellaneous `ObligationCauseCode` cleanups)
 - #118288 (Use `is_{some,ok}_and` more in the compiler)
 - #118289 (`is_{some,ok}_and` for rustdoc)
 - #118290 (Don't ICE when encountering placeholders in implied bounds computation)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-11-26 02:28:05 +00:00
r0cky
91aee2de15 Clean dead codes 2023-11-26 09:25:07 +08:00
bors
ee80c8d0a8 Auto merge of #117611 - Nadrieril:linear-pass-take-4, r=cjgillot
Rewrite exhaustiveness in one pass

This is at least my 4th attempt at this in as many years x) Previous attempts were all too complicated or too slow. But we're finally here!

The previous version of the exhaustiveness algorithm computed reachability for each arm then exhaustiveness of the whole match. Since each of these steps does roughly the same things, this rewrites the algorithm to do them all in one go. I also think this makes things much simpler.

I also rewrote the documentation of the algorithm in depth. Hopefully it's up-to-date and easier to follow now. Plz comment if anything's unclear.

r? `@oli-obk` I think you're one of the rare other people to understand the exhaustiveness algorithm?

cc `@varkor` I know you're not active anymore, but if you feel like having a look you might enjoy this :D

Fixes https://github.com/rust-lang/rust/issues/79307
2023-11-26 00:14:14 +00:00
Michael Goulet
8dd8db5073
Rollup merge of #118288 - compiler-errors:is_some_and, r=lqd,dtolnay
Use `is_{some,ok}_and` more in the compiler

slightly more fluent-reading code
2023-11-25 17:23:34 -05:00
Michael Goulet
3b2f33ee28
Rollup merge of #118158 - nnethercote:reduce-fluent-boilerplate, r=compiler-errors
Reduce fluent boilerplate

Best reviewed one commit at a time.

r? `@davidtwco`
2023-11-25 17:23:33 -05:00
Nicholas Nethercote
57cd5e6551 Use rustc_fluent_macro::fluent_messages! directly.
Currently we always do this:
```
use rustc_fluent_macro::fluent_messages;
...
fluent_messages! { "./example.ftl" }
```
But there is no need, we can just do this everywhere:
```
rustc_fluent_macro::fluent_messages! { "./example.ftl" }
```
which is shorter.
2023-11-26 08:38:40 +11:00
Nicholas Nethercote
a733082be9 Avoid need for {D,Subd}iagnosticMessage imports.
The `fluent_messages!` macro produces uses of
`crate::{D,Subd}iagnosticMessage`, which means that every crate using
the macro must have this import:
```
use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage};
```

This commit changes the macro to instead use
`rustc_errors::{D,Subd}iagnosticMessage`, which avoids the need for the
imports.
2023-11-26 08:38:00 +11:00
Michael Goulet
079a2e865f is_{some,ok}_and 2023-11-25 18:47:16 +00:00
Michael Goulet
8bf9c18914 Review comment 2023-11-25 18:00:35 +00:00
Michael Goulet
82f23d56b7 make sure we still eagerly emit errors 2023-11-25 18:00:35 +00:00
Michael Goulet
a992defc8b Remove mir::Const::from_anon_const 2023-11-25 17:52:43 +00:00
Deadbeef
d5ebdfc2c5 effects: Run enforce_context_effects for all method calls 2023-11-25 13:11:38 +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
Nadrieril
273cbb7304 Separate PatStack and MatrixRow
This disentangles the row-specific tracking of `parent_row` etc from the
logical operation of specialization. This means `wildcard_row` doesn't
need to provide dummy values for `parent_row` etc anymore.
2023-11-22 03:25:15 +01:00
Nadrieril
41e8f58fdc Clarify the Wildcard/Missing situation 2023-11-22 03:25:15 +01:00
Nadrieril
0edb879167 Cleanup span passing 2023-11-22 03:25:15 +01:00
Nadrieril
fd0d8834c2 Store wildcard row in the matrix 2023-11-22 03:25:15 +01:00
Nadrieril
cc6936d577 Fully rework the algorithm and its explanation 2023-11-22 03:25:15 +01:00
Nadrieril
d744aecabf Keep rows with guards in the matrix 2023-11-22 03:25:15 +01:00
Nadrieril
6ee51426a9 Respect split invariants for Opaques 2023-11-22 03:25:15 +01:00
Nadrieril
25696cc0e9 Abstract over the list of WitnessStacks 2023-11-22 03:25:10 +01:00
Nadrieril
8ad33a887f Tweak lower_pattern 2023-11-22 02:14:43 +01: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
94d9b7e708
Rollup merge of #117832 - RalfJung:interpret-shift, r=cjgillot
interpret: simplify handling of shifts by no longer trying to handle signed and unsigned shift amounts in the same branch

While we're at it, also update comments in codegen and MIR building related to shifts, and fix the overflow error printed by Miri on negative shift amounts.
2023-11-19 19:14:33 -08:00
lcnr
40b154e53c rename bound region instantiation
- `erase_late_bound_regions` -> `instantiate_bound_regions_with_erased`
- `replace_late_bound_regions_X` -> `instantiate_bound_regions_X`
2023-11-17 09:29:48 +00:00
Mark Rousskov
917f6540ed Re-format code with new rustfmt 2023-11-15 21:45:48 -05:00
Matthias Krüger
d2cdf6c479
Rollup merge of #117686 - compiler-errors:gen-body, r=wesleywiser
Build pre-coroutine-transform coroutine body on error

I was accidentally building the post-transform coroutine body, rather than the pre-transform coroutine body. There's no pinning expected here yet, and the return type isn't yet transformed into `CoroutineState`.

Fixes #117670
2023-11-14 21:50:38 +01:00
bors
5526682702 Auto merge of #117330 - tmiasko:custom-mir-cleanup-blocks, r=cjgillot
Custom MIR: Support cleanup blocks

Cleanup blocks are declared with `bb (cleanup) = { ... }`.

`Call` and `Drop` terminators take an additional argument describing the unwind action, which is one of the following:

* `UnwindContinue()`
* `UnwindUnreachable()`
* `UnwindTerminate(reason)`, where reason is `ReasonAbi` or `ReasonInCleanup`
* `UnwindCleanup(block)`

Also support unwind resume and unwind terminate terminators:

* `UnwindResume()`
* `UnwindTerminate(reason)`
2023-11-14 08:53:25 +00:00
Tomasz Miąsko
78da577650 Custom MIR: Support cleanup blocks
Cleanup blocks are declared with `bb (cleanup) = { ... }`.

`Call` and `Drop` terminators take an additional argument describing the
unwind action, which is one of the following:

* `UnwindContinue()`
* `UnwindUnreachable()`
* `UnwindTerminate(reason)`, where reason is `ReasonAbi` or `ReasonInCleanup`
* `UnwindCleanup(block)`

Also support unwind resume and unwind terminate terminators:

* `UnwindResume()`
* `UnwindTerminate(reason)`
2023-11-14 08:23:58 +01:00
lcnr
86fa1317a3 rename ReLateBound to ReBound
other changes:
- `Region::new_late_bound` -> `Region::new_bound`
- `Region::is_late_bound` -> `Region::is_bound`
2023-11-13 14:13:54 +00:00
Ralf Jung
31493c70fa interpret: simplify handling of shifts by no longer trying to handle signed and unsigned shift amounts in the same branch 2023-11-12 12:49:46 +01:00
bors
b7583d38b7 Auto merge of #117712 - lcnr:expand-coroutine, r=jackh726
generator layout: ignore fake borrows

fixes #117059

We emit fake shallow borrows in case the scrutinee place uses a `Deref` and there is a match guard. This is necessary to prevent the match guard from mutating the scrutinee: fab1054e17/compiler/rustc_mir_build/src/build/matches/mod.rs (L1250-L1265)

These fake borrows end up impacting the generator witness computation in `mir_generator_witnesses`, which causes the issue in #117059. This PR now completely ignores fake borrows during this computation. This is sound as thse are always removed after analysis and the actual computation of the generator layout happens afterwards.

Only the second commit impacts behavior, and could be backported by itself.

r? types
2023-11-09 14:23:45 +00:00
lcnr
992d93f687 rename BorrowKind::Shallow to Fake
also adds some comments
2023-11-08 22:55:28 +01:00
bors
fdaaaf9f92 Auto merge of #116930 - RalfJung:raw-ptr-match, r=davidtwco
patterns: reject raw pointers that are not just integers

Matching against `0 as *const i32` is fine, matching against `&42 as *const i32` is not.

This extends the existing check against function pointers and wide pointers: we now uniformly reject all these pointer types during valtree construction, and then later lint because of that. See [here](https://github.com/rust-lang/rust/pull/116930#issuecomment-1784654073) for some more explanation and context.

Also fixes https://github.com/rust-lang/rust/issues/116929.

Cc `@oli-obk` `@lcnr`
2023-11-08 20:42:32 +00:00
Ralf Jung
30588657b7 avoid unnecessary nested conditionals 2023-11-08 20:37:08 +01:00
Michael Goulet
0ba7d19769 Build pre-coroutine-transform coroutine body 2023-11-07 21:14:43 +00:00
bors
61a3eea804 Auto merge of #117229 - matthewjasper:thir-unsafeck-fixes, r=cjgillot
Thir unsafeck fixes

- Recognise thread local statics in THIR unsafeck
- Add suggestion for unsafe_op_in_unsafe_fn
- Fix unsafe checking of let expressions
2023-11-07 10:41:10 +00:00
Michael Goulet
5a9f07cc97 Build a better MIR body when errors are encountered 2023-11-06 23:54:53 +00:00
Matthew Jasper
868de8e76b Visit patterns in THIR let expressions
This fixes some THIR unsafety checking errors not being emitted for
let expressions in these situations.
2023-11-06 16:23:09 +00:00
Matthew Jasper
2b59992736 Add suggestion to THIR unsafe_op_in_unsafe_fn lint 2023-11-06 16:23:09 +00:00
Matthew Jasper
931692fa13 Recognise thread local statics in THIR unsafeck 2023-11-06 16:23:08 +00:00
Nadrieril
f0e8330879 Suggest to set lint level on whole match 2023-11-04 14:44:00 +01:00
Nadrieril
61d0fc7cf5 Warn when lint level is set on a match arm 2023-11-04 14:44:00 +01:00
Takayuki Maeda
9b9ea77641
Rollup merge of #117343 - Nadrieril:cleanup_check_match, r=davidtwco
Cleanup `rustc_mir_build/../check_match.rs`

The file had become pretty unwieldy, with a fair amount of duplication. As a bonus, I discovered that we weren't running some pattern checks in if-let chains.

I recommend looking commit-by-commit. The last commit is a whim, I think it makes more sense that way but I don't hold this opinion strongly.
2023-11-04 12:44:44 +09:00
Nadrieril
746197c08a Tweak spans for "adt defined here" note 2023-11-03 18:26:16 +01:00
Nadrieril
335156ca73 Accumulate let chains alongside the visit 2023-11-03 18:26:16 +01:00
Matthias Krüger
1ba97cb1cc clone less 2023-11-03 13:23:26 +01:00
Nadrieril
3760d919d8 Cleanup check_match code paths 2023-11-02 03:19:19 +01:00
Nadrieril
fcd24fbd3c Factor out pointing at ADT definition 2023-11-02 03:19:19 +01:00
Nadrieril
c19856929d Always do all the pattern checks 2023-11-02 03:19:19 +01:00
Nadrieril
d95f6a9532 Tweak diagnostic for consistency 2023-11-02 03:19:19 +01:00
Nadrieril
380c56c6b3 Check pattern error while lowering 2023-11-02 03:19:18 +01:00
Nadrieril
1f9a2f73e1 Uncomplicate check_let_chain 2023-11-02 03:19:18 +01:00
Nadrieril
fedee8d524 Reorder 2023-11-02 03:19:18 +01:00
bors
146dafa262 Auto merge of #114208 - GKFX:offset_of_enum, r=wesleywiser
Support enum variants in offset_of!

This MR implements support for navigating through enum variants in `offset_of!`, placing the enum variant name in the second argument to `offset_of!`. The RFC placed it in the first argument, but I think it interacts better with nested field access in the second, as you can then write things like

```rust
offset_of!(Type, field.Variant.field)
```

Alternatively, a syntactic distinction could be made between variants and fields (e.g. `field::Variant.field`) but I'm not convinced this would be helpful.

[RFC 3308 # Enum Support](https://rust-lang.github.io/rfcs/3308-offset_of.html#enum-support-offset_ofsomeenumstructvariant-field_on_variant)
Tracking Issue #106655.
2023-11-01 14:17:56 +00:00
bors
7fc6365570 Auto merge of #116692 - Nadrieril:half-open-ranges, r=cjgillot
Match usize/isize exhaustively with half-open ranges

The long-awaited finale to the saga of [exhaustiveness checking for integers](https://github.com/rust-lang/rust/pull/50912)!

```rust
match 0usize {
    0.. => {} // exhaustive!
}
match 0usize {
    0..usize::MAX => {} // helpful error message!
}
```

Features:
- Half-open ranges behave as expected for `usize`/`isize`;
- Trying to use `0..usize::MAX` will tell you that `usize::MAX..` is missing and explain why. No more unhelpful "`_` is missing";
- Everything else stays the same.

This should unblock https://github.com/rust-lang/rust/issues/37854.

Review-wise:
- I recommend looking commit-by-commit;
- This regresses perf because of the added complexity in `IntRange`; hopefully not too much;
- I measured each `#[inline]`, they all help a bit with the perf regression (tho I don't get why);
- I did not touch MIR building; I expect there's an easy PR there that would skip unnecessary comparisons when the range is half-open.
2023-11-01 03:17:19 +00:00
George Bateman
e936416a8d
Support enum variants in offset_of! 2023-10-31 23:25:54 +00:00
Michael Goulet
add09e66f2 Some more coroutine renamings 2023-10-30 23:46:27 +00:00
bors
31bc7e2c47 Auto merge of #117415 - matthiaskrgr:rollup-jr2p1t2, r=matthiaskrgr
Rollup of 7 pull requests

Successful merges:

 - #116862 (Detect when trait is implemented for type and suggest importing it)
 - #117389 (Some diagnostics improvements of `gen` blocks)
 - #117396 (Don't treat closures/coroutine types as part of the public API)
 - #117398 (Correctly handle nested or-patterns in exhaustiveness)
 - #117403 (Poison check_well_formed if method receivers are invalid to prevent typeck from running on it)
 - #117411 (Improve some diagnostics around `?Trait` bounds)
 - #117414 (Don't normalize to an un-revealed opaque when we hit the recursion limit)

r? `@ghost`
`@rustbot` modify labels: rollup
2023-10-30 20:50:14 +00:00
Matthias Krüger
342483ccc6
Rollup merge of #117398 - Nadrieril:fix-117378, r=compiler-errors
Correctly handle nested or-patterns in exhaustiveness

I had assumed nested or-patterns were flattened, and they mostly are but not always.

Fixes https://github.com/rust-lang/rust/issues/117378
2023-10-30 21:03:38 +01:00
Nadrieril
d5e836cf0c Correctly handle nested or-patterns in column-wise analyses 2023-10-30 15:31:00 +01:00
Ralf Jung
03b24f2756 remove some dead code 2023-10-30 09:11:52 +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
Ralf Jung
af6c7e0ca1 also lint against fn ptr and raw ptr nested inside the const 2023-10-28 17:02:18 +02:00
Ralf Jung
bec88ad4aa patterns: reject raw pointers that are not just integers 2023-10-28 17:02:18 +02:00
bors
59bb9505bc Auto merge of #103208 - cjgillot:match-fake-read, r=oli-obk,RalfJung
Allow partially moved values in match

This PR attempts to unify the behaviour between `let _ = PLACE`, `let _: TY = PLACE;` and `match PLACE { _ => {} }`.
The logical conclusion is that the `match` version should not check for uninitialised places nor check that borrows are still live.

The `match PLACE {}` case is handled by keeping a `FakeRead` in the unreachable fallback case to verify that `PLACE` has a legal value.

Schematically, `match PLACE { arms }` in surface rust becomes in MIR:
```rust
PlaceMention(PLACE)
match PLACE {
  // Decision tree for the explicit arms
  arms,
  // An extra fallback arm
  _ => {
    FakeRead(ForMatchedPlace, PLACE);
    unreachable
  }
}
```

`match *borrow { _ => {} }` continues to check that `*borrow` is live, but does not read the value.
`match *borrow {}` both checks that `*borrow` is live, and fake-reads the value.

Continuation of ~https://github.com/rust-lang/rust/pull/102256~ ~https://github.com/rust-lang/rust/pull/104844~

Fixes https://github.com/rust-lang/rust/issues/99180 https://github.com/rust-lang/rust/issues/53114
2023-10-27 18:51:43 +00:00
Nadrieril
35fe75d8f3 Make IntRange exclusive 2023-10-27 19:56:12 +02:00
Nadrieril
feb769a5c9 s/to_pat/to_diagnostic_pat/ 2023-10-27 19:56:12 +02:00
Nadrieril
a4875ae1e2 Match usize/isize exhaustively 2023-10-27 19:56:12 +02:00
Nadrieril
6f35ae6f9b Propagate half-open ranges through exhaustiveness checking 2023-10-27 19:56:12 +02:00
Nadrieril
9bc4c378ab Inline RangeInclusive into IntRange 2023-10-27 19:56:12 +02:00
Nadrieril
a5c67f4107 Don't use IntRange for booleans 2023-10-27 19:56:12 +02:00
Nadrieril
0ba6c4ab67 Propagate half-open ranges through THIR 2023-10-27 19:56:12 +02:00
Nadrieril
8a77b3248f Abstract over PatRange boundary value 2023-10-27 19:56:12 +02:00
Nadrieril
3fa2e71ce1 Handle ty::Opaque correctly 2023-10-27 05:16:26 +02:00
Nadrieril
d5070e32ea Lint overlapping ranges as a separate pass 2023-10-27 05:16:26 +02:00
Nadrieril
beecd93316 Abstract over per-column pattern traversal 2023-10-27 05:16:13 +02:00
bors
6f65201659 Auto merge of #113262 - Nilstrieb:rawr-casting, r=lcnr
Never consider raw pointer casts to be trival

HIR typeck tries to figure out which casts are trivial by doing them as
coercions and seeing whether this works. Since HIR typeck is oblivious
of lifetimes, this doesn't work for pointer casts that only change the
lifetime of the pointee, which are, as borrowck will tell you, not
trivial.

This change makes it so that raw pointer casts are never considered
trivial.

This also incidentally fixes the "trivial cast" lint false positive on
the same code. Unfortunately, "trivial cast" lints are now never emitted
on raw pointer casts, even if they truly are trivial. This could be
fixed by also doing the lint in borrowck for raw pointers specifically.

fixes #113257
2023-10-26 12:54:19 +00:00
Nilstrieb
e8a4814d6d Use let chains instead of let else
This makes it more obvious that we're looking at a special case.
2023-10-25 23:15:29 +02:00
Matthew Jasper
dc3d428a8a Make THIR unused_unsafe lint consistent with MIR
Updates THIR behavior to match the changes from #93678
2023-10-25 10:10:13 +00:00
bors
848a387967 Auto merge of #116482 - matthewjasper:thir-unsafeck-inline-constants, r=b-naber
Fix inline const pattern unsafety checking in THIR

Fix THIR unsafety checking of inline constants.
- Steal THIR in THIR unsafety checking (if enabled) instead of MIR lowering.
- Represent inline constants in THIR patterns.
2023-10-25 00:03:57 +00:00
Camille GILLOT
2dbbec34ab Update documentation. 2023-10-24 15:30:17 +00:00
Camille GILLOT
ec28dc7aa7 Use PlaceMention for match scrutinees. 2023-10-24 15:30:17 +00:00
Nadrieril
a134f1624c Fix #117033 2023-10-21 23:04:17 +02:00
bors
786c94a4eb Auto merge of #116734 - Nadrieril:lint-per-column, r=cjgillot
Lint `non_exhaustive_omitted_patterns` by columns

This is a rework of the `non_exhaustive_omitted_patterns` lint to make it more consistent. The intent of the lint is to help consumers of `non_exhaustive` enums ensure they stay up-to-date with all upstream variants. This rewrite fixes two cases we didn't handle well before:

First, because of details of exhaustiveness checking, the following wouldn't lint `Enum::C` as missing:
```rust
match Some(x) {
    Some(Enum::A) => {}
    Some(Enum::B) => {}
    _ => {}
}
```

Second, because of the fundamental workings of exhaustiveness checking, the following would treat the `true` and `false` cases separately and thus lint about missing variants:
```rust
match (true, x) {
    (true, Enum::A) => {}
    (true, Enum::B) => {}
    (false, Enum::C) => {}
    _ => {}
}
```
Moreover, it would correctly not lint in the case where the pair is flipped, because of asymmetry in how exhaustiveness checking proceeds.

A drawback is that it no longer makes sense to set the lint level per-arm. This will silently break the lint for current users of it (but it's behind a feature gate so that's ok).

The new approach is now independent of the exhaustiveness algorithm; it's a separate pass that looks at patterns column by column. This is another of the motivations for this: I'm glad to move it out of the algorithm, it was akward there.

This PR is almost identical to https://github.com/rust-lang/rust/pull/111651. cc `@eholk` who reviewed it at the time. Compared to then, I'm more confident this is the right approach.
2023-10-21 11:04:19 +00:00
Oli Scherer
e96ce20b34 s/generator/coroutine/ 2023-10-20 21:14:01 +00:00
Oli Scherer
60956837cf s/Generator/Coroutine/ 2023-10-20 21:10:38 +00:00
Zalathar
c479bc7f3b coverage: Attach an optional FunctionCoverageInfo to mir::Body
This allows coverage information to be attached to the function as a whole when
appropriate, instead of being smuggled through coverage statements in the
function's basic blocks.

As an example, this patch moves the `function_source_hash` value out of
individual `CoverageKind::Counter` statements and into the per-function info.

When synthesizing unused functions for coverage purposes, the absence of this
info is taken to indicate that a function was not eligible for coverage and
should not be synthesized.
2023-10-18 21:20:29 +11:00
Matthew Jasper
8aea0e9590 Address review comments
Clean up code and add comments.
Use InlineConstant to wrap range patterns.
2023-10-16 15:58:01 +00:00
Matthew Jasper
5cc83fd4a5 Fix inline const pattern unsafety checking in THIR
THIR unsafety checking was getting a cycle of
function unsafety checking
-> building THIR for the function
-> evaluating pattern inline constants in the function
-> building MIR for the inline constant
-> checking unsafety of functions (so that THIR can be stolen)
This is fixed by not stealing THIR when generating MIR but instead when
unsafety checking.
This leaves an issue with pattern inline constants not being unsafety
checked because they are evaluated away when generating THIR.
To fix that we now represent inline constants in THIR patterns and
visit them in THIR unsafety checking.
2023-10-16 15:57:59 +00:00
Matthias Krüger
51be0df011
Rollup merge of #116522 - bvanjoi:fix-115599, r=oli-obk
use `PatKind::Error` when an ADT const value has violation

Fixes #115599

Since the [to_pat](https://github.com/rust-lang/rust/pull/111913/files#diff-6d8d99538aca600d633270051580c7a9e40b35824ea2863d9dda2c85a733b5d9R126-R155) behavior has been changed in the #111913 update, the kind of `inlined_const_ast_pat` has transformed from `PatKind::Leaf { pattern: Pat { kind: Wild, ..} } ` to `PatKind::Constant`. This caused a scenario where there are no matched candidates, leading to a testing of the candidates. This process ultimately attempts to test the string const, triggering the `bug!` invocation finally.

r? ``@oli-obk``
2023-10-15 21:29:07 +02: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
bohan
223674a824 use PatKind::error when an ADT const value has violation 2023-10-15 19:20:06 +08:00
Nadrieril
ca869e3334 Lint non_exhaustive_omitted_patterns per column 2023-10-14 19:39:18 +02:00
Nadrieril
272c914bdd Distinguish user patterns from reconstructed witnesses 2023-10-14 19:39:18 +02:00
Nadrieril
89f75ff4d0 Skip most of check_match checks in the presence of PatKind::Error 2023-10-14 13:38:04 +02:00
Nadrieril
8646afb9c5 Use PatKind::Error instead of PatKind::Wild to report errors 2023-10-14 13:38:04 +02:00
Nadrieril
aab3b9327e Propagate pattern errors via a new PatKind::Error variant
Instead of via `Const::new_error`
2023-10-14 13:38:02 +02:00
Michael Goulet
e805151fd4 Bless tests and new warnings due to formatting changes 2023-10-13 09:31:36 +00:00
Michael Goulet
b2d2184ede Format all the let chains in compiler 2023-10-13 08:59:36 +00:00
bors
e20cb77021 Auto merge of #116391 - Nadrieril:constructorset, r=cjgillot
exhaustiveness: Rework constructor splitting

`SplitWildcard` was pretty opaque. I replaced it with a more legible abstraction: `ConstructorSet` represents the set of constructors for patterns of a given type. This clarifies responsibilities: `ConstructorSet` handles one clear task, and diagnostic-related shenanigans can be done separately.

I'm quite excited, I had has this in mind for years but could never quite introduce it. This opens up possibilities, including type-specific optimisations (like using a `FxHashSet` to collect enum variants, which had been [hackily attempted some years ago](https://github.com/rust-lang/rust/pull/76918)), my one-pass rewrite (https://github.com/rust-lang/rust/pull/116042), and future librarification.
2023-10-12 21:33:31 +00:00
Oli Scherer
eca786cd14 Remember the ErrorReported used to silence follow up errors instead of recreating it with delay_span_bug 2023-10-11 12:49:57 +00:00
Oli Scherer
e83467c3b8 Avoid emitting the non_exhaustive error if other errors already occurred 2023-10-11 12:49:57 +00:00
Oli Scherer
d1fd11f3f9 Prevent spurious unreachable pattern lints
Means you'll get more `non-exhaustive` patterns
2023-10-11 12:49:57 +00:00
bors
71704c4f84 Auto merge of #116623 - Nadrieril:validate-range-endpoints, r=oli-obk
Fix overflow checking in range patterns

When a range pattern contains an overflowing literal, if we're not careful we might not notice the overflow and use the wrapped value. This makes for confusing error messages because linting against overflowing literals is only done in a later pass. So when a range is invalid we check for overflows to provide a better error.

This check didn't use to handle negative types; this PR fixes that. First commit adds tests, second cleans up without changing behavior, third does the fix.

EDIT: while I was at it, I fixed a small annoyance about the span of the overflow lint on negated literals.

Fixes https://github.com/rust-lang/rust/issues/94239
2023-10-11 10:07:19 +00:00
Nadrieril
1baf8bf54d Fix range overflow checking 2023-10-11 04:55:55 +02:00
Nadrieril
1e1174b034 Rework error handling when lowering range endpoints 2023-10-11 04:54:49 +02:00
bors
5c3a0e932b Auto merge of #116427 - cjgillot:no-internal, r=oli-obk
Remove mir::LocalDecl::internal.

It does not serve any purpose, as we don't have typeck-based generator witnesses any more.
2023-10-05 09:59:14 +00:00
Jubilee
ea3454eabb
Rollup merge of #116223 - catandcoder:master, r=cjgillot
Fix misuses of a vs an

Fixes the misuse of "a" vs "an", according to English grammatical
expectations and using https://www.a-or-an.com/
2023-10-05 00:56:29 -07:00
Nadrieril
c1b29b338d Fix handling slices of empty types 2023-10-05 00:58:14 +02:00
Camille GILLOT
e63d19c4dd Remove mir::LocalDecl::internal. 2023-10-04 17:55:15 +00:00
Nadrieril
edf6a2d337 Clarify for review 2023-10-04 15:59:16 +02:00
cui fliter
f44d116e1f Fix misuses of a vs an
Signed-off-by: cui fliter <imcusg@gmail.com>
2023-10-04 08:01:11 +08:00
Nadrieril
fda0301b33 Don't collect seen if not needed 2023-10-03 19:58:47 +02:00
Nadrieril
2f4cab4d21 Clarify handling of hidden variants 2023-10-03 19:58:47 +02:00
Nadrieril
c1800ef93f Replace SplitWildcard with a cleaner ConstructorSet abstraction 2023-10-03 19:58:47 +02:00