]> git.proxmox.com Git - rustc.git/blob - src/librustc/middle/pat_util.rs
Imported Upstream version 1.8.0+dfsg1
[rustc.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::{self, PatKind};
18 use rustc_front::util::walk_pat;
19 use syntax::codemap::{respan, Span, Spanned, DUMMY_SP};
20
21 use std::cell::RefCell;
22
23 pub type PatIdMap = FnvHashMap<ast::Name, ast::NodeId>;
24
25 // This is used because same-named variables in alternative patterns need to
26 // use the NodeId of their namesake in the first pattern.
27 pub fn pat_id_map(dm: &RefCell<DefMap>, pat: &hir::Pat) -> PatIdMap {
28 let mut map = FnvHashMap();
29 pat_bindings(dm, pat, |_bm, p_id, _s, path1| {
30 map.insert(path1.node, p_id);
31 });
32 map
33 }
34
35 pub fn pat_is_refutable(dm: &DefMap, pat: &hir::Pat) -> bool {
36 match pat.node {
37 PatKind::Lit(_) | PatKind::Range(_, _) | PatKind::QPath(..) => true,
38 PatKind::TupleStruct(..) |
39 PatKind::Path(..) |
40 PatKind::Ident(_, _, None) |
41 PatKind::Struct(..) => {
42 match dm.get(&pat.id).map(|d| d.full_def()) {
43 Some(Def::Variant(..)) => true,
44 _ => false
45 }
46 }
47 PatKind::Vec(_, _, _) => 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 PatKind::TupleStruct(..) |
55 PatKind::Path(..) |
56 PatKind::Ident(_, _, None) |
57 PatKind::Struct(..) => {
58 match dm.get(&pat.id).map(|d| d.full_def()) {
59 Some(Def::Variant(..)) | Some(Def::Struct(..)) | Some(Def::TyAlias(..)) => true,
60 _ => false
61 }
62 }
63 _ => false
64 }
65 }
66
67 pub fn pat_is_const(dm: &DefMap, pat: &hir::Pat) -> bool {
68 match pat.node {
69 PatKind::Ident(_, _, None) | PatKind::Path(..) | PatKind::QPath(..) => {
70 match dm.get(&pat.id).map(|d| d.full_def()) {
71 Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => true,
72 _ => false
73 }
74 }
75 _ => false
76 }
77 }
78
79 // Same as above, except that partially-resolved defs cause `false` to be
80 // returned instead of a panic.
81 pub fn pat_is_resolved_const(dm: &DefMap, pat: &hir::Pat) -> bool {
82 match pat.node {
83 PatKind::Ident(_, _, None) | PatKind::Path(..) | PatKind::QPath(..) => {
84 match dm.get(&pat.id)
85 .and_then(|d| if d.depth == 0 { Some(d.base_def) }
86 else { None } ) {
87 Some(Def::Const(..)) | Some(Def::AssociatedConst(..)) => true,
88 _ => false
89 }
90 }
91 _ => false
92 }
93 }
94
95 pub fn pat_is_binding(dm: &DefMap, pat: &hir::Pat) -> bool {
96 match pat.node {
97 PatKind::Ident(..) => {
98 !pat_is_variant_or_struct(dm, pat) &&
99 !pat_is_const(dm, pat)
100 }
101 _ => false
102 }
103 }
104
105 pub fn pat_is_binding_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
106 match pat.node {
107 PatKind::Ident(..) => pat_is_binding(dm, pat),
108 PatKind::Wild => true,
109 _ => false
110 }
111 }
112
113 /// Call `it` on every "binding" in a pattern, e.g., on `a` in
114 /// `match foo() { Some(a) => (), None => () }`
115 pub fn pat_bindings<I>(dm: &RefCell<DefMap>, pat: &hir::Pat, mut it: I) where
116 I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Name>),
117 {
118 walk_pat(pat, |p| {
119 match p.node {
120 PatKind::Ident(binding_mode, ref pth, _) if pat_is_binding(&dm.borrow(), p) => {
121 it(binding_mode, p.id, p.span, &respan(pth.span, pth.node.name));
122 }
123 _ => {}
124 }
125 true
126 });
127 }
128 pub fn pat_bindings_ident<I>(dm: &RefCell<DefMap>, pat: &hir::Pat, mut it: I) where
129 I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<hir::Ident>),
130 {
131 walk_pat(pat, |p| {
132 match p.node {
133 PatKind::Ident(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 whether 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 whether 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_key(|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 PatKind::Ident(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: hir::Ident::from_name(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 PatKind::TupleStruct(..) |
230 PatKind::Path(..) |
231 PatKind::Ident(_, _, None) |
232 PatKind::Struct(..) => {
233 match dm.get(&p.id) {
234 Some(&PathResolution { base_def: Def::Variant(_, id), .. }) => {
235 variants.push(id);
236 }
237 _ => ()
238 }
239 }
240 _ => ()
241 }
242 true
243 });
244 variants.sort();
245 variants.dedup();
246 variants
247 }