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.
15 use std::collections::HashMap;
16 use std::gc::{Gc, GC};
18 use syntax::ast_util::{walk_pat};
19 use syntax::codemap::{Span, DUMMY_SP};
20 use syntax::owned_slice::OwnedSlice;
22 pub type PatIdMap = HashMap<Ident, NodeId>;
24 // This is used because same-named variables in alternative patterns need to
25 // use the NodeId of their namesake in the first pattern.
26 pub fn pat_id_map(dm: &resolve::DefMap, pat: &Pat) -> PatIdMap {
27 let mut map = HashMap::new();
28 pat_bindings(dm, pat, |_bm, p_id, _s, path1| {
29 map.insert(path1.node, p_id);
34 pub fn pat_is_variant_or_struct(dm: &resolve::DefMap, pat: &Pat) -> bool {
36 PatEnum(_, _) | PatIdent(_, _, None) | PatStruct(..) => {
37 match dm.borrow().find(&pat.id) {
38 Some(&DefVariant(..)) | Some(&DefStruct(..)) => true,
46 pub fn pat_is_const(dm: &resolve::DefMap, pat: &Pat) -> bool {
48 PatIdent(_, _, None) | PatEnum(..) => {
49 match dm.borrow().find(&pat.id) {
50 Some(&DefStatic(_, false)) => true,
58 pub fn pat_is_binding(dm: &resolve::DefMap, pat: &Pat) -> bool {
61 !pat_is_variant_or_struct(dm, pat) &&
62 !pat_is_const(dm, pat)
68 pub fn pat_is_binding_or_wild(dm: &resolve::DefMap, pat: &Pat) -> bool {
70 PatIdent(..) => pat_is_binding(dm, pat),
71 PatWild | PatWildMulti => true,
76 /// Call `it` on every "binding" in a pattern, e.g., on `a` in
77 /// `match foo() { Some(a) => (), None => () }`
78 pub fn pat_bindings(dm: &resolve::DefMap,
80 it: |BindingMode, NodeId, Span, &SpannedIdent|) {
83 PatIdent(binding_mode, ref pth, _) if pat_is_binding(dm, p) => {
84 it(binding_mode, p.id, p.span, pth);
92 /// Checks if the pattern contains any patterns that bind something to
93 /// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
94 pub fn pat_contains_bindings(dm: &resolve::DefMap, pat: &Pat) -> bool {
95 let mut contains_bindings = false;
97 if pat_is_binding(dm, p) {
98 contains_bindings = true;
99 false // there's at least one binding, can short circuit now.
107 pub fn simple_identifier<'a>(pat: &'a Pat) -> Option<&'a Ident> {
109 PatIdent(BindByValue(_), ref path1, None) => {
118 pub fn wild() -> Gc<Pat> {
119 box (GC) Pat { id: 0, node: PatWild, span: DUMMY_SP }
122 pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> Path {
123 ty::with_path(tcx, id, |mut path| Path {
125 segments: path.last().map(|elem| PathSegment {
126 identifier: Ident::new(elem.name()),
128 types: OwnedSlice::empty()
129 }).move_iter().collect(),