-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
mod.rs
1274 lines (1176 loc) · 47.2 KB
/
mod.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
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Code to validate patterns/matches
mod _match;
mod check_match;
pub use self::check_match::check_crate;
pub(crate) use self::check_match::check_match;
use const_eval::{const_field, const_variant_index};
use rustc::mir::{fmt_const_val, Field, BorrowKind, Mutability};
use rustc::mir::interpret::{Scalar, GlobalId, ConstValue, sign_extend};
use rustc::ty::{self, CanonicalTy, TyCtxt, AdtDef, Ty, Region};
use rustc::ty::subst::{Substs, Kind};
use rustc::hir::{self, PatKind, RangeEnd};
use rustc::hir::def::{Def, CtorKind};
use rustc::hir::pat_util::EnumerateAndAdjustIterator;
use rustc_data_structures::indexed_vec::Idx;
use std::cmp::Ordering;
use std::fmt;
use syntax::ast;
use syntax::ptr::P;
use syntax_pos::Span;
use syntax_pos::symbol::Symbol;
#[derive(Clone, Debug)]
pub enum PatternError {
AssociatedConstInPattern(Span),
StaticInPattern(Span),
FloatBug,
NonConstPath(Span),
}
#[derive(Copy, Clone, Debug)]
pub enum BindingMode<'tcx> {
ByValue,
ByRef(Region<'tcx>, BorrowKind),
}
#[derive(Clone, Debug)]
pub struct FieldPattern<'tcx> {
pub field: Field,
pub pattern: Pattern<'tcx>,
}
#[derive(Clone, Debug)]
pub struct Pattern<'tcx> {
pub ty: Ty<'tcx>,
pub span: Span,
pub kind: Box<PatternKind<'tcx>>,
}
#[derive(Clone, Debug)]
pub enum PatternKind<'tcx> {
Wild,
AscribeUserType {
user_ty: CanonicalTy<'tcx>,
subpattern: Pattern<'tcx>,
},
/// x, ref x, x @ P, etc
Binding {
mutability: Mutability,
name: ast::Name,
mode: BindingMode<'tcx>,
var: ast::NodeId,
ty: Ty<'tcx>,
subpattern: Option<Pattern<'tcx>>,
},
/// Foo(...) or Foo{...} or Foo, where `Foo` is a variant name from an adt with >1 variants
Variant {
adt_def: &'tcx AdtDef,
substs: &'tcx Substs<'tcx>,
variant_index: usize,
subpatterns: Vec<FieldPattern<'tcx>>,
},
/// (...), Foo(...), Foo{...}, or Foo, where `Foo` is a variant name from an adt with 1 variant
Leaf {
subpatterns: Vec<FieldPattern<'tcx>>,
},
/// box P, &P, &mut P, etc
Deref {
subpattern: Pattern<'tcx>,
},
Constant {
value: &'tcx ty::Const<'tcx>,
},
Range {
lo: &'tcx ty::Const<'tcx>,
hi: &'tcx ty::Const<'tcx>,
ty: Ty<'tcx>,
end: RangeEnd,
},
/// matches against a slice, checking the length and extracting elements.
/// irrefutable when there is a slice pattern and both `prefix` and `suffix` are empty.
/// e.g. `&[ref xs..]`.
Slice {
prefix: Vec<Pattern<'tcx>>,
slice: Option<Pattern<'tcx>>,
suffix: Vec<Pattern<'tcx>>,
},
/// fixed match against an array, irrefutable
Array {
prefix: Vec<Pattern<'tcx>>,
slice: Option<Pattern<'tcx>>,
suffix: Vec<Pattern<'tcx>>,
},
}
impl<'tcx> fmt::Display for Pattern<'tcx> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self.kind {
PatternKind::Wild => write!(f, "_"),
PatternKind::AscribeUserType { ref subpattern, .. } =>
write!(f, "{}: _", subpattern),
PatternKind::Binding { mutability, name, mode, ref subpattern, .. } => {
let is_mut = match mode {
BindingMode::ByValue => mutability == Mutability::Mut,
BindingMode::ByRef(_, bk) => {
write!(f, "ref ")?;
match bk { BorrowKind::Mut { .. } => true, _ => false }
}
};
if is_mut {
write!(f, "mut ")?;
}
write!(f, "{}", name)?;
if let Some(ref subpattern) = *subpattern {
write!(f, " @ {}", subpattern)?;
}
Ok(())
}
PatternKind::Variant { ref subpatterns, .. } |
PatternKind::Leaf { ref subpatterns } => {
let variant = match *self.kind {
PatternKind::Variant { adt_def, variant_index, .. } => {
Some(&adt_def.variants[variant_index])
}
_ => if let ty::Adt(adt, _) = self.ty.sty {
if !adt.is_enum() {
Some(&adt.variants[0])
} else {
None
}
} else {
None
}
};
let mut first = true;
let mut start_or_continue = || if first { first = false; "" } else { ", " };
if let Some(variant) = variant {
write!(f, "{}", variant.name)?;
// Only for Adt we can have `S {...}`,
// which we handle separately here.
if variant.ctor_kind == CtorKind::Fictive {
write!(f, " {{ ")?;
let mut printed = 0;
for p in subpatterns {
if let PatternKind::Wild = *p.pattern.kind {
continue;
}
let name = variant.fields[p.field.index()].ident;
write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
printed += 1;
}
if printed < variant.fields.len() {
write!(f, "{}..", start_or_continue())?;
}
return write!(f, " }}");
}
}
let num_fields = variant.map_or(subpatterns.len(), |v| v.fields.len());
if num_fields != 0 || variant.is_none() {
write!(f, "(")?;
for i in 0..num_fields {
write!(f, "{}", start_or_continue())?;
// Common case: the field is where we expect it.
if let Some(p) = subpatterns.get(i) {
if p.field.index() == i {
write!(f, "{}", p.pattern)?;
continue;
}
}
// Otherwise, we have to go looking for it.
if let Some(p) = subpatterns.iter().find(|p| p.field.index() == i) {
write!(f, "{}", p.pattern)?;
} else {
write!(f, "_")?;
}
}
write!(f, ")")?;
}
Ok(())
}
PatternKind::Deref { ref subpattern } => {
match self.ty.sty {
ty::Adt(def, _) if def.is_box() => write!(f, "box ")?,
ty::Ref(_, _, mutbl) => {
write!(f, "&")?;
if mutbl == hir::MutMutable {
write!(f, "mut ")?;
}
}
_ => bug!("{} is a bad Deref pattern type", self.ty)
}
write!(f, "{}", subpattern)
}
PatternKind::Constant { value } => {
fmt_const_val(f, value)
}
PatternKind::Range { lo, hi, ty: _, end } => {
fmt_const_val(f, lo)?;
match end {
RangeEnd::Included => write!(f, "..=")?,
RangeEnd::Excluded => write!(f, "..")?,
}
fmt_const_val(f, hi)
}
PatternKind::Slice { ref prefix, ref slice, ref suffix } |
PatternKind::Array { ref prefix, ref slice, ref suffix } => {
let mut first = true;
let mut start_or_continue = || if first { first = false; "" } else { ", " };
write!(f, "[")?;
for p in prefix {
write!(f, "{}{}", start_or_continue(), p)?;
}
if let Some(ref slice) = *slice {
write!(f, "{}", start_or_continue())?;
match *slice.kind {
PatternKind::Wild => {}
_ => write!(f, "{}", slice)?
}
write!(f, "..")?;
}
for p in suffix {
write!(f, "{}{}", start_or_continue(), p)?;
}
write!(f, "]")
}
}
}
}
pub struct PatternContext<'a, 'tcx: 'a> {
pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
pub param_env: ty::ParamEnv<'tcx>,
pub tables: &'a ty::TypeckTables<'tcx>,
pub substs: &'tcx Substs<'tcx>,
pub errors: Vec<PatternError>,
}
impl<'a, 'tcx> Pattern<'tcx> {
pub fn from_hir(tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
tables: &'a ty::TypeckTables<'tcx>,
pat: &'tcx hir::Pat) -> Self {
let mut pcx = PatternContext::new(tcx, param_env_and_substs, tables);
let result = pcx.lower_pattern(pat);
if !pcx.errors.is_empty() {
let msg = format!("encountered errors lowering pattern: {:?}", pcx.errors);
tcx.sess.delay_span_bug(pat.span, &msg);
}
debug!("Pattern::from_hir({:?}) = {:?}", pat, result);
result
}
}
impl<'a, 'tcx> PatternContext<'a, 'tcx> {
pub fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
param_env_and_substs: ty::ParamEnvAnd<'tcx, &'tcx Substs<'tcx>>,
tables: &'a ty::TypeckTables<'tcx>) -> Self {
PatternContext {
tcx,
param_env: param_env_and_substs.param_env,
tables,
substs: param_env_and_substs.value,
errors: vec![]
}
}
pub fn lower_pattern(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
// When implicit dereferences have been inserted in this pattern, the unadjusted lowered
// pattern has the type that results *after* dereferencing. For example, in this code:
//
// ```
// match &&Some(0i32) {
// Some(n) => { ... },
// _ => { ... },
// }
// ```
//
// the type assigned to `Some(n)` in `unadjusted_pat` would be `Option<i32>` (this is
// determined in rustc_typeck::check::match). The adjustments would be
//
// `vec![&&Option<i32>, &Option<i32>]`.
//
// Applying the adjustments, we want to instead output `&&Some(n)` (as a HAIR pattern). So
// we wrap the unadjusted pattern in `PatternKind::Deref` repeatedly, consuming the
// adjustments in *reverse order* (last-in-first-out, so that the last `Deref` inserted
// gets the least-dereferenced type).
let unadjusted_pat = self.lower_pattern_unadjusted(pat);
self.tables
.pat_adjustments()
.get(pat.hir_id)
.unwrap_or(&vec![])
.iter()
.rev()
.fold(unadjusted_pat, |pat, ref_ty| {
debug!("{:?}: wrapping pattern with type {:?}", pat, ref_ty);
Pattern {
span: pat.span,
ty: ref_ty,
kind: Box::new(PatternKind::Deref { subpattern: pat }),
}
},
)
}
fn lower_pattern_unadjusted(&mut self, pat: &'tcx hir::Pat) -> Pattern<'tcx> {
let mut ty = self.tables.node_id_to_type(pat.hir_id);
let kind = match pat.node {
PatKind::Wild => PatternKind::Wild,
PatKind::Lit(ref value) => self.lower_lit(value),
PatKind::Range(ref lo_expr, ref hi_expr, end) => {
match (self.lower_lit(lo_expr), self.lower_lit(hi_expr)) {
(PatternKind::Constant { value: lo },
PatternKind::Constant { value: hi }) => {
use std::cmp::Ordering;
let cmp = compare_const_vals(
self.tcx,
lo,
hi,
self.param_env.and(ty),
);
match (end, cmp) {
(RangeEnd::Excluded, Some(Ordering::Less)) =>
PatternKind::Range { lo, hi, ty, end },
(RangeEnd::Excluded, _) => {
span_err!(
self.tcx.sess,
lo_expr.span,
E0579,
"lower range bound must be less than upper",
);
PatternKind::Wild
}
(RangeEnd::Included, Some(Ordering::Equal)) => {
PatternKind::Constant { value: lo }
}
(RangeEnd::Included, Some(Ordering::Less)) => {
PatternKind::Range { lo, hi, ty, end }
}
(RangeEnd::Included, _) => {
let mut err = struct_span_err!(
self.tcx.sess,
lo_expr.span,
E0030,
"lower range bound must be less than or equal to upper"
);
err.span_label(
lo_expr.span,
"lower bound larger than upper bound",
);
if self.tcx.sess.teach(&err.get_code().unwrap()) {
err.note("When matching against a range, the compiler \
verifies that the range is non-empty. Range \
patterns include both end-points, so this is \
equivalent to requiring the start of the range \
to be less than or equal to the end of the range.");
}
err.emit();
PatternKind::Wild
}
}
}
_ => PatternKind::Wild
}
}
PatKind::Path(ref qpath) => {
return self.lower_path(qpath, pat.hir_id, pat.span);
}
PatKind::Ref(ref subpattern, _) |
PatKind::Box(ref subpattern) => {
PatternKind::Deref { subpattern: self.lower_pattern(subpattern) }
}
PatKind::Slice(ref prefix, ref slice, ref suffix) => {
match ty.sty {
ty::Ref(_, ty, _) =>
PatternKind::Deref {
subpattern: Pattern {
ty,
span: pat.span,
kind: Box::new(self.slice_or_array_pattern(
pat.span, ty, prefix, slice, suffix))
},
},
ty::Slice(..) |
ty::Array(..) =>
self.slice_or_array_pattern(pat.span, ty, prefix, slice, suffix),
ty::Error => { // Avoid ICE
return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
}
ref sty =>
span_bug!(
pat.span,
"unexpanded type for vector pattern: {:?}",
sty),
}
}
PatKind::Tuple(ref subpatterns, ddpos) => {
match ty.sty {
ty::Tuple(ref tys) => {
let subpatterns =
subpatterns.iter()
.enumerate_and_adjust(tys.len(), ddpos)
.map(|(i, subpattern)| FieldPattern {
field: Field::new(i),
pattern: self.lower_pattern(subpattern)
})
.collect();
PatternKind::Leaf { subpatterns: subpatterns }
}
ty::Error => { // Avoid ICE (#50577)
return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
}
ref sty => span_bug!(pat.span, "unexpected type for tuple pattern: {:?}", sty),
}
}
PatKind::Binding(_, id, ident, ref sub) => {
let var_ty = self.tables.node_id_to_type(pat.hir_id);
let region = match var_ty.sty {
ty::Ref(r, _, _) => Some(r),
ty::Error => { // Avoid ICE
return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
}
_ => None,
};
let bm = *self.tables.pat_binding_modes().get(pat.hir_id)
.expect("missing binding mode");
let (mutability, mode) = match bm {
ty::BindByValue(hir::MutMutable) =>
(Mutability::Mut, BindingMode::ByValue),
ty::BindByValue(hir::MutImmutable) =>
(Mutability::Not, BindingMode::ByValue),
ty::BindByReference(hir::MutMutable) =>
(Mutability::Not, BindingMode::ByRef(
region.unwrap(), BorrowKind::Mut { allow_two_phase_borrow: false })),
ty::BindByReference(hir::MutImmutable) =>
(Mutability::Not, BindingMode::ByRef(
region.unwrap(), BorrowKind::Shared)),
};
// A ref x pattern is the same node used for x, and as such it has
// x's type, which is &T, where we want T (the type being matched).
if let ty::BindByReference(_) = bm {
if let ty::Ref(_, rty, _) = ty.sty {
ty = rty;
} else {
bug!("`ref {}` has wrong type {}", ident, ty);
}
}
PatternKind::Binding {
mutability,
mode,
name: ident.name,
var: id,
ty: var_ty,
subpattern: self.lower_opt_pattern(sub),
}
}
PatKind::TupleStruct(ref qpath, ref subpatterns, ddpos) => {
let def = self.tables.qpath_def(qpath, pat.hir_id);
let adt_def = match ty.sty {
ty::Adt(adt_def, _) => adt_def,
ty::Error => { // Avoid ICE (#50585)
return Pattern { span: pat.span, ty, kind: Box::new(PatternKind::Wild) };
}
_ => span_bug!(pat.span,
"tuple struct pattern not applied to an ADT {:?}",
ty.sty),
};
let variant_def = adt_def.variant_of_def(def);
let subpatterns =
subpatterns.iter()
.enumerate_and_adjust(variant_def.fields.len(), ddpos)
.map(|(i, field)| FieldPattern {
field: Field::new(i),
pattern: self.lower_pattern(field),
})
.collect();
self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
}
PatKind::Struct(ref qpath, ref fields, _) => {
let def = self.tables.qpath_def(qpath, pat.hir_id);
let subpatterns =
fields.iter()
.map(|field| {
FieldPattern {
field: Field::new(self.tcx.field_index(field.node.id,
self.tables)),
pattern: self.lower_pattern(&field.node.pat),
}
})
.collect();
self.lower_variant_or_leaf(def, pat.span, ty, subpatterns)
}
};
Pattern {
span: pat.span,
ty,
kind: Box::new(kind),
}
}
fn lower_patterns(&mut self, pats: &'tcx [P<hir::Pat>]) -> Vec<Pattern<'tcx>> {
pats.iter().map(|p| self.lower_pattern(p)).collect()
}
fn lower_opt_pattern(&mut self, pat: &'tcx Option<P<hir::Pat>>) -> Option<Pattern<'tcx>>
{
pat.as_ref().map(|p| self.lower_pattern(p))
}
fn flatten_nested_slice_patterns(
&mut self,
prefix: Vec<Pattern<'tcx>>,
slice: Option<Pattern<'tcx>>,
suffix: Vec<Pattern<'tcx>>)
-> (Vec<Pattern<'tcx>>, Option<Pattern<'tcx>>, Vec<Pattern<'tcx>>)
{
let orig_slice = match slice {
Some(orig_slice) => orig_slice,
None => return (prefix, slice, suffix)
};
let orig_prefix = prefix;
let orig_suffix = suffix;
// dance because of intentional borrow-checker stupidity.
let kind = *orig_slice.kind;
match kind {
PatternKind::Slice { prefix, slice, mut suffix } |
PatternKind::Array { prefix, slice, mut suffix } => {
let mut orig_prefix = orig_prefix;
orig_prefix.extend(prefix);
suffix.extend(orig_suffix);
(orig_prefix, slice, suffix)
}
_ => {
(orig_prefix, Some(Pattern {
kind: box kind, ..orig_slice
}), orig_suffix)
}
}
}
fn slice_or_array_pattern(
&mut self,
span: Span,
ty: Ty<'tcx>,
prefix: &'tcx [P<hir::Pat>],
slice: &'tcx Option<P<hir::Pat>>,
suffix: &'tcx [P<hir::Pat>])
-> PatternKind<'tcx>
{
let prefix = self.lower_patterns(prefix);
let slice = self.lower_opt_pattern(slice);
let suffix = self.lower_patterns(suffix);
let (prefix, slice, suffix) =
self.flatten_nested_slice_patterns(prefix, slice, suffix);
match ty.sty {
ty::Slice(..) => {
// matching a slice or fixed-length array
PatternKind::Slice { prefix: prefix, slice: slice, suffix: suffix }
}
ty::Array(_, len) => {
// fixed-length array
let len = len.unwrap_usize(self.tcx);
assert!(len >= prefix.len() as u64 + suffix.len() as u64);
PatternKind::Array { prefix: prefix, slice: slice, suffix: suffix }
}
_ => {
span_bug!(span, "bad slice pattern type {:?}", ty);
}
}
}
fn lower_variant_or_leaf(
&mut self,
def: Def,
span: Span,
ty: Ty<'tcx>,
subpatterns: Vec<FieldPattern<'tcx>>)
-> PatternKind<'tcx>
{
match def {
Def::Variant(variant_id) | Def::VariantCtor(variant_id, ..) => {
let enum_id = self.tcx.parent_def_id(variant_id).unwrap();
let adt_def = self.tcx.adt_def(enum_id);
if adt_def.is_enum() {
let substs = match ty.sty {
ty::Adt(_, substs) |
ty::FnDef(_, substs) => substs,
ty::Error => { // Avoid ICE (#50585)
return PatternKind::Wild;
}
_ => bug!("inappropriate type for def: {:?}", ty.sty),
};
PatternKind::Variant {
adt_def,
substs,
variant_index: adt_def.variant_index_with_id(variant_id),
subpatterns,
}
} else {
PatternKind::Leaf { subpatterns: subpatterns }
}
}
Def::Struct(..) | Def::StructCtor(..) | Def::Union(..) |
Def::TyAlias(..) | Def::AssociatedTy(..) | Def::SelfTy(..) | Def::SelfCtor(..) => {
PatternKind::Leaf { subpatterns: subpatterns }
}
_ => {
self.errors.push(PatternError::NonConstPath(span));
PatternKind::Wild
}
}
}
/// Takes a HIR Path. If the path is a constant, evaluates it and feeds
/// it to `const_to_pat`. Any other path (like enum variants without fields)
/// is converted to the corresponding pattern via `lower_variant_or_leaf`
fn lower_path(&mut self,
qpath: &hir::QPath,
id: hir::HirId,
span: Span)
-> Pattern<'tcx> {
let ty = self.tables.node_id_to_type(id);
let def = self.tables.qpath_def(qpath, id);
let is_associated_const = match def {
Def::AssociatedConst(_) => true,
_ => false,
};
let kind = match def {
Def::Const(def_id) | Def::AssociatedConst(def_id) => {
let substs = self.tables.node_substs(id);
match ty::Instance::resolve(
self.tcx,
self.param_env,
def_id,
substs,
) {
Some(instance) => {
let cid = GlobalId {
instance,
promoted: None,
};
match self.tcx.at(span).const_eval(self.param_env.and(cid)) {
Ok(value) => {
return self.const_to_pat(instance, value, id, span)
},
Err(err) => {
err.report_as_error(
self.tcx.at(span),
"could not evaluate constant pattern",
);
PatternKind::Wild
},
}
},
None => {
self.errors.push(if is_associated_const {
PatternError::AssociatedConstInPattern(span)
} else {
PatternError::StaticInPattern(span)
});
PatternKind::Wild
},
}
}
_ => self.lower_variant_or_leaf(def, span, ty, vec![]),
};
Pattern {
span,
ty,
kind: Box::new(kind),
}
}
/// Converts literals, paths and negation of literals to patterns.
/// The special case for negation exists to allow things like -128i8
/// which would overflow if we tried to evaluate 128i8 and then negate
/// afterwards.
fn lower_lit(&mut self, expr: &'tcx hir::Expr) -> PatternKind<'tcx> {
match expr.node {
hir::ExprKind::Lit(ref lit) => {
let ty = self.tables.expr_ty(expr);
match lit_to_const(&lit.node, self.tcx, ty, false) {
Ok(val) => {
let instance = ty::Instance::new(
self.tables.local_id_root.expect("literal outside any scope"),
self.substs,
);
*self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
},
Err(e) => {
if e == LitToConstError::UnparseableFloat {
self.errors.push(PatternError::FloatBug);
}
PatternKind::Wild
},
}
},
hir::ExprKind::Path(ref qpath) => *self.lower_path(qpath, expr.hir_id, expr.span).kind,
hir::ExprKind::Unary(hir::UnNeg, ref expr) => {
let ty = self.tables.expr_ty(expr);
let lit = match expr.node {
hir::ExprKind::Lit(ref lit) => lit,
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
};
match lit_to_const(&lit.node, self.tcx, ty, true) {
Ok(val) => {
let instance = ty::Instance::new(
self.tables.local_id_root.expect("literal outside any scope"),
self.substs,
);
*self.const_to_pat(instance, val, expr.hir_id, lit.span).kind
},
Err(e) => {
if e == LitToConstError::UnparseableFloat {
self.errors.push(PatternError::FloatBug);
}
PatternKind::Wild
},
}
}
_ => span_bug!(expr.span, "not a literal: {:?}", expr),
}
}
/// Converts an evaluated constant to a pattern (if possible).
/// This means aggregate values (like structs and enums) are converted
/// to a pattern that matches the value (as if you'd compare via eq).
fn const_to_pat(
&self,
instance: ty::Instance<'tcx>,
cv: &'tcx ty::Const<'tcx>,
id: hir::HirId,
span: Span,
) -> Pattern<'tcx> {
debug!("const_to_pat: cv={:#?}", cv);
let adt_subpattern = |i, variant_opt| {
let field = Field::new(i);
let val = const_field(
self.tcx, self.param_env, instance,
variant_opt, field, cv,
).expect("field access failed");
self.const_to_pat(instance, val, id, span)
};
let adt_subpatterns = |n, variant_opt| {
(0..n).map(|i| {
let field = Field::new(i);
FieldPattern {
field,
pattern: adt_subpattern(i, variant_opt),
}
}).collect::<Vec<_>>()
};
let kind = match cv.ty.sty {
ty::Float(_) => {
let id = self.tcx.hir.hir_to_node_id(id);
self.tcx.lint_node(
::rustc::lint::builtin::ILLEGAL_FLOATING_POINT_LITERAL_PATTERN,
id,
span,
"floating-point types cannot be used in patterns",
);
PatternKind::Constant {
value: cv,
}
},
ty::Adt(adt_def, _) if adt_def.is_union() => {
// Matching on union fields is unsafe, we can't hide it in constants
self.tcx.sess.span_err(span, "cannot use unions in constant patterns");
PatternKind::Wild
}
ty::Adt(adt_def, _) if !self.tcx.has_attr(adt_def.did, "structural_match") => {
let msg = format!("to use a constant of type `{}` in a pattern, \
`{}` must be annotated with `#[derive(PartialEq, Eq)]`",
self.tcx.item_path_str(adt_def.did),
self.tcx.item_path_str(adt_def.did));
self.tcx.sess.span_err(span, &msg);
PatternKind::Wild
},
ty::Adt(adt_def, substs) if adt_def.is_enum() => {
let variant_index = const_variant_index(
self.tcx, self.param_env, instance, cv
).expect("const_variant_index failed");
let subpatterns = adt_subpatterns(
adt_def.variants[variant_index].fields.len(),
Some(variant_index),
);
PatternKind::Variant {
adt_def,
substs,
variant_index,
subpatterns,
}
},
ty::Adt(adt_def, _) => {
let struct_var = adt_def.non_enum_variant();
PatternKind::Leaf {
subpatterns: adt_subpatterns(struct_var.fields.len(), None),
}
}
ty::Tuple(fields) => {
PatternKind::Leaf {
subpatterns: adt_subpatterns(fields.len(), None),
}
}
ty::Array(_, n) => {
PatternKind::Array {
prefix: (0..n.unwrap_usize(self.tcx))
.map(|i| adt_subpattern(i as usize, None))
.collect(),
slice: None,
suffix: Vec::new(),
}
}
_ => {
PatternKind::Constant {
value: cv,
}
},
};
Pattern {
span,
ty: cv.ty,
kind: Box::new(kind),
}
}
}
pub trait PatternFoldable<'tcx> : Sized {
fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
self.super_fold_with(folder)
}
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self;
}
pub trait PatternFolder<'tcx> : Sized {
fn fold_pattern(&mut self, pattern: &Pattern<'tcx>) -> Pattern<'tcx> {
pattern.super_fold_with(self)
}
fn fold_pattern_kind(&mut self, kind: &PatternKind<'tcx>) -> PatternKind<'tcx> {
kind.super_fold_with(self)
}
}
impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Box<T> {
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
let content: T = (**self).fold_with(folder);
box content
}
}
impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Vec<T> {
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
self.iter().map(|t| t.fold_with(folder)).collect()
}
}
impl<'tcx, T: PatternFoldable<'tcx>> PatternFoldable<'tcx> for Option<T> {
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self{
self.as_ref().map(|t| t.fold_with(folder))
}
}
macro_rules! CloneImpls {
(<$lt_tcx:tt> $($ty:ty),+) => {
$(
impl<$lt_tcx> PatternFoldable<$lt_tcx> for $ty {
fn super_fold_with<F: PatternFolder<$lt_tcx>>(&self, _: &mut F) -> Self {
Clone::clone(self)
}
}
)+
}
}
CloneImpls!{ <'tcx>
Span, Field, Mutability, ast::Name, ast::NodeId, usize, &'tcx ty::Const<'tcx>,
Region<'tcx>, Ty<'tcx>, BindingMode<'tcx>, &'tcx AdtDef,
&'tcx Substs<'tcx>, &'tcx Kind<'tcx>, CanonicalTy<'tcx>
}
impl<'tcx> PatternFoldable<'tcx> for FieldPattern<'tcx> {
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
FieldPattern {
field: self.field.fold_with(folder),
pattern: self.pattern.fold_with(folder)
}
}
}
impl<'tcx> PatternFoldable<'tcx> for Pattern<'tcx> {
fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_pattern(self)
}
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
Pattern {
ty: self.ty.fold_with(folder),
span: self.span.fold_with(folder),
kind: self.kind.fold_with(folder)
}
}
}
impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
fn fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
folder.fold_pattern_kind(self)
}
fn super_fold_with<F: PatternFolder<'tcx>>(&self, folder: &mut F) -> Self {
match *self {
PatternKind::Wild => PatternKind::Wild,
PatternKind::AscribeUserType {
ref subpattern,
user_ty,
} => PatternKind::AscribeUserType {
subpattern: subpattern.fold_with(folder),
user_ty: user_ty.fold_with(folder),
},
PatternKind::Binding {
mutability,
name,
mode,
var,
ty,
ref subpattern,
} => PatternKind::Binding {
mutability: mutability.fold_with(folder),
name: name.fold_with(folder),