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(..) => {
35 match dm.get().find(&pat.id) {
36 Some(&DefVariant(..)) | Some(&DefStruct(..)) => true,
44 pub fn pat_is_const(dm: resolve::DefMap, pat: &Pat) -> bool {
46 PatIdent(_, _, None) | PatEnum(..) => {
48 match dm.get().find(&pat.id) {
49 Some(&DefStatic(_, false)) => true,
57 pub fn pat_is_binding(dm: resolve::DefMap, pat: &Pat) -> bool {
60 !pat_is_variant_or_struct(dm, pat) &&
61 !pat_is_const(dm, pat)
67 pub fn pat_is_binding_or_wild(dm: resolve::DefMap, pat: &Pat) -> bool {
69 PatIdent(..) => pat_is_binding(dm, pat),
70 PatWild | PatWildMulti => true,
75 /// Call `it` on every "binding" in a pattern, e.g., on `a` in
76 /// `match foo() { Some(a) => (), None => () }`
77 pub fn pat_bindings(dm: resolve::DefMap,
79 it: |BindingMode, NodeId, Span, &Path|) {
82 PatIdent(binding_mode, ref pth, _) if pat_is_binding(dm, p) => {
83 it(binding_mode, p.id, p.span, pth);
91 pub fn pat_binding_ids(dm: resolve::DefMap, pat: &Pat) -> Vec<NodeId> {
92 let mut found = Vec::new();
93 pat_bindings(dm, pat, |_bm, b_id, _sp, _pt| found.push(b_id) );
97 /// Checks if the pattern contains any patterns that bind something to
98 /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
99 pub fn pat_contains_bindings(dm: resolve::DefMap, pat: &Pat) -> bool {
100 let mut contains_bindings = false;
102 if pat_is_binding(dm, p) {
103 contains_bindings = true;
104 false // there's at least one binding, can short circuit now.
112 pub fn simple_identifier<'a>(pat: &'a Pat) -> Option<&'a Path> {
114 PatIdent(BindByValue(_), ref path, None) => {