]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/build/matches/simplify.rs
Improve some compiletest documentation
[rust.git] / src / librustc_mir / build / matches / simplify.rs
1 //! Simplifying Candidates
2 //!
3 //! *Simplifying* a match pair `place @ pattern` means breaking it down
4 //! into bindings or other, simpler match pairs. For example:
5 //!
6 //! - `place @ (P1, P2)` can be simplified to `[place.0 @ P1, place.1 @ P2]`
7 //! - `place @ x` can be simplified to `[]` by binding `x` to `place`
8 //!
9 //! The `simplify_candidate` routine just repeatedly applies these
10 //! sort of simplifications until there is nothing left to
11 //! simplify. Match pairs cannot be simplified if they require some
12 //! sort of test: for example, testing which variant an enum is, or
13 //! testing a value against a constant.
14
15 use crate::build::Builder;
16 use crate::build::matches::{Ascription, Binding, MatchPair, Candidate};
17 use crate::hair::{self, *};
18 use rustc::ty;
19 use rustc::ty::layout::{Integer, IntegerExt, Size};
20 use syntax::attr::{SignedInt, UnsignedInt};
21 use rustc::hir::RangeEnd;
22 use rustc::mir::interpret::truncate;
23
24 use std::mem;
25
26 impl<'a, 'gcx, 'tcx> Builder<'a, 'gcx, 'tcx> {
27     pub fn simplify_candidate<'pat>(&mut self,
28                                     candidate: &mut Candidate<'pat, 'tcx>) {
29         // repeatedly simplify match pairs until fixed point is reached
30         loop {
31             let match_pairs = mem::replace(&mut candidate.match_pairs, vec![]);
32             let mut changed = false;
33             for match_pair in match_pairs {
34                 match self.simplify_match_pair(match_pair, candidate) {
35                     Ok(()) => {
36                         changed = true;
37                     }
38                     Err(match_pair) => {
39                         candidate.match_pairs.push(match_pair);
40                     }
41                 }
42             }
43             if !changed {
44                 return; // if we were not able to simplify any, done.
45             }
46         }
47     }
48
49     /// Tries to simplify `match_pair`, returning `Ok(())` if
50     /// successful. If successful, new match pairs and bindings will
51     /// have been pushed into the candidate. If no simplification is
52     /// possible, `Err` is returned and no changes are made to
53     /// candidate.
54     fn simplify_match_pair<'pat>(&mut self,
55                                  match_pair: MatchPair<'pat, 'tcx>,
56                                  candidate: &mut Candidate<'pat, 'tcx>)
57                                  -> Result<(), MatchPair<'pat, 'tcx>> {
58         let tcx = self.hir.tcx();
59         match *match_pair.pattern.kind {
60             PatternKind::AscribeUserType {
61                 ref subpattern,
62                 ascription: hair::pattern::Ascription {
63                     variance,
64                     ref user_ty,
65                     user_ty_span,
66                 },
67             } => {
68                 // Apply the type ascription to the value at `match_pair.place`, which is the
69                 // value being matched, taking the variance field into account.
70                 candidate.ascriptions.push(Ascription {
71                     span: user_ty_span,
72                     user_ty: user_ty.clone(),
73                     source: match_pair.place.clone(),
74                     variance,
75                 });
76
77                 candidate.match_pairs.push(MatchPair::new(match_pair.place, subpattern));
78
79                 Ok(())
80             }
81
82             PatternKind::Wild => {
83                 // nothing left to do
84                 Ok(())
85             }
86
87             PatternKind::Binding { name, mutability, mode, var, ty, ref subpattern } => {
88                 candidate.bindings.push(Binding {
89                     name,
90                     mutability,
91                     span: match_pair.pattern.span,
92                     source: match_pair.place.clone(),
93                     var_id: var,
94                     var_ty: ty,
95                     binding_mode: mode,
96                 });
97
98                 if let Some(subpattern) = subpattern.as_ref() {
99                     // this is the `x @ P` case; have to keep matching against `P` now
100                     candidate.match_pairs.push(MatchPair::new(match_pair.place, subpattern));
101                 }
102
103                 Ok(())
104             }
105
106             PatternKind::Constant { .. } => {
107                 // FIXME normalize patterns when possible
108                 Err(match_pair)
109             }
110
111             PatternKind::Range(PatternRange { lo, hi, ty, end }) => {
112                 let (range, bias) = match ty.sty {
113                     ty::Char => {
114                         (Some(('\u{0000}' as u128, '\u{10FFFF}' as u128, Size::from_bits(32))), 0)
115                     }
116                     ty::Int(ity) => {
117                         let size = Integer::from_attr(&tcx, SignedInt(ity)).size();
118                         let max = truncate(u128::max_value(), size);
119                         let bias = 1u128 << (size.bits() - 1);
120                         (Some((0, max, size)), bias)
121                     }
122                     ty::Uint(uty) => {
123                         let size = Integer::from_attr(&tcx, UnsignedInt(uty)).size();
124                         let max = truncate(u128::max_value(), size);
125                         (Some((0, max, size)), 0)
126                     }
127                     _ => (None, 0),
128                 };
129                 if let Some((min, max, sz)) = range {
130                     if let (Some(lo), Some(hi)) = (lo.val.try_to_bits(sz), hi.val.try_to_bits(sz)) {
131                         // We want to compare ranges numerically, but the order of the bitwise
132                         // representation of signed integers does not match their numeric order.
133                         // Thus, to correct the ordering, we need to shift the range of signed
134                         // integers to correct the comparison. This is achieved by XORing with a
135                         // bias (see pattern/_match.rs for another pertinent example of this
136                         // pattern).
137                         let (lo, hi) = (lo ^ bias, hi ^ bias);
138                         if lo <= min && (hi > max || hi == max && end == RangeEnd::Included) {
139                             // Irrefutable pattern match.
140                             return Ok(());
141                         }
142                     }
143                 }
144                 Err(match_pair)
145             }
146
147             PatternKind::Slice { ref prefix, ref slice, ref suffix } => {
148                 if prefix.is_empty() && slice.is_some() && suffix.is_empty() {
149                     // irrefutable
150                     self.prefix_slice_suffix(&mut candidate.match_pairs,
151                                              &match_pair.place,
152                                              prefix,
153                                              slice.as_ref(),
154                                              suffix);
155                     Ok(())
156                 } else {
157                     Err(match_pair)
158                 }
159             }
160
161             PatternKind::Variant { adt_def, substs, variant_index, ref subpatterns } => {
162                 let irrefutable = adt_def.variants.iter_enumerated().all(|(i, v)| {
163                     i == variant_index || {
164                         self.hir.tcx().features().never_type &&
165                         self.hir.tcx().features().exhaustive_patterns &&
166                         self.hir.tcx().is_variant_uninhabited_from_all_modules(v, substs)
167                     }
168                 });
169                 if irrefutable {
170                     let place = match_pair.place.downcast(adt_def, variant_index);
171                     candidate.match_pairs.extend(self.field_match_pairs(place, subpatterns));
172                     Ok(())
173                 } else {
174                     Err(match_pair)
175                 }
176             }
177
178             PatternKind::Array { ref prefix, ref slice, ref suffix } => {
179                 self.prefix_slice_suffix(&mut candidate.match_pairs,
180                                          &match_pair.place,
181                                          prefix,
182                                          slice.as_ref(),
183                                          suffix);
184                 Ok(())
185             }
186
187             PatternKind::Leaf { ref subpatterns } => {
188                 // tuple struct, match subpats (if any)
189                 candidate.match_pairs
190                          .extend(self.field_match_pairs(match_pair.place, subpatterns));
191                 Ok(())
192             }
193
194             PatternKind::Deref { ref subpattern } => {
195                 let place = match_pair.place.deref();
196                 candidate.match_pairs.push(MatchPair::new(place, subpattern));
197                 Ok(())
198             }
199         }
200     }
201 }