-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
check_match.rs
1282 lines (1205 loc) · 48 KB
/
check_match.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use rustc_arena::{DroplessArena, TypedArena};
use rustc_ast::Mutability;
use rustc_data_structures::fx::FxIndexSet;
use rustc_data_structures::stack::ensure_sufficient_stack;
use rustc_errors::codes::*;
use rustc_errors::{struct_span_code_err, Applicability, ErrorGuaranteed, MultiSpan};
use rustc_hir::def::*;
use rustc_hir::def_id::LocalDefId;
use rustc_hir::{self as hir, BindingMode, ByRef, HirId};
use rustc_middle::bug;
use rustc_middle::middle::limits::get_limit_size;
use rustc_middle::thir::visit::Visitor;
use rustc_middle::thir::*;
use rustc_middle::ty::print::with_no_trimmed_paths;
use rustc_middle::ty::{self, AdtDef, Ty, TyCtxt};
use rustc_pattern_analysis::errors::Uncovered;
use rustc_pattern_analysis::rustc::{
Constructor, DeconstructedPat, MatchArm, RedundancyExplanation, RevealedTy,
RustcPatCtxt as PatCtxt, Usefulness, UsefulnessReport, WitnessPat,
};
use rustc_session::lint::builtin::{
BINDINGS_WITH_VARIANT_NAME, IRREFUTABLE_LET_PATTERNS, UNREACHABLE_PATTERNS,
};
use rustc_span::hygiene::DesugaringKind;
use rustc_span::{sym, Span};
use tracing::instrument;
use crate::errors::*;
use crate::fluent_generated as fluent;
pub(crate) fn check_match(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Result<(), ErrorGuaranteed> {
let typeck_results = tcx.typeck(def_id);
let (thir, expr) = tcx.thir_body(def_id)?;
let thir = thir.borrow();
let pattern_arena = TypedArena::default();
let dropless_arena = DroplessArena::default();
let mut visitor = MatchVisitor {
tcx,
thir: &*thir,
typeck_results,
param_env: tcx.param_env(def_id),
lint_level: tcx.local_def_id_to_hir_id(def_id),
let_source: LetSource::None,
pattern_arena: &pattern_arena,
dropless_arena: &dropless_arena,
error: Ok(()),
};
visitor.visit_expr(&thir[expr]);
let origin = match tcx.def_kind(def_id) {
DefKind::AssocFn | DefKind::Fn => "function argument",
DefKind::Closure => "closure argument",
// other types of MIR don't have function parameters, and we don't need to
// categorize those for the irrefutable check.
_ if thir.params.is_empty() => "",
kind => bug!("unexpected function parameters in THIR: {kind:?} {def_id:?}"),
};
for param in thir.params.iter() {
if let Some(box ref pattern) = param.pat {
visitor.check_binding_is_irrefutable(pattern, origin, None, None);
}
}
visitor.error
}
#[derive(Debug, Copy, Clone, PartialEq)]
enum RefutableFlag {
Irrefutable,
Refutable,
}
use RefutableFlag::*;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LetSource {
None,
PlainLet,
IfLet,
IfLetGuard,
LetElse,
WhileLet,
}
struct MatchVisitor<'p, 'tcx> {
tcx: TyCtxt<'tcx>,
param_env: ty::ParamEnv<'tcx>,
typeck_results: &'tcx ty::TypeckResults<'tcx>,
thir: &'p Thir<'tcx>,
lint_level: HirId,
let_source: LetSource,
pattern_arena: &'p TypedArena<DeconstructedPat<'p, 'tcx>>,
dropless_arena: &'p DroplessArena,
/// Tracks if we encountered an error while checking this body. That the first function to
/// report it stores it here. Some functions return `Result` to allow callers to short-circuit
/// on error, but callers don't need to store it here again.
error: Result<(), ErrorGuaranteed>,
}
// Visitor for a thir body. This calls `check_match`, `check_let` and `check_let_chain` as
// appropriate.
impl<'p, 'tcx> Visitor<'p, 'tcx> for MatchVisitor<'p, 'tcx> {
fn thir(&self) -> &'p Thir<'tcx> {
self.thir
}
#[instrument(level = "trace", skip(self))]
fn visit_arm(&mut self, arm: &'p Arm<'tcx>) {
self.with_lint_level(arm.lint_level, |this| {
if let Some(expr) = arm.guard {
this.with_let_source(LetSource::IfLetGuard, |this| {
this.visit_expr(&this.thir[expr])
});
}
this.visit_pat(&arm.pattern);
this.visit_expr(&self.thir[arm.body]);
});
}
#[instrument(level = "trace", skip(self))]
fn visit_expr(&mut self, ex: &'p Expr<'tcx>) {
match ex.kind {
ExprKind::Scope { value, lint_level, .. } => {
self.with_lint_level(lint_level, |this| {
this.visit_expr(&this.thir[value]);
});
return;
}
ExprKind::If { cond, then, else_opt, if_then_scope: _ } => {
// Give a specific `let_source` for the condition.
let let_source = match ex.span.desugaring_kind() {
Some(DesugaringKind::WhileLoop) => LetSource::WhileLet,
_ => LetSource::IfLet,
};
self.with_let_source(let_source, |this| this.visit_expr(&self.thir[cond]));
self.with_let_source(LetSource::None, |this| {
this.visit_expr(&this.thir[then]);
if let Some(else_) = else_opt {
this.visit_expr(&this.thir[else_]);
}
});
return;
}
ExprKind::Match { scrutinee, scrutinee_hir_id: _, box ref arms, match_source } => {
self.check_match(scrutinee, arms, match_source, ex.span);
}
ExprKind::Let { box ref pat, expr } => {
self.check_let(pat, Some(expr), ex.span);
}
ExprKind::LogicalOp { op: LogicalOp::And, .. }
if !matches!(self.let_source, LetSource::None) =>
{
let mut chain_refutabilities = Vec::new();
let Ok(()) = self.visit_land(ex, &mut chain_refutabilities) else { return };
// If at least one of the operands is a `let ... = ...`.
if chain_refutabilities.iter().any(|x| x.is_some()) {
self.check_let_chain(chain_refutabilities, ex.span);
}
return;
}
_ => {}
};
self.with_let_source(LetSource::None, |this| visit::walk_expr(this, ex));
}
fn visit_stmt(&mut self, stmt: &'p Stmt<'tcx>) {
match stmt.kind {
StmtKind::Let {
box ref pattern, initializer, else_block, lint_level, span, ..
} => {
self.with_lint_level(lint_level, |this| {
let let_source =
if else_block.is_some() { LetSource::LetElse } else { LetSource::PlainLet };
this.with_let_source(let_source, |this| {
this.check_let(pattern, initializer, span)
});
visit::walk_stmt(this, stmt);
});
}
StmtKind::Expr { .. } => {
visit::walk_stmt(self, stmt);
}
}
}
}
impl<'p, 'tcx> MatchVisitor<'p, 'tcx> {
#[instrument(level = "trace", skip(self, f))]
fn with_let_source(&mut self, let_source: LetSource, f: impl FnOnce(&mut Self)) {
let old_let_source = self.let_source;
self.let_source = let_source;
ensure_sufficient_stack(|| f(self));
self.let_source = old_let_source;
}
fn with_lint_level<T>(
&mut self,
new_lint_level: LintLevel,
f: impl FnOnce(&mut Self) -> T,
) -> T {
if let LintLevel::Explicit(hir_id) = new_lint_level {
let old_lint_level = self.lint_level;
self.lint_level = hir_id;
let ret = f(self);
self.lint_level = old_lint_level;
ret
} else {
f(self)
}
}
/// Visit a nested chain of `&&`. Used for if-let chains. This must call `visit_expr` on the
/// subexpressions we are not handling ourselves.
fn visit_land(
&mut self,
ex: &'p Expr<'tcx>,
accumulator: &mut Vec<Option<(Span, RefutableFlag)>>,
) -> Result<(), ErrorGuaranteed> {
match ex.kind {
ExprKind::Scope { value, lint_level, .. } => self.with_lint_level(lint_level, |this| {
this.visit_land(&this.thir[value], accumulator)
}),
ExprKind::LogicalOp { op: LogicalOp::And, lhs, rhs } => {
// We recurse into the lhs only, because `&&` chains associate to the left.
let res_lhs = self.visit_land(&self.thir[lhs], accumulator);
let res_rhs = self.visit_land_rhs(&self.thir[rhs])?;
accumulator.push(res_rhs);
res_lhs
}
_ => {
let res = self.visit_land_rhs(ex)?;
accumulator.push(res);
Ok(())
}
}
}
/// Visit the right-hand-side of a `&&`. Used for if-let chains. Returns `Some` if the
/// expression was ultimately a `let ... = ...`, and `None` if it was a normal boolean
/// expression. This must call `visit_expr` on the subexpressions we are not handling ourselves.
fn visit_land_rhs(
&mut self,
ex: &'p Expr<'tcx>,
) -> Result<Option<(Span, RefutableFlag)>, ErrorGuaranteed> {
match ex.kind {
ExprKind::Scope { value, lint_level, .. } => {
self.with_lint_level(lint_level, |this| this.visit_land_rhs(&this.thir[value]))
}
ExprKind::Let { box ref pat, expr } => {
let expr = &self.thir()[expr];
self.with_let_source(LetSource::None, |this| {
this.visit_expr(expr);
});
Ok(Some((ex.span, self.is_let_irrefutable(pat, Some(expr))?)))
}
_ => {
self.with_let_source(LetSource::None, |this| {
this.visit_expr(ex);
});
Ok(None)
}
}
}
fn lower_pattern(
&mut self,
cx: &PatCtxt<'p, 'tcx>,
pat: &'p Pat<'tcx>,
) -> Result<&'p DeconstructedPat<'p, 'tcx>, ErrorGuaranteed> {
if let Err(err) = pat.pat_error_reported() {
self.error = Err(err);
Err(err)
} else {
// Check the pattern for some things unrelated to exhaustiveness.
let refutable = if cx.refutable { Refutable } else { Irrefutable };
let mut err = Ok(());
pat.walk_always(|pat| {
check_borrow_conflicts_in_at_patterns(self, pat);
check_for_bindings_named_same_as_variants(self, pat, refutable);
err = err.and(check_never_pattern(cx, pat));
});
err?;
Ok(self.pattern_arena.alloc(cx.lower_pat(pat)))
}
}
/// Inspects the match scrutinee expression to determine whether the place it evaluates to may
/// hold invalid data.
fn is_known_valid_scrutinee(&self, scrutinee: &Expr<'tcx>) -> bool {
use ExprKind::*;
match &scrutinee.kind {
// Pointers can validly point to a place with invalid data. It is undecided whether
// references can too, so we conservatively assume they can.
Deref { .. } => false,
// Inherit validity of the parent place, unless the parent is an union.
Field { lhs, .. } => {
let lhs = &self.thir()[*lhs];
match lhs.ty.kind() {
ty::Adt(def, _) if def.is_union() => false,
_ => self.is_known_valid_scrutinee(lhs),
}
}
// Essentially a field access.
Index { lhs, .. } => {
let lhs = &self.thir()[*lhs];
self.is_known_valid_scrutinee(lhs)
}
// No-op.
Scope { value, .. } => self.is_known_valid_scrutinee(&self.thir()[*value]),
// Casts don't cause a load.
NeverToAny { source }
| Cast { source }
| Use { source }
| PointerCoercion { source, .. }
| PlaceTypeAscription { source, .. }
| ValueTypeAscription { source, .. } => {
self.is_known_valid_scrutinee(&self.thir()[*source])
}
// These diverge.
Become { .. } | Break { .. } | Continue { .. } | Return { .. } => true,
// These are statements that evaluate to `()`.
Assign { .. } | AssignOp { .. } | InlineAsm { .. } | Let { .. } => true,
// These evaluate to a value.
AddressOf { .. }
| Adt { .. }
| Array { .. }
| Binary { .. }
| Block { .. }
| Borrow { .. }
| Box { .. }
| Call { .. }
| Closure { .. }
| ConstBlock { .. }
| ConstParam { .. }
| If { .. }
| Literal { .. }
| LogicalOp { .. }
| Loop { .. }
| Match { .. }
| NamedConst { .. }
| NonHirLiteral { .. }
| OffsetOf { .. }
| Repeat { .. }
| StaticRef { .. }
| ThreadLocalRef { .. }
| Tuple { .. }
| Unary { .. }
| UpvarRef { .. }
| VarRef { .. }
| ZstLiteral { .. }
| Yield { .. } => true,
}
}
fn new_cx(
&self,
refutability: RefutableFlag,
whole_match_span: Option<Span>,
scrutinee: Option<&Expr<'tcx>>,
scrut_span: Span,
) -> PatCtxt<'p, 'tcx> {
let refutable = match refutability {
Irrefutable => false,
Refutable => true,
};
// If we don't have a scrutinee we're either a function parameter or a `let x;`. Both cases
// require validity.
let known_valid_scrutinee =
scrutinee.map(|scrut| self.is_known_valid_scrutinee(scrut)).unwrap_or(true);
PatCtxt {
tcx: self.tcx,
typeck_results: self.typeck_results,
param_env: self.param_env,
module: self.tcx.parent_module(self.lint_level).to_def_id(),
dropless_arena: self.dropless_arena,
match_lint_level: self.lint_level,
whole_match_span,
scrut_span,
refutable,
known_valid_scrutinee,
}
}
fn analyze_patterns(
&mut self,
cx: &PatCtxt<'p, 'tcx>,
arms: &[MatchArm<'p, 'tcx>],
scrut_ty: Ty<'tcx>,
) -> Result<UsefulnessReport<'p, 'tcx>, ErrorGuaranteed> {
let pattern_complexity_limit =
get_limit_size(cx.tcx.hir().krate_attrs(), cx.tcx.sess, sym::pattern_complexity);
let report = rustc_pattern_analysis::rustc::analyze_match(
&cx,
&arms,
scrut_ty,
pattern_complexity_limit,
)
.map_err(|err| {
self.error = Err(err);
err
})?;
// Warn unreachable subpatterns.
for (arm, is_useful) in report.arm_usefulness.iter() {
if let Usefulness::Useful(redundant_subpats) = is_useful
&& !redundant_subpats.is_empty()
{
let mut redundant_subpats = redundant_subpats.clone();
// Emit lints in the order in which they occur in the file.
redundant_subpats.sort_unstable_by_key(|(pat, _)| pat.data().span);
for (pat, explanation) in redundant_subpats {
report_unreachable_pattern(cx, arm.arm_data, pat, &explanation)
}
}
}
Ok(report)
}
#[instrument(level = "trace", skip(self))]
fn check_let(&mut self, pat: &'p Pat<'tcx>, scrutinee: Option<ExprId>, span: Span) {
assert!(self.let_source != LetSource::None);
let scrut = scrutinee.map(|id| &self.thir[id]);
if let LetSource::PlainLet = self.let_source {
self.check_binding_is_irrefutable(pat, "local binding", scrut, Some(span))
} else {
let Ok(refutability) = self.is_let_irrefutable(pat, scrut) else { return };
if matches!(refutability, Irrefutable) {
report_irrefutable_let_patterns(
self.tcx,
self.lint_level,
self.let_source,
1,
span,
);
}
}
}
fn check_match(
&mut self,
scrut: ExprId,
arms: &[ArmId],
source: hir::MatchSource,
expr_span: Span,
) {
let scrut = &self.thir[scrut];
let cx = self.new_cx(Refutable, Some(expr_span), Some(scrut), scrut.span);
let mut tarms = Vec::with_capacity(arms.len());
for &arm in arms {
let arm = &self.thir.arms[arm];
let got_error = self.with_lint_level(arm.lint_level, |this| {
let Ok(pat) = this.lower_pattern(&cx, &arm.pattern) else { return true };
let arm =
MatchArm { pat, arm_data: this.lint_level, has_guard: arm.guard.is_some() };
tarms.push(arm);
false
});
if got_error {
return;
}
}
let Ok(report) = self.analyze_patterns(&cx, &tarms, scrut.ty) else { return };
match source {
// Don't report arm reachability of desugared `match $iter.into_iter() { iter => .. }`
// when the iterator is an uninhabited type. unreachable_code will trigger instead.
hir::MatchSource::ForLoopDesugar if arms.len() == 1 => {}
hir::MatchSource::ForLoopDesugar
| hir::MatchSource::Postfix
| hir::MatchSource::Normal
| hir::MatchSource::FormatArgs => report_arm_reachability(&cx, &report),
// Unreachable patterns in try and await expressions occur when one of
// the arms are an uninhabited type. Which is OK.
hir::MatchSource::AwaitDesugar | hir::MatchSource::TryDesugar(_) => {}
}
// Check if the match is exhaustive.
let witnesses = report.non_exhaustiveness_witnesses;
if !witnesses.is_empty() {
if source == hir::MatchSource::ForLoopDesugar
&& let [_, snd_arm] = *arms
{
// the for loop pattern is not irrefutable
let pat = &self.thir[snd_arm].pattern;
// `pat` should be `Some(<pat_field>)` from a desugared for loop.
debug_assert_eq!(pat.span.desugaring_kind(), Some(DesugaringKind::ForLoop));
let PatKind::Variant { ref subpatterns, .. } = pat.kind else { bug!() };
let [pat_field] = &subpatterns[..] else { bug!() };
self.check_binding_is_irrefutable(
&pat_field.pattern,
"`for` loop binding",
None,
None,
);
} else {
// span after scrutinee, or after `.match`. That is, the braces, arms,
// and any whitespace preceding the braces.
let braces_span = match source {
hir::MatchSource::Normal => scrut
.span
.find_ancestor_in_same_ctxt(expr_span)
.map(|scrut_span| scrut_span.shrink_to_hi().with_hi(expr_span.hi())),
hir::MatchSource::Postfix => {
// This is horrendous, and we should deal with it by just
// stashing the span of the braces somewhere (like in the match source).
scrut.span.find_ancestor_in_same_ctxt(expr_span).and_then(|scrut_span| {
let sm = self.tcx.sess.source_map();
let brace_span = sm.span_extend_to_next_char(scrut_span, '{', true);
if sm.span_to_snippet(sm.next_point(brace_span)).as_deref() == Ok("{") {
let sp = brace_span.shrink_to_hi().with_hi(expr_span.hi());
// We also need to extend backwards for whitespace
sm.span_extend_prev_while(sp, |c| c.is_whitespace()).ok()
} else {
None
}
})
}
hir::MatchSource::ForLoopDesugar
| hir::MatchSource::TryDesugar(_)
| hir::MatchSource::AwaitDesugar
| hir::MatchSource::FormatArgs => None,
};
self.error = Err(report_non_exhaustive_match(
&cx,
self.thir,
scrut.ty,
scrut.span,
witnesses,
arms,
braces_span,
));
}
}
}
#[instrument(level = "trace", skip(self))]
fn check_let_chain(
&mut self,
chain_refutabilities: Vec<Option<(Span, RefutableFlag)>>,
whole_chain_span: Span,
) {
assert!(self.let_source != LetSource::None);
if chain_refutabilities.iter().all(|r| matches!(*r, Some((_, Irrefutable)))) {
// The entire chain is made up of irrefutable `let` statements
report_irrefutable_let_patterns(
self.tcx,
self.lint_level,
self.let_source,
chain_refutabilities.len(),
whole_chain_span,
);
return;
}
if let Some(until) =
chain_refutabilities.iter().position(|r| !matches!(*r, Some((_, Irrefutable))))
&& until > 0
{
// The chain has a non-zero prefix of irrefutable `let` statements.
// Check if the let source is while, for there is no alternative place to put a prefix,
// and we shouldn't lint.
// For let guards inside a match, prefixes might use bindings of the match pattern,
// so can't always be moved out.
// FIXME: Add checking whether the bindings are actually used in the prefix,
// and lint if they are not.
if !matches!(self.let_source, LetSource::WhileLet | LetSource::IfLetGuard) {
// Emit the lint
let prefix = &chain_refutabilities[..until];
let span_start = prefix[0].unwrap().0;
let span_end = prefix.last().unwrap().unwrap().0;
let span = span_start.to(span_end);
let count = prefix.len();
self.tcx.emit_node_span_lint(
IRREFUTABLE_LET_PATTERNS,
self.lint_level,
span,
LeadingIrrefutableLetPatterns { count },
);
}
}
if let Some(from) =
chain_refutabilities.iter().rposition(|r| !matches!(*r, Some((_, Irrefutable))))
&& from != (chain_refutabilities.len() - 1)
{
// The chain has a non-empty suffix of irrefutable `let` statements
let suffix = &chain_refutabilities[from + 1..];
let span_start = suffix[0].unwrap().0;
let span_end = suffix.last().unwrap().unwrap().0;
let span = span_start.to(span_end);
let count = suffix.len();
self.tcx.emit_node_span_lint(
IRREFUTABLE_LET_PATTERNS,
self.lint_level,
span,
TrailingIrrefutableLetPatterns { count },
);
}
}
fn analyze_binding(
&mut self,
pat: &'p Pat<'tcx>,
refutability: RefutableFlag,
scrut: Option<&Expr<'tcx>>,
) -> Result<(PatCtxt<'p, 'tcx>, UsefulnessReport<'p, 'tcx>), ErrorGuaranteed> {
let cx = self.new_cx(refutability, None, scrut, pat.span);
let pat = self.lower_pattern(&cx, pat)?;
let arms = [MatchArm { pat, arm_data: self.lint_level, has_guard: false }];
let report = self.analyze_patterns(&cx, &arms, pat.ty().inner())?;
Ok((cx, report))
}
fn is_let_irrefutable(
&mut self,
pat: &'p Pat<'tcx>,
scrut: Option<&Expr<'tcx>>,
) -> Result<RefutableFlag, ErrorGuaranteed> {
let (cx, report) = self.analyze_binding(pat, Refutable, scrut)?;
// Report if the pattern is unreachable, which can only occur when the type is uninhabited.
report_arm_reachability(&cx, &report);
// If the list of witnesses is empty, the match is exhaustive, i.e. the `if let` pattern is
// irrefutable.
Ok(if report.non_exhaustiveness_witnesses.is_empty() { Irrefutable } else { Refutable })
}
#[instrument(level = "trace", skip(self))]
fn check_binding_is_irrefutable(
&mut self,
pat: &'p Pat<'tcx>,
origin: &str,
scrut: Option<&Expr<'tcx>>,
sp: Option<Span>,
) {
let pattern_ty = pat.ty;
let Ok((cx, report)) = self.analyze_binding(pat, Irrefutable, scrut) else { return };
let witnesses = report.non_exhaustiveness_witnesses;
if witnesses.is_empty() {
// The pattern is irrefutable.
return;
}
let inform = sp.is_some().then_some(Inform);
let mut let_suggestion = None;
let mut misc_suggestion = None;
let mut interpreted_as_const = None;
if let PatKind::Constant { .. }
| PatKind::AscribeUserType {
subpattern: box Pat { kind: PatKind::Constant { .. }, .. },
..
} = pat.kind
&& let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(pat.span)
{
// If the pattern to match is an integer literal:
if snippet.chars().all(|c| c.is_digit(10)) {
// Then give a suggestion, the user might've meant to create a binding instead.
misc_suggestion = Some(MiscPatternSuggestion::AttemptedIntegerLiteral {
start_span: pat.span.shrink_to_lo(),
});
} else if snippet.chars().all(|c| c.is_alphanumeric() || c == '_') {
interpreted_as_const =
Some(InterpretedAsConst { span: pat.span, variable: snippet });
}
}
if let Some(span) = sp
&& self.tcx.sess.source_map().is_span_accessible(span)
&& interpreted_as_const.is_none()
&& scrut.is_some()
{
let mut bindings = vec![];
pat.each_binding(|name, _, _, _| bindings.push(name));
let semi_span = span.shrink_to_hi();
let start_span = span.shrink_to_lo();
let end_span = semi_span.shrink_to_lo();
let count = witnesses.len();
let_suggestion = Some(if bindings.is_empty() {
SuggestLet::If { start_span, semi_span, count }
} else {
SuggestLet::Else { end_span, count }
});
};
let adt_defined_here = report_adt_defined_here(self.tcx, pattern_ty, &witnesses, false);
// Emit an extra note if the first uncovered witness would be uninhabited
// if we disregard visibility.
let witness_1_is_privately_uninhabited = if let Some(witness_1) = witnesses.get(0)
&& let ty::Adt(adt, args) = witness_1.ty().kind()
&& adt.is_enum()
&& let Constructor::Variant(variant_index) = witness_1.ctor()
{
let variant = adt.variant(*variant_index);
let inhabited = variant.inhabited_predicate(self.tcx, *adt).instantiate(self.tcx, args);
assert!(inhabited.apply(self.tcx, cx.param_env, cx.module));
!inhabited.apply_ignore_module(self.tcx, cx.param_env)
} else {
false
};
self.error = Err(self.tcx.dcx().emit_err(PatternNotCovered {
span: pat.span,
origin,
uncovered: Uncovered::new(pat.span, &cx, witnesses),
inform,
interpreted_as_const,
witness_1_is_privately_uninhabited: witness_1_is_privately_uninhabited.then_some(()),
_p: (),
pattern_ty,
let_suggestion,
misc_suggestion,
adt_defined_here,
}));
}
}
/// Check if a by-value binding is by-value. That is, check if the binding's type is not `Copy`.
/// Check that there are no borrow or move conflicts in `binding @ subpat` patterns.
///
/// For example, this would reject:
/// - `ref x @ Some(ref mut y)`,
/// - `ref mut x @ Some(ref y)`,
/// - `ref mut x @ Some(ref mut y)`,
/// - `ref mut? x @ Some(y)`, and
/// - `x @ Some(ref mut? y)`.
///
/// This analysis is *not* subsumed by NLL.
fn check_borrow_conflicts_in_at_patterns<'tcx>(cx: &MatchVisitor<'_, 'tcx>, pat: &Pat<'tcx>) {
// Extract `sub` in `binding @ sub`.
let PatKind::Binding { name, mode, ty, subpattern: Some(box ref sub), .. } = pat.kind else {
return;
};
let is_binding_by_move = |ty: Ty<'tcx>| !ty.is_copy_modulo_regions(cx.tcx, cx.param_env);
let sess = cx.tcx.sess;
// Get the binding move, extract the mutability if by-ref.
let mut_outer = match mode.0 {
ByRef::No if is_binding_by_move(ty) => {
// We have `x @ pat` where `x` is by-move. Reject all borrows in `pat`.
let mut conflicts_ref = Vec::new();
sub.each_binding(|_, mode, _, span| {
if matches!(mode, ByRef::Yes(_)) {
conflicts_ref.push(span)
}
});
if !conflicts_ref.is_empty() {
sess.dcx().emit_err(BorrowOfMovedValue {
binding_span: pat.span,
conflicts_ref,
name,
ty,
suggest_borrowing: Some(pat.span.shrink_to_lo()),
});
}
return;
}
ByRef::No => return,
ByRef::Yes(m) => m,
};
// We now have `ref $mut_outer binding @ sub` (semantically).
// Recurse into each binding in `sub` and find mutability or move conflicts.
let mut conflicts_move = Vec::new();
let mut conflicts_mut_mut = Vec::new();
let mut conflicts_mut_ref = Vec::new();
sub.each_binding(|name, mode, ty, span| {
match mode {
ByRef::Yes(mut_inner) => match (mut_outer, mut_inner) {
// Both sides are `ref`.
(Mutability::Not, Mutability::Not) => {}
// 2x `ref mut`.
(Mutability::Mut, Mutability::Mut) => {
conflicts_mut_mut.push(Conflict::Mut { span, name })
}
(Mutability::Not, Mutability::Mut) => {
conflicts_mut_ref.push(Conflict::Mut { span, name })
}
(Mutability::Mut, Mutability::Not) => {
conflicts_mut_ref.push(Conflict::Ref { span, name })
}
},
ByRef::No if is_binding_by_move(ty) => {
conflicts_move.push(Conflict::Moved { span, name }) // `ref mut?` + by-move conflict.
}
ByRef::No => {} // `ref mut?` + by-copy is fine.
}
});
let report_mut_mut = !conflicts_mut_mut.is_empty();
let report_mut_ref = !conflicts_mut_ref.is_empty();
let report_move_conflict = !conflicts_move.is_empty();
let mut occurrences = match mut_outer {
Mutability::Mut => vec![Conflict::Mut { span: pat.span, name }],
Mutability::Not => vec![Conflict::Ref { span: pat.span, name }],
};
occurrences.extend(conflicts_mut_mut);
occurrences.extend(conflicts_mut_ref);
occurrences.extend(conflicts_move);
// Report errors if any.
if report_mut_mut {
// Report mutability conflicts for e.g. `ref mut x @ Some(ref mut y)`.
sess.dcx().emit_err(MultipleMutBorrows { span: pat.span, occurrences });
} else if report_mut_ref {
// Report mutability conflicts for e.g. `ref x @ Some(ref mut y)` or the converse.
match mut_outer {
Mutability::Mut => {
sess.dcx().emit_err(AlreadyMutBorrowed { span: pat.span, occurrences });
}
Mutability::Not => {
sess.dcx().emit_err(AlreadyBorrowed { span: pat.span, occurrences });
}
};
} else if report_move_conflict {
// Report by-ref and by-move conflicts, e.g. `ref x @ y`.
sess.dcx().emit_err(MovedWhileBorrowed { span: pat.span, occurrences });
}
}
fn check_for_bindings_named_same_as_variants(
cx: &MatchVisitor<'_, '_>,
pat: &Pat<'_>,
rf: RefutableFlag,
) {
if let PatKind::Binding {
name,
mode: BindingMode(ByRef::No, Mutability::Not),
subpattern: None,
ty,
..
} = pat.kind
&& let ty::Adt(edef, _) = ty.peel_refs().kind()
&& edef.is_enum()
&& edef
.variants()
.iter()
.any(|variant| variant.name == name && variant.ctor_kind() == Some(CtorKind::Const))
{
let variant_count = edef.variants().len();
let ty_path = with_no_trimmed_paths!(cx.tcx.def_path_str(edef.did()));
cx.tcx.emit_node_span_lint(
BINDINGS_WITH_VARIANT_NAME,
cx.lint_level,
pat.span,
BindingsWithVariantName {
// If this is an irrefutable pattern, and there's > 1 variant,
// then we can't actually match on this. Applying the below
// suggestion would produce code that breaks on `check_binding_is_irrefutable`.
suggestion: if rf == Refutable || variant_count == 1 {
Some(pat.span)
} else {
None
},
ty_path,
name,
},
)
}
}
/// Check that never patterns are only used on inhabited types.
fn check_never_pattern<'tcx>(
cx: &PatCtxt<'_, 'tcx>,
pat: &Pat<'tcx>,
) -> Result<(), ErrorGuaranteed> {
if let PatKind::Never = pat.kind {
if !cx.is_uninhabited(pat.ty) {
return Err(cx.tcx.dcx().emit_err(NonEmptyNeverPattern { span: pat.span, ty: pat.ty }));
}
}
Ok(())
}
fn report_irrefutable_let_patterns(
tcx: TyCtxt<'_>,
id: HirId,
source: LetSource,
count: usize,
span: Span,
) {
macro_rules! emit_diag {
($lint:tt) => {{
tcx.emit_node_span_lint(IRREFUTABLE_LET_PATTERNS, id, span, $lint { count });
}};
}
match source {
LetSource::None | LetSource::PlainLet => bug!(),
LetSource::IfLet => emit_diag!(IrrefutableLetPatternsIfLet),
LetSource::IfLetGuard => emit_diag!(IrrefutableLetPatternsIfLetGuard),
LetSource::LetElse => emit_diag!(IrrefutableLetPatternsLetElse),
LetSource::WhileLet => emit_diag!(IrrefutableLetPatternsWhileLet),
}
}
/// Report unreachable arms, if any.
fn report_unreachable_pattern<'p, 'tcx>(
cx: &PatCtxt<'p, 'tcx>,
hir_id: HirId,
pat: &DeconstructedPat<'p, 'tcx>,
explanation: &RedundancyExplanation<'p, 'tcx>,
) {
let pat_span = pat.data().span;
let mut lint = UnreachablePattern {
span: Some(pat_span),
matches_no_values: None,
covered_by_catchall: None,
covered_by_one: None,
covered_by_many: None,
};
match explanation.covered_by.as_slice() {
[] => {
// Empty pattern; we report the uninhabited type that caused the emptiness.
lint.span = None; // Don't label the pattern itself
pat.walk(&mut |subpat| {
let ty = **subpat.ty();
if cx.is_uninhabited(ty) {
lint.matches_no_values = Some(UnreachableMatchesNoValues { ty });
false // No need to dig further.
} else if matches!(subpat.ctor(), Constructor::Ref | Constructor::UnionField) {
false // Don't explore further since they are not by-value.
} else {
true
}
});
}
[covering_pat] if pat_is_catchall(covering_pat) => {
lint.covered_by_catchall = Some(covering_pat.data().span);
}
[covering_pat] => {
lint.covered_by_one = Some(covering_pat.data().span);
}
covering_pats => {
let mut multispan = MultiSpan::from_span(pat_span);
for p in covering_pats {
multispan.push_span_label(
p.data().span,
fluent::mir_build_unreachable_matches_same_values,
);
}
multispan
.push_span_label(pat_span, fluent::mir_build_unreachable_making_this_unreachable);
lint.covered_by_many = Some(multispan);
}
}
cx.tcx.emit_node_span_lint(UNREACHABLE_PATTERNS, hir_id, pat_span, lint);
}
/// Report unreachable arms, if any.
fn report_arm_reachability<'p, 'tcx>(cx: &PatCtxt<'p, 'tcx>, report: &UsefulnessReport<'p, 'tcx>) {
for (arm, is_useful) in report.arm_usefulness.iter() {
if let Usefulness::Redundant(explanation) = is_useful {
report_unreachable_pattern(cx, arm.arm_data, arm.pat, explanation)
}
}
}
/// Checks for common cases of "catchall" patterns that may not be intended as such.
fn pat_is_catchall(pat: &DeconstructedPat<'_, '_>) -> bool {
match pat.ctor() {
Constructor::Wildcard => true,
Constructor::Struct | Constructor::Ref => {
pat.iter_fields().all(|ipat| pat_is_catchall(&ipat.pat))
}
_ => false,
}
}
/// Report that a match is not exhaustive.
fn report_non_exhaustive_match<'p, 'tcx>(
cx: &PatCtxt<'p, 'tcx>,
thir: &Thir<'tcx>,
scrut_ty: Ty<'tcx>,
sp: Span,
witnesses: Vec<WitnessPat<'p, 'tcx>>,
arms: &[ArmId],
braces_span: Option<Span>,
) -> ErrorGuaranteed {
let is_empty_match = arms.is_empty();
let non_empty_enum = match scrut_ty.kind() {
ty::Adt(def, _) => def.is_enum() && !def.variants().is_empty(),
_ => false,
};
// In the case of an empty match, replace the '`_` not covered' diagnostic with something more
// informative.