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.
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.
14 use collections::HashMap;
16 use syntax::ast_util::{path_to_ident, walk_pat};
17 use syntax::codemap::Span;
19 pub type PatIdMap = HashMap<Ident, NodeId>;
21 // This is used because same-named variables in alternative patterns need to
22 // use the NodeId of their namesake in the first pattern.
23 pub fn pat_id_map(dm: resolve::DefMap, pat: &Pat) -> PatIdMap {
24 let mut map = HashMap::new();
25 pat_bindings(dm, pat, |_bm, p_id, _s, n| {
26 map.insert(path_to_ident(n), p_id);
31 pub fn pat_is_variant_or_struct(dm: resolve::DefMap, pat: &Pat) -> bool {
33 PatEnum(_, _) | PatIdent(_, _, None) | PatStruct(..) => {
34 match dm.borrow().find(&pat.id) {
35 Some(&DefVariant(..)) | Some(&DefStruct(..)) => true,
43 pub fn pat_is_const(dm: resolve::DefMap, pat: &Pat) -> bool {
45 PatIdent(_, _, None) | PatEnum(..) => {
46 match dm.borrow().find(&pat.id) {
47 Some(&DefStatic(_, false)) => true,
55 pub fn pat_is_binding(dm: resolve::DefMap, pat: &Pat) -> bool {
58 !pat_is_variant_or_struct(dm, pat) &&
59 !pat_is_const(dm, pat)
65 pub fn pat_is_binding_or_wild(dm: resolve::DefMap, pat: &Pat) -> bool {
67 PatIdent(..) => pat_is_binding(dm, pat),
68 PatWild | PatWildMulti => true,
73 /// Call `it` on every "binding" in a pattern, e.g., on `a` in
74 /// `match foo() { Some(a) => (), None => () }`
75 pub fn pat_bindings(dm: resolve::DefMap,
77 it: |BindingMode, NodeId, Span, &Path|) {
80 PatIdent(binding_mode, ref pth, _) if pat_is_binding(dm, p) => {
81 it(binding_mode, p.id, p.span, pth);
89 pub fn pat_binding_ids(dm: resolve::DefMap, pat: &Pat) -> Vec<NodeId> {
90 let mut found = Vec::new();
91 pat_bindings(dm, pat, |_bm, b_id, _sp, _pt| found.push(b_id) );
95 /// Checks if the pattern contains any patterns that bind something to
96 /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
97 pub fn pat_contains_bindings(dm: resolve::DefMap, pat: &Pat) -> bool {
98 let mut contains_bindings = false;
100 if pat_is_binding(dm, p) {
101 contains_bindings = true;
102 false // there's at least one binding, can short circuit now.
110 pub fn simple_identifier<'a>(pat: &'a Pat) -> Option<&'a Path> {
112 PatIdent(BindByValue(_), ref path, None) => {