Commit Graph

234 Commits

Author SHA1 Message Date
Nadrieril
2af01a2fef Abort on arity mismatch
As this can cause panics on array accesses later.
2024-03-04 19:35:33 +01:00
Guillaume Gomez
be31b6b6cd Add new pattern_complexity attribute to add possibility to limit and check recursion in pattern matching 2024-03-03 13:10:15 +01:00
bors
6cbf0926d5 Auto merge of #121728 - tgross35:f16-f128-step1-ty-updates, r=compiler-errors
Add stubs in IR and ABI for `f16` and `f128`

This is the very first step toward the changes in https://github.com/rust-lang/rust/pull/114607 and the [`f16` and `f128` RFC](https://rust-lang.github.io/rfcs/3453-f16-and-f128.html). It adds the types to `rustc_type_ir::FloatTy` and `rustc_abi::Primitive`, and just propagates those out as `unimplemented!` stubs where necessary.

These types do not parse yet so there is no feature gate, and it should be okay to use `unimplemented!`.

The next steps will probably be AST support with parsing and the feature gate.

r? `@compiler-errors`
cc `@Nilstrieb` suggested breaking the PR up in https://github.com/rust-lang/rust/pull/120645#issuecomment-1925900572
2024-03-01 03:36:11 +00:00
Guillaume Gomez
9df7f26b1b
Rollup merge of #121000 - Nadrieril:keep_all_fields, r=compiler-errors
pattern_analysis: rework how we hide empty private fields

Consider this:
```rust
mod foo {
  pub struct Bar {
    pub a: bool,
    b: !,
  }
}

fn match_a_bar(bar: foo::Bar) -> bool {
  match bar {
    Bar { a, .. } => a,
  }
}
```

Because the field `b` is private, matches outside the module are not allowed to observe the fact that `Bar` is empty. In particular `match bar {}` is valid within the module `foo` but an error outside (assuming `exhaustive_patterns`).

We currently handle this by hiding the field `b` when it's both private and empty. This means that the pattern `Bar { a, .. }` is lowered to `Bar(a, _)` if we're inside of `foo` and to `Bar(a)` outside. This involves a bit of a dance to keep field indices straight. But most importantly this makes pattern lowering depend on the module.

In this PR, I instead do nothing special when lowering. Only during analysis do we track whether a place must be skipped.

r? `@compiler-errors`
2024-02-29 17:08:37 +01:00
Matthias Krüger
eca6a249a6
Rollup merge of #121735 - Nadrieril:no-panic-on-type-error, r=compiler-errors
pattern analysis: Don't panic when encountering unexpected constructor

Tiny PR to fix https://github.com/rust-lang/rust-analyzer/issues/16656

r? ``@compiler-errors``
2024-02-29 00:17:00 +01:00
Trevor Gross
e3f63d9375 Add f16 and f128 to rustc_type_ir::FloatTy and rustc_abi::Primitive
Make changes necessary to support these types in the compiler.
2024-02-28 12:58:32 -05:00
Nadrieril
c918893b63 Rename Skip to PrivateUninhabited 2024-02-28 17:56:01 +01:00
Nadrieril
39441e4cdd Simplify 2024-02-28 17:47:19 +01:00
Nadrieril
ea38166390 Don't filter out skipped fields 2024-02-28 17:47:19 +01:00
Nadrieril
4f7f06777b Add special Skip constructor 2024-02-28 17:47:19 +01:00
Nadrieril
ab06037269 Push the decision to skip fields further down 2024-02-28 17:47:19 +01:00
Nadrieril
be01e28dce Push down the decision to skip fields 2024-02-28 17:47:19 +01:00
Nadrieril
12b991d9f8 Don't panic when encountering unexpected constructor 2024-02-28 13:28:27 +01:00
Nicholas Nethercote
899cb40809 Rename DiagnosticBuilder as Diag.
Much better!

Note that this involves renaming (and updating the value of)
`DIAGNOSTIC_BUILDER` in clippy.
2024-02-28 08:55:35 +11:00
Matthias Krüger
86a35c07b2
Rollup merge of #121324 - Nadrieril:unspecialize, r=cjgillot
pattern_analysis: factor out unspecialization

Just moving a dense bit of logic into its own method.
2024-02-25 17:05:21 +01:00
Matthias Krüger
86a7fc840f compiler: clippy::complexity fixes 2024-02-23 19:56:35 +01:00
bors
29f87ade9d Auto merge of #120576 - nnethercote:merge-Diagnostic-DiagnosticBuilder, r=davidtwco
Overhaul `Diagnostic` and `DiagnosticBuilder`

Implements the first part of https://github.com/rust-lang/compiler-team/issues/722, which moves functionality and use away from `Diagnostic`, onto `DiagnosticBuilder`.

Likely follow-ups:
- Move things around, because this PR was written to minimize diff size, so some things end up in sub-optimal places. E.g. `DiagnosticBuilder` has impls in both `diagnostic.rs` and `diagnostic_builder.rs`.
- Rename `Diagnostic` as `DiagInner` and `DiagnosticBuilder` as `Diag`.

r? `@davidtwco`
2024-02-20 12:05:09 +00:00
bors
bcea3cb748 Auto merge of #120692 - Nadrieril:move-column-analysis-to-placeinfo, r=compiler-errors
pattern_analysis: Move constructor selection logic to `PlaceInfo`

This is a small refactor PR. There was a dense bit of constructor-related logic in `compute_exhaustiveness_and_usefulness`. I'm moving it out into a `PlaceInfo` method to make it easier to follow both separately. I also have plans that will complicate it further so it's good that it's somewhat encapsulated.

r? `@compiler-errors`
2024-02-20 04:57:15 +00:00
Nadrieril
47b21730c4 Factor out unspecialization 2024-02-20 04:45:18 +01:00
Nicholas Nethercote
f6f8779843 Reduce capabilities of Diagnostic.
Currently many diagnostic modifier methods are available on both
`Diagnostic` and `DiagnosticBuilder`. This commit removes most of them
from `Diagnostic`. To minimize the diff size, it keeps them within
`diagnostic.rs` but changes the surrounding `impl Diagnostic` block to
`impl DiagnosticBuilder`. (I intend to move things around later, to give
a more sensible code layout.)

`Diagnostic` keeps a few methods that it still needs, like `sub`,
`arg`, and `replace_args`.

The `forward!` macro, which defined two additional methods per call
(e.g. `note` and `with_note`), is replaced by the `with_fn!` macro,
which defines one additional method per call (e.g. `with_note`). It's
now also only used when necessary -- not all modifier methods currently
need a `with_*` form. (New ones can be easily added as necessary.)

All this also requires changing `trait AddToDiagnostic` so its methods
take `DiagnosticBuilder` instead of `Diagnostic`, which leads to many
mechanical changes. `SubdiagnosticMessageOp` gains a type parameter `G`.

There are three subdiagnostics -- `DelayedAtWithoutNewline`,
`DelayedAtWithNewline`, and `InvalidFlushedDelayedDiagnosticLevel` --
that are created within the diagnostics machinery and appended to
external diagnostics. These are handled at the `Diagnostic` level, which
means it's now hard to construct them via `derive(Diagnostic)`, so
instead we construct them by hand. This has no effect on what they look
like when printed.

There are lots of new `allow` markers for `untranslatable_diagnostics`
and `diagnostics_outside_of_impl`. This is because
`#[rustc_lint_diagnostics]` annotations were present on the `Diagnostic`
modifier methods, but missing from the `DiagnosticBuilder` modifier
methods. They're now present.
2024-02-20 13:22:17 +11:00
bors
0a5b998c57 Auto merge of #120991 - matthiaskrgr:rollup-f8kw2st, r=matthiaskrgr
Rollup of 8 pull requests

Successful merges:

 - #118983 (Warn on references casting to bigger memory layout)
 - #119451 (Gate PR CI on clippy correctness lints)
 - #120273 (compiletest: few naive improvements)
 - #120950 (Fix async closures in CTFE)
 - #120958 (Dejargonize `subst`)
 - #120965 (Add lahfsahf and prfchw target feature)
 - #120970 (add another test for promoteds-in-static)
 - #120979 (Update books)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-02-13 00:31:53 +00:00
bors
74c3f5a146 Auto merge of #120324 - Nadrieril:remove-interior-mutability, r=compiler-errors
pattern_analysis: track usefulness without interior mutability

Because of or-patterns, exhaustiveness needs to be able to lint if a sub-pattern is redundant, e.g. in `Some(_) | Some(true)`. So far the only sane solution I had found was interior mutability. This is a bit of an abstraction leak, and would become a footgun if we ever reused the same `DeconstructedPat`. This PR replaces interior mutability with an address-indexed hashmap, which is logically equivalent.
2024-02-12 22:16:58 +00:00
Shoyu Vanilla
3856df059e Dejargnonize subst 2024-02-12 15:46:35 +09:00
Matthias Krüger
46a0448405
Rollup merge of #120693 - nnethercote:invert-diagnostic-lints, r=davidtwco
Invert diagnostic lints.

That is, change `diagnostic_outside_of_impl` and `untranslatable_diagnostic` from `allow` to `deny`, because more than half of the compiler has been converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow` attributes, which proves that this change is warranted.

r? ````@davidtwco````
2024-02-09 14:41:50 +01:00
Matthias Krüger
4ffb1a7f3d
Rollup merge of #120590 - compiler-errors:dead, r=Nilstrieb
Remove unused args from functions

`#[instrument]` suppresses the unused arguments from a function, *and* suppresses unused methods too! This PR removes things which are only used via `#[instrument]` calls, and fixes some other errors (privacy?) that I will comment inline.

It's possible that some of these arguments were being passed in for the purposes of being instrumented, but I am unconvinced by most of them.
2024-02-08 20:34:57 +01:00
Nadrieril
778c7e1db4 Move constructor selection logic to PlaceInfo 2024-02-08 15:34:17 +01:00
Nadrieril
3602b9d817 Decide which constructors to report earlier.
This gets rid of `report_individual_missing_ctors`
2024-02-08 15:34:17 +01:00
Nadrieril
924d6cd1a6 Tweak how we record missing constructors
This is slower but also not a performance-sensitive path.
2024-02-08 15:34:17 +01:00
Matthias Krüger
87e1e05aa1
Rollup merge of #120734 - nnethercote:SubdiagnosticMessageOp, r=compiler-errors
Add `SubdiagnosticMessageOp` as a trait alias.

It avoids a lot of repetition.

r? matthewjasper
2024-02-08 09:06:36 +01:00
Nicholas Nethercote
6b175a848d Add SubdiagnosticMessageOp as a trait alias.
It avoids a lot of repetition.
2024-02-08 13:02:44 +11:00
Nadrieril
9dca6be7b8 Prefer "0..MAX not covered" to "_ not covered" 2024-02-07 23:25:11 +01:00
Nadrieril
be29cd173a Use a unique id instead of by-address indexing 2024-02-07 23:16:47 +01:00
Nadrieril
8465c82b64 Cleanup comments and dead code 2024-02-07 23:16:47 +01:00
Nadrieril
9715df3f44 Track redundant subpatterns without interior mutability 2024-02-07 23:16:47 +01:00
Nadrieril
cb3ce6645f Move usefulness-specific pattern computations to usefulness 2024-02-07 23:10:51 +01:00
Guillaume Boisseau
3328ee86bb
Rollup merge of #120633 - Nadrieril:place_info, r=compiler-errors
pattern_analysis: gather up place-relevant info

We track 3 things about each place during exhaustiveness: its type, its (data) validity, and whether it's the scrutinee place. This PR gathers all three into a single struct.

r? `````@compiler-errors`````
2024-02-07 18:24:44 +01:00
Matthias Krüger
ce32d4862b
Rollup merge of #120331 - Nadrieril:no-arena, r=compiler-errors
pattern_analysis: use a plain `Vec` in `DeconstructedPat`

The use of an arena-allocated slice in `DeconstructedPat` dates to when we needed the arena anyway for lifetime reasons. Now that we don't, I'm thinking that if `thir::Pat` can use plain old `Vec`s, maybe so can I.

r? ```@ghost```
2024-02-06 22:45:40 +01:00
Michael Goulet
c567eddec2 Add CoroutineClosure to TyKind, AggregateKind, UpvarArgs 2024-02-06 02:22:58 +00:00
Nicholas Nethercote
0ac1195ee0 Invert diagnostic lints.
That is, change `diagnostic_outside_of_impl` and
`untranslatable_diagnostic` from `allow` to `deny`, because more than
half of the compiler has be converted to use translated diagnostics.

This commit removes more `deny` attributes than it adds `allow`
attributes, which proves that this change is warranted.
2024-02-06 13:12:33 +11:00
Nadrieril
6cac1c459e Track is_top_level via PlaceInfo 2024-02-06 00:54:39 +01:00
Nadrieril
411967c078 Zip together place_ty and place_validity 2024-02-06 00:54:39 +01:00
bors
f067fd6084 Auto merge of #120313 - Nadrieril:graceful-error, r=compiler-errors
pattern_analysis: Gracefully abort on type incompatibility

This leaves the option for a consumer of the crate to return `Err` instead of panicking on type error. rust-analyzer could use that (e.g. https://github.com/rust-lang/rust-analyzer/issues/15808).

Since the only use of `TypeCx::bug` is in `Constructor::is_covered_by`, it is tempting to return `false` instead of `Err()`, but that would cause "non-exhaustive match" false positives.

r? `@compiler-errors`
2024-02-05 21:36:25 +00:00
Matthias Krüger
ceeaa8a852
Rollup merge of #120517 - Nadrieril:lower-never-as-wildcard, r=compiler-errors
never patterns: It is correct to lower `!` to `_`.

This is just a comment update but a non-trivial one: it is correct to lower `!` patterns as `_`. The reasoning is that `!` matches all the possible values of the type, since the type is empty. Moreover, we do want to warn that the `Err` is redundant in:
```rust
match x {
  !,
  Err(!),
}
```
which is consistent with `!` behaving like a wildcard.

I did try to introduce `Constructor::Never` and it ended up needing to behave exactly like `Constructor::Wildcard`.

r? ```@compiler-errors```
2024-02-03 22:25:15 +01:00
Matthias Krüger
f3ebf1e50f
Rollup merge of #120516 - Nadrieril:cleanup-impls, r=compiler-errors
pattern_analysis: cleanup manual impls

https://github.com/rust-lang/rust/pull/120420 introduced some unneeded manual impls. I remove them here.

r? ```@Nilstrieb```
2024-02-03 22:25:14 +01:00
Michael Goulet
6b2a8249c1 Remove dead args from functions 2024-02-02 22:47:26 +00:00
Nadrieril
f65fe3ba59 Remove pattern_arena from RustcMatchCheckCtxt 2024-01-31 19:25:40 +01:00
Nadrieril
be77cf86ba Use a Vec instead of a slice in DeconstructedPat 2024-01-31 19:25:40 +01:00
Nadrieril
400dc46a05 Gracefully abort on type incompatibility
Since the only use of `TypeCx::bug` is in `Constructor::is_covered_by`,
it is tempting to return `false` instead of `Err()`, but that would
cause "non-exhaustive match" false positives.
2024-01-31 19:22:48 +01:00
Nadrieril
ee2cddd8f2 It is correct to lower ! to _. 2024-01-31 01:43:41 +01:00
Nadrieril
40402cbada Manual Debug impls are not needed since TypeCx: Debug 2024-01-31 01:32:05 +01:00
Nadrieril
15b473451c Remove unused Constructor: PartialEq impl 2024-01-31 01:32:05 +01:00
Nadrieril
59031429c5 Separate PlaceCtxt from UsefulnessCtxt 2024-01-30 17:07:06 +01:00
Nadrieril
6ef836246b Make PatternColumn part of the public API 2024-01-30 17:06:52 +01:00
Nadrieril
83e88c6dfc Repurpose MatchCtxt for usefulness only 2024-01-30 17:06:51 +01:00
Nadrieril
cb0e8c508c Limit the use of PlaceCtxt 2024-01-30 17:06:30 +01:00
Nadrieril
0b2579a1b6 Make PatternColumn generic in Cx 2024-01-30 16:57:44 +01:00
Laurențiu Nicola
f5c78955c8 Stop using derivative in rustc_pattern_analysis 2024-01-27 14:21:01 +02:00
Matthias Krüger
a37fa37281
Rollup merge of #118803 - Nadrieril:min-exhaustive-patterns, r=compiler-errors
Add the `min_exhaustive_patterns` feature gate

## Motivation

Pattern-matching on empty types is tricky around unsafe code. For that reason, current stable rust conservatively requires arms for empty types in all but the simplest case. It has long been the intention to allow omitting empty arms when it's safe to do so. The [`exhaustive_patterns`](https://github.com/rust-lang/rust/issues/51085) feature allows the omission of all empty arms, but hasn't been stabilized because that was deemed dangerous around unsafe code.

## Proposal

This feature aims to stabilize an uncontroversial subset of exhaustive_patterns. Namely: when `min_exhaustive_patterns` is enabled and the data we're matching on is guaranteed to be valid by rust's operational semantics, then we allow empty arms to be omitted. E.g.:

```rust
let x: Result<T, !> = foo();
match x { // ok
    Ok(y) => ...,
}
let Ok(y) = x; // ok
```

If the place is not guaranteed to hold valid data (namely ptr dereferences, ref dereferences (conservatively) and union field accesses), then we keep stable behavior i.e. we (usually) require arms for the empty cases.

```rust
unsafe {
    let ptr: *const Result<u32, !> = ...;
    match *ptr {
        Ok(x) => { ... }
        Err(_) => { ... } // still required
    }
}
let foo: Result<u32, &!> = ...;
match foo {
    Ok(x) => { ... }
    Err(&_) => { ... } // still required because of the dereference
}
unsafe {
    let ptr: *const ! = ...;
    match *ptr {} // already allowed on stable
}
```

Note that we conservatively consider that a valid reference can point to invalid data, hence we don't allow arms of type `&!` and similar cases to be omitted. This could eventually change depending on [opsem decisions](https://github.com/rust-lang/unsafe-code-guidelines/issues/413). Whenever opsem is undecided on a case, we conservatively keep today's stable behavior.

I proposed this behavior in the [`never_patterns`](https://github.com/rust-lang/rust/issues/118155) feature gate but it makes sense on its own and could be stabilized more quickly. The two proposals nicely complement each other.

## Unresolved Questions

Part of the question is whether this requires an RFC. I'd argue this doesn't need one since there is no design question beyond the intent to omit unreachable patterns, but I'm aware the problem can be framed in ways that require design (I'm thinking of the [original never patterns proposal](https://smallcultfollowing.com/babysteps/blog/2018/08/13/never-patterns-exhaustive-matching-and-uninhabited-types-oh-my/), which would frame this behavior as "auto-nevering" happening).

EDIT: I initially proposed a future-compatibility lint as part of this feature, I don't anymore.
2024-01-26 06:36:36 +01:00
Matthias Krüger
a1ecced532
Rollup merge of #120318 - Nadrieril:share-debug-impl, r=compiler-errors
pattern_analysis: Reuse most of the `DeconstructedPat` `Debug` impl

The `DeconstructedPat: Debug` is best-effort because we'd need `tcx` to get things like field names etc. Since rust-analyzer has a similar constraint, this PR moves most the impl to be shared between the two. While I was at it I also fixed a nit in the `IntRange: Debug` impl.

r? `@compiler-errors`
2024-01-25 08:39:45 +01:00
Nadrieril
95a14d43d7 Implement feature gate logic 2024-01-25 00:12:32 +01:00
Nadrieril
354b45f528 Improve Range: Debug impl 2024-01-24 20:09:30 +01:00
Nadrieril
bdab213993 Most of the DeconstructedPat Debug impl is reusable 2024-01-24 20:04:33 +01:00
Nadrieril
e088016f9d Let ctor_sub_tys return any Iterator they want
Since we always clone and allocate the types somewhere else ourselves,
no need to ask for `Cx` to do the allocation.
2024-01-24 16:55:26 +01:00
Nicholas Nethercote
e164cf30f8 Rename TyCtxt::emit_spanned_lint as TyCtxt::emit_node_span_lint. 2024-01-23 08:09:05 +11:00
Nadrieril
796cdc590c Remove Ty: Copy bound 2024-01-20 15:22:14 +01:00
Matthias Krüger
2587100a9b
Rollup merge of #119835 - Nadrieril:simplify-empty-logic, r=compiler-errors
Exhaustiveness: simplify empty pattern logic

The logic that handles empty patterns had gotten quite convoluted. This PR simplifies it a lot. I tried to make the logic as easy as possible to follow; this only does logically equivalent changes.

The first commit is a drive-by comment clarification that was requested after another PR a while back.

r? `@compiler-errors`
2024-01-19 19:27:00 +01:00
Matthias Krüger
3a3242a0f9
Rollup merge of #120039 - Nadrieril:remove-idx, r=compiler-errors
pat_analysis: Don't rely on contiguous `VariantId`s outside of rustc

Today's pattern_analysis uses `BitSet` and `IndexVec` on the provided enum variant ids, which only makes sense if these ids count the variants from 0. In rust-analyzer, the variant ids are global interning ids, which would make `BitSet` and `IndexVec` ridiculously wasteful. In this PR I add some shims to use `FxHashSet`/`FxHashMap` instead outside of rustc.

r? ```@compiler-errors```
2024-01-17 20:21:23 +01:00
Nadrieril
19d6f068ee Don't rely on contiguous VariantIds outside of rustc 2024-01-17 03:09:06 +01:00
Nadrieril
448c4a4efb Remove the unused overlapping_range_endpoints Vec 2024-01-15 19:27:06 +01:00
Nadrieril
8b66f497eb Lint overlapping ranges directly from exhaustiveness 2024-01-15 19:27:06 +01:00
Nadrieril
d95644d3ae Simplify empty pattern logic some more 2024-01-15 16:56:18 +01:00
Nadrieril
de77f1a86e Simplify empty pattern logic a bit 2024-01-15 16:56:18 +01:00
Nadrieril
edb27a306a Make all the empty pattern decisions in usefulness 2024-01-15 16:56:18 +01:00
Nadrieril
bf913ad0ae Simplify use of ValidityConstraint
We had reached a point where the shenanigans about omitting empty arms
are unnecessary.
2024-01-15 16:52:51 +01:00
Nadrieril
db36304102 rustc_pattern_analysis no longer needs to be passed an arena 2024-01-12 18:55:27 +01:00
Nadrieril
a24f4db41b Only lint ranges that really overlap 2024-01-11 14:04:11 +01:00
Nadrieril
6f6ba2571d Factor out collection of overlapping ranges 2024-01-11 13:59:41 +01:00
Nadrieril
89d01babe6 Track row intersections 2024-01-11 13:56:09 +01:00
bors
65b323b168 Auto merge of #119837 - matthiaskrgr:rollup-l2olpad, r=matthiaskrgr
Rollup of 11 pull requests

Successful merges:

 - #115046 (Use version-sorting for all sorting)
 - #118915 (Add some comments, add `can_define_opaque_ty` check to `try_normalize_ty_recur`)
 - #119006 (Fix is_global special address handling)
 - #119637 (Pass LLVM error message back to pass wrapper.)
 - #119715 (Exhaustiveness: abort on type error)
 - #119763 (Cleanup things in and around `Diagnostic`)
 - #119788 (change function name in comments)
 - #119790 (Fix all_trait* methods to return all traits available in StableMIR)
 - #119803 (Silence some follow-up errors [1/x])
 - #119804 (Stabilize mutex_unpoison feature)
 - #119832 (Meta: Add project const traits to triagebot config)

r? `@ghost`
`@rustbot` modify labels: rollup
2024-01-11 02:10:34 +00:00
Nadrieril
4a1889e3fd Document the new expand_and_push method 2024-01-09 16:32:17 +01:00
Nadrieril
5c65e9fdaf Avoid PatOrWild glob import 2024-01-09 16:22:11 +01:00
Nadrieril
4b2e8bc841 Abort analysis on type error 2024-01-07 22:13:08 +01:00
Nadrieril
07d5f19426 Add an error path to the algorithm 2024-01-07 22:13:08 +01:00
Nadrieril
1a3edc169b We only need the arity of the subtype list now 2024-01-07 19:20:19 +01:00
Nadrieril
4ae2840e84 Use special enum to represent algorithm-generated wildcards in the matrix 2024-01-07 19:20:19 +01:00
Nadrieril
30ca1c0a5d Remove incorrect assert
It's incorrect because `CtorSet::split` returns a non-present
constructor into `present` in one specific case: variable-length slices
of an empty type. That's because empty constructors of arity 0 break the
algorithm. This is a tricky corner case that's hard to do cleanly. The
assert wasn't adding much anyway.
2024-01-07 16:45:44 +01:00
Nadrieril
4c2386137a Factor out pushing onto PatternColumn 2024-01-07 16:45:44 +01:00
Nadrieril
50b197c6ee Reuse ctor_sub_tys when we have one around 2024-01-06 18:03:13 +01:00
Nadrieril
d40f1b1172 Remove Matrix.wildcard_row
It was only used to track types and relevancy, so may as well store that
directly.
2024-01-06 17:56:54 +01:00
bors
5bcd86d89b Auto merge of #119329 - Nadrieril:reveal-opaques-early, r=compiler-errors
Exhaustiveness: Statically enforce revealing of opaques

In https://github.com/rust-lang/rust/pull/116821 it was decided that exhaustiveness should operate on the hidden type of an opaque type when relevant. This PR makes sure we consistently reveal opaques within exhaustiveness. This makes it possible to remove `reveal_opaque_ty` from the `TypeCx` trait which was an unfortunate implementation detail.

r? `@compiler-errors`
2024-01-06 02:00:24 +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
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
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
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
Michael Goulet
4ae024c754 Elide more lifetimes 2023-12-26 02:12:33 +00:00
Michael Goulet
ae40f6a7ff Clean up more lifetimes 2023-12-26 02:06:39 +00:00
Michael Goulet
b91a98ba10 Even more 2023-12-26 02:02:01 +00:00
Michael Goulet
eebb2abe0b Yeet some lifetimes 2023-12-26 01:59:18 +00:00
bors
1a086e49f1 Auto merge of #118796 - Nadrieril:fix-exponential-id-match-2, r=cjgillot
Exhaustiveness: Improve complexity on some wide matches

https://github.com/rust-lang/rust/issues/118437 revealed an exponential case in exhaustiveness checking. While [exponential cases are unavoidable](https://compilercrim.es/rust-np/), this one only showed up after my https://github.com/rust-lang/rust/pull/117611 rewrite of the algorithm. I remember anticipating a case like this and dismissing it as unrealistic, but here we are :').

The tricky match is as follows:
```rust
match command {
    BaseCommand { field01: true, .. } => {}
    BaseCommand { field02: true, .. } => {}
    BaseCommand { field03: true, .. } => {}
    BaseCommand { field04: true, .. } => {}
    BaseCommand { field05: true, .. } => {}
    BaseCommand { field06: true, .. } => {}
    BaseCommand { field07: true, .. } => {}
    BaseCommand { field08: true, .. } => {}
    BaseCommand { field09: true, .. } => {}
    BaseCommand { field10: true, .. } => {}
    // ...20 more of the same

    _ => {}
}
```

To fix this, this PR formalizes a concept of "relevancy" (naming is hard) that was already used to decide what patterns to report. Now we track it for every row, which in wide matches like the above can drastically cut on the number of cases we explore. After this fix, the above match is checked with linear-many cases instead of exponentially-many.

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

r? `@cjgillot`
2023-12-24 14:40:36 +00:00
Nadrieril
efb04e6572 Rework the explanation of relevancy 2023-12-23 22:43:06 +01: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
Nadrieril
34307ab7c5 Reveal empty opaques in depth 2023-12-23 14:59:12 +01:00
Nadrieril
71e83347bb Improve performance on wide matches 2023-12-23 13:11:38 +01: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
Nadrieril
c6aa16c469 Use derivative for better derive bounds 2023-12-23 00:04:20 +01:00
Nadrieril
2a87bae48d Reveal opaque types in exhaustiveness checking 2023-12-20 14:43:00 +01: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
Matthias Krüger
74d81d15b4 NFC: do not clone types that are copy 2023-12-15 23:19:51 +01:00
Nadrieril
3016c29628 s/MatchCx/TypeCx/ 2023-12-15 17:26:19 +01:00
Nadrieril
4bcf66f875 Introduce MatchCtxt 2023-12-15 16:58:38 +01:00
Nadrieril
60ea14bfaa s/PatCtxt/PlaceCtxt/ 2023-12-15 16:58:38 +01:00
Nadrieril
1e89a38423 pattern_analysis doesn't need to know what spans are 2023-12-15 16:58:38 +01:00
Nadrieril
8c5e89907c Address review comments 2023-12-15 16:58:38 +01:00
Nadrieril
e10b165775 s/RustcCtxt/RustcMatchCheckCtxt/ 2023-12-15 16:58:38 +01:00
Nadrieril
63c5b008e1 Make the crate compile on stable 2023-12-15 16:58:38 +01:00
Nadrieril
e646c9f723 Make the rustc_data_structures dependency optional 2023-12-15 16:58:38 +01:00
Nadrieril
16bd6ac3ed Gate rustc-specific code under a feature 2023-12-15 16:58:37 +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
081c3dcf43 Remove all matching on ty.kind() outside cx 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
2a1acc26a0
Update compiler/rustc_pattern_analysis/src/constructor.rs
add note that `missing_empty` is cleared now

Co-authored-by: Nadrieril <Nadrieril@users.noreply.github.com>
2023-12-12 21:12:19 +01:00
Matthias Krüger
6892fcd690 simplify merging of two vecs 2023-12-12 18:42:37 +01:00
Nadrieril
43714edb6f Fix doc links 2023-12-11 12:53:01 +01:00
Nadrieril
5d6c539c2d Fix item visibilities 2023-12-11 11:20:55 +01:00
Nadrieril
de3f983bcd Make MaybeInfiniteInt rustc-independent 2023-12-11 11:20:55 +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