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