rust/src/librustc/middle/pat_util.rs

84 lines
2.2 KiB
Rust
Raw Normal View History

2012-09-04 13:54:36 -05:00
use syntax::ast::*;
use syntax::ast_util;
use syntax::ast_util::{path_to_ident, respan, walk_pat};
use syntax::fold;
use syntax::fold::*;
use syntax::codemap::span;
2012-09-10 17:38:28 -05:00
use std::map::HashMap;
export pat_binding_ids, pat_bindings, pat_id_map, PatIdMap;
export pat_is_variant_or_struct, pat_is_binding, pat_is_binding_or_wild;
export pat_is_const;
type PatIdMap = std::map::HashMap<ident, node_id>;
// This is used because same-named variables in alternative patterns need to
// use the node_id of their namesake in the first pattern.
fn pat_id_map(dm: resolve::DefMap, pat: @pat) -> PatIdMap {
let map = std::map::HashMap();
do pat_bindings(dm, pat) |_bm, p_id, _s, n| {
map.insert(path_to_ident(n), p_id);
};
2012-08-01 19:30:05 -05:00
return map;
}
fn pat_is_variant_or_struct(dm: resolve::DefMap, pat: @pat) -> bool {
2012-08-06 14:34:08 -05:00
match pat.node {
pat_enum(_, _) | pat_ident(_, _, None) | pat_struct(*) => {
match dm.find(pat.id) {
Some(def_variant(*)) | Some(def_class(*)) => true,
_ => false
}
}
2012-08-03 21:59:04 -05:00
_ => false
}
}
fn pat_is_const(dm: resolve::DefMap, pat: &pat) -> bool {
match pat.node {
pat_ident(_, _, None) => {
match dm.find(pat.id) {
Some(def_const(*)) => true,
_ => false
}
}
_ => false
}
}
fn pat_is_binding(dm: resolve::DefMap, pat: @pat) -> bool {
match pat.node {
pat_ident(*) => {
!pat_is_variant_or_struct(dm, pat) &&
!pat_is_const(dm, pat)
}
_ => false
}
}
fn pat_is_binding_or_wild(dm: resolve::DefMap, pat: @pat) -> bool {
match pat.node {
pat_ident(*) => pat_is_binding(dm, pat),
pat_wild => true,
_ => false
}
}
2012-08-29 15:26:26 -05:00
fn pat_bindings(dm: resolve::DefMap, pat: @pat,
it: fn(binding_mode, node_id, span, @path)) {
2012-06-30 18:19:07 -05:00
do walk_pat(pat) |p| {
2012-08-06 14:34:08 -05:00
match p.node {
pat_ident(binding_mode, pth, _) if pat_is_binding(dm, p) => {
it(binding_mode, p.id, p.span, pth);
}
2012-08-03 21:59:04 -05:00
_ => {}
}
}
}
2012-08-29 15:26:26 -05:00
fn pat_binding_ids(dm: resolve::DefMap, pat: @pat) -> ~[node_id] {
let mut found = ~[];
pat_bindings(dm, pat, |_bm, b_id, _sp, _pt| found.push(b_id) );
2012-08-01 19:30:05 -05:00
return found;
}