]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/pat_util.rs
Auto merge of #28119 - nagisa:bytesderef, r=alexcrichton
[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::{Span, DUMMY_SP};
20
21 pub type PatIdMap = FnvHashMap<ast::Ident, 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, &hir::SpannedIdent),
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, pth);
118           }
119           _ => {}
120         }
121         true
122     });
123 }
124
125 /// Checks if the pattern contains any patterns that bind something to
126 /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
127 pub fn pat_contains_bindings(dm: &DefMap, pat: &hir::Pat) -> bool {
128     let mut contains_bindings = false;
129     walk_pat(pat, |p| {
130         if pat_is_binding(dm, p) {
131             contains_bindings = true;
132             false // there's at least one binding, can short circuit now.
133         } else {
134             true
135         }
136     });
137     contains_bindings
138 }
139
140 /// Checks if the pattern contains any `ref` or `ref mut` bindings,
141 /// and if yes wether its containing mutable ones or just immutables ones.
142 pub fn pat_contains_ref_binding(dm: &DefMap, pat: &hir::Pat) -> Option<hir::Mutability> {
143     let mut result = None;
144     pat_bindings(dm, pat, |mode, _, _, _| {
145         match mode {
146             hir::BindingMode::BindByRef(m) => {
147                 // Pick Mutable as maximum
148                 match result {
149                     None | Some(hir::MutImmutable) => result = Some(m),
150                     _ => (),
151                 }
152             }
153             hir::BindingMode::BindByValue(_) => { }
154         }
155     });
156     result
157 }
158
159 /// Checks if the patterns for this arm contain any `ref` or `ref mut`
160 /// bindings, and if yes wether its containing mutable ones or just immutables ones.
161 pub fn arm_contains_ref_binding(dm: &DefMap, arm: &hir::Arm) -> Option<hir::Mutability> {
162     arm.pats.iter()
163             .filter_map(|pat| pat_contains_ref_binding(dm, pat))
164             .max_by(|m| match *m {
165                 hir::MutMutable => 1,
166                 hir::MutImmutable => 0,
167             })
168 }
169
170 /// Checks if the pattern contains any patterns that bind something to
171 /// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`,
172 pub fn pat_contains_bindings_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
173     let mut contains_bindings = false;
174     walk_pat(pat, |p| {
175         if pat_is_binding_or_wild(dm, p) {
176             contains_bindings = true;
177             false // there's at least one binding/wildcard, can short circuit now.
178         } else {
179             true
180         }
181     });
182     contains_bindings
183 }
184
185 pub fn simple_identifier<'a>(pat: &'a hir::Pat) -> Option<&'a ast::Ident> {
186     match pat.node {
187         hir::PatIdent(hir::BindByValue(_), ref path1, None) => {
188             Some(&path1.node)
189         }
190         _ => {
191             None
192         }
193     }
194 }
195
196 pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> hir::Path {
197     tcx.with_path(id, |path| hir::Path {
198         global: false,
199         segments: path.last().map(|elem| hir::PathSegment {
200             identifier: ast::Ident::new(elem.name()),
201             parameters: hir::PathParameters::none(),
202         }).into_iter().collect(),
203         span: DUMMY_SP,
204     })
205 }
206
207 /// Return variants that are necessary to exist for the pattern to match.
208 pub fn necessary_variants(dm: &DefMap, pat: &hir::Pat) -> Vec<ast::NodeId> {
209     let mut variants = vec![];
210     walk_pat(pat, |p| {
211         match p.node {
212             hir::PatEnum(_, _) |
213             hir::PatIdent(_, _, None) |
214             hir::PatStruct(..) => {
215                 match dm.borrow().get(&p.id) {
216                     Some(&PathResolution { base_def: DefVariant(_, id, _), .. }) => {
217                         variants.push(id.node);
218                     }
219                     _ => ()
220                 }
221             }
222             _ => ()
223         }
224         true
225     });
226     variants.sort();
227     variants.dedup();
228     variants
229 }