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