]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/pat_util.rs
Auto merge of #29531 - bltavares:issue-28586, r=sanxiyn
[rust.git] / src / librustc / middle / pat_util.rs
1 // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use middle::def::*;
12 use middle::def_id::DefId;
13 use middle::ty;
14 use util::nodemap::FnvHashMap;
15
16 use syntax::ast;
17 use syntax::ext::mtwt;
18 use rustc_front::hir;
19 use rustc_front::util::walk_pat;
20 use syntax::codemap::{respan, Span, Spanned, DUMMY_SP};
21
22 use std::cell::RefCell;
23
24 pub type PatIdMap = FnvHashMap<ast::Name, ast::NodeId>;
25
26 // This is used because same-named variables in alternative patterns need to
27 // use the NodeId of their namesake in the first pattern.
28 pub fn pat_id_map(dm: &RefCell<DefMap>, pat: &hir::Pat) -> PatIdMap {
29     let mut map = FnvHashMap();
30     pat_bindings_hygienic(dm, pat, |_bm, p_id, _s, path1| {
31         map.insert(mtwt::resolve(path1.node), p_id);
32     });
33     map
34 }
35
36 pub fn pat_is_refutable(dm: &DefMap, pat: &hir::Pat) -> bool {
37     match pat.node {
38         hir::PatLit(_) | hir::PatRange(_, _) | hir::PatQPath(..) => true,
39         hir::PatEnum(_, _) |
40         hir::PatIdent(_, _, None) |
41         hir::PatStruct(..) => {
42             match dm.get(&pat.id).map(|d| d.full_def()) {
43                 Some(DefVariant(..)) => true,
44                 _ => false
45             }
46         }
47         hir::PatVec(_, _, _) => true,
48         _ => false
49     }
50 }
51
52 pub fn pat_is_variant_or_struct(dm: &DefMap, pat: &hir::Pat) -> bool {
53     match pat.node {
54         hir::PatEnum(_, _) |
55         hir::PatIdent(_, _, None) |
56         hir::PatStruct(..) => {
57             match dm.get(&pat.id).map(|d| d.full_def()) {
58                 Some(DefVariant(..)) | Some(DefStruct(..)) => true,
59                 _ => false
60             }
61         }
62         _ => false
63     }
64 }
65
66 pub fn pat_is_const(dm: &DefMap, pat: &hir::Pat) -> bool {
67     match pat.node {
68         hir::PatIdent(_, _, None) | hir::PatEnum(..) | hir::PatQPath(..) => {
69             match dm.get(&pat.id).map(|d| d.full_def()) {
70                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) => true,
71                 _ => false
72             }
73         }
74         _ => false
75     }
76 }
77
78 // Same as above, except that partially-resolved defs cause `false` to be
79 // returned instead of a panic.
80 pub fn pat_is_resolved_const(dm: &DefMap, pat: &hir::Pat) -> bool {
81     match pat.node {
82         hir::PatIdent(_, _, None) | hir::PatEnum(..) | hir::PatQPath(..) => {
83             match dm.get(&pat.id)
84                     .and_then(|d| if d.depth == 0 { Some(d.base_def) }
85                                   else { None } ) {
86                 Some(DefConst(..)) | Some(DefAssociatedConst(..)) => true,
87                 _ => false
88             }
89         }
90         _ => false
91     }
92 }
93
94 pub fn pat_is_binding(dm: &DefMap, pat: &hir::Pat) -> bool {
95     match pat.node {
96         hir::PatIdent(..) => {
97             !pat_is_variant_or_struct(dm, pat) &&
98             !pat_is_const(dm, pat)
99         }
100         _ => false
101     }
102 }
103
104 pub fn pat_is_binding_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
105     match pat.node {
106         hir::PatIdent(..) => pat_is_binding(dm, pat),
107         hir::PatWild => true,
108         _ => false
109     }
110 }
111
112 /// Call `it` on every "binding" in a pattern, e.g., on `a` in
113 /// `match foo() { Some(a) => (), None => () }`
114 pub fn pat_bindings<I>(dm: &RefCell<DefMap>, pat: &hir::Pat, mut it: I) where
115     I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Name>),
116 {
117     walk_pat(pat, |p| {
118         match p.node {
119           hir::PatIdent(binding_mode, ref pth, _) if pat_is_binding(&dm.borrow(), p) => {
120             it(binding_mode, p.id, p.span, &respan(pth.span, pth.node.name));
121           }
122           _ => {}
123         }
124         true
125     });
126 }
127
128 pub fn pat_bindings_hygienic<I>(dm: &RefCell<DefMap>, pat: &hir::Pat, mut it: I) where
129     I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Ident>),
130 {
131     walk_pat(pat, |p| {
132         match p.node {
133           hir::PatIdent(binding_mode, ref pth, _) if pat_is_binding(&dm.borrow(), p) => {
134             it(binding_mode, p.id, p.span, &respan(pth.span, pth.node));
135           }
136           _ => {}
137         }
138         true
139     });
140 }
141
142 /// Checks if the pattern contains any patterns that bind something to
143 /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
144 pub fn pat_contains_bindings(dm: &DefMap, pat: &hir::Pat) -> bool {
145     let mut contains_bindings = false;
146     walk_pat(pat, |p| {
147         if pat_is_binding(dm, p) {
148             contains_bindings = true;
149             false // there's at least one binding, can short circuit now.
150         } else {
151             true
152         }
153     });
154     contains_bindings
155 }
156
157 /// Checks if the pattern contains any `ref` or `ref mut` bindings,
158 /// and if yes wether its containing mutable ones or just immutables ones.
159 pub fn pat_contains_ref_binding(dm: &RefCell<DefMap>, pat: &hir::Pat) -> Option<hir::Mutability> {
160     let mut result = None;
161     pat_bindings(dm, pat, |mode, _, _, _| {
162         match mode {
163             hir::BindingMode::BindByRef(m) => {
164                 // Pick Mutable as maximum
165                 match result {
166                     None | Some(hir::MutImmutable) => result = Some(m),
167                     _ => (),
168                 }
169             }
170             hir::BindingMode::BindByValue(_) => { }
171         }
172     });
173     result
174 }
175
176 /// Checks if the patterns for this arm contain any `ref` or `ref mut`
177 /// bindings, and if yes wether its containing mutable ones or just immutables ones.
178 pub fn arm_contains_ref_binding(dm: &RefCell<DefMap>, arm: &hir::Arm) -> Option<hir::Mutability> {
179     arm.pats.iter()
180             .filter_map(|pat| pat_contains_ref_binding(dm, pat))
181             .max_by(|m| match *m {
182                 hir::MutMutable => 1,
183                 hir::MutImmutable => 0,
184             })
185 }
186
187 /// Checks if the pattern contains any patterns that bind something to
188 /// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`,
189 pub fn pat_contains_bindings_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
190     let mut contains_bindings = false;
191     walk_pat(pat, |p| {
192         if pat_is_binding_or_wild(dm, p) {
193             contains_bindings = true;
194             false // there's at least one binding/wildcard, can short circuit now.
195         } else {
196             true
197         }
198     });
199     contains_bindings
200 }
201
202 pub fn simple_name<'a>(pat: &'a hir::Pat) -> Option<ast::Name> {
203     match pat.node {
204         hir::PatIdent(hir::BindByValue(_), ref path1, None) => {
205             Some(path1.node.name)
206         }
207         _ => {
208             None
209         }
210     }
211 }
212
213 pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> hir::Path {
214     tcx.with_path(id, |path| hir::Path {
215         global: false,
216         segments: path.last().map(|elem| hir::PathSegment {
217             identifier: ast::Ident::with_empty_ctxt(elem.name()),
218             parameters: hir::PathParameters::none(),
219         }).into_iter().collect(),
220         span: DUMMY_SP,
221     })
222 }
223
224 /// Return variants that are necessary to exist for the pattern to match.
225 pub fn necessary_variants(dm: &DefMap, pat: &hir::Pat) -> Vec<DefId> {
226     let mut variants = vec![];
227     walk_pat(pat, |p| {
228         match p.node {
229             hir::PatEnum(_, _) |
230             hir::PatIdent(_, _, None) |
231             hir::PatStruct(..) => {
232                 match dm.get(&p.id) {
233                     Some(&PathResolution { base_def: DefVariant(_, id, _), .. }) => {
234                         variants.push(id);
235                     }
236                     _ => ()
237                 }
238             }
239             _ => ()
240         }
241         true
242     });
243     variants.sort();
244     variants.dedup();
245     variants
246 }