rust/src/librustc/middle/pat_util.rs

244 lines
7.6 KiB
Rust
Raw Normal View History

// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use middle::def::*;
2015-08-16 06:32:28 -04:00
use middle::def_id::DefId;
use middle::ty;
use util::nodemap::FnvHashMap;
use syntax::ast;
2015-07-31 00:04:06 -07:00
use rustc_front::hir;
use rustc_front::util::walk_pat;
use syntax::codemap::{respan, Span, Spanned, DUMMY_SP};
pub type PatIdMap = FnvHashMap<ast::Name, ast::NodeId>;
// This is used because same-named variables in alternative patterns need to
// use the NodeId of their namesake in the first pattern.
2015-07-31 00:04:06 -07:00
pub fn pat_id_map(dm: &DefMap, pat: &hir::Pat) -> PatIdMap {
let mut map = FnvHashMap();
pat_bindings(dm, pat, |_bm, p_id, _s, path1| {
map.insert(path1.node, p_id);
});
2013-03-03 11:44:11 -08:00
map
}
2015-07-31 00:04:06 -07:00
pub fn pat_is_refutable(dm: &DefMap, pat: &hir::Pat) -> bool {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatLit(_) | hir::PatRange(_, _) | hir::PatQPath(..) => true,
hir::PatEnum(_, _) |
hir::PatIdent(_, _, None) |
hir::PatStruct(..) => {
match dm.borrow().get(&pat.id).map(|d| d.full_def()) {
Some(DefVariant(..)) => true,
_ => false
}
}
2015-07-31 00:04:06 -07:00
hir::PatVec(_, _, _) => true,
_ => false
}
}
2015-07-31 00:04:06 -07:00
pub fn pat_is_variant_or_struct(dm: &DefMap, pat: &hir::Pat) -> bool {
2012-08-06 12:34:08 -07:00
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatEnum(_, _) |
hir::PatIdent(_, _, None) |
hir::PatStruct(..) => {
match dm.borrow().get(&pat.id).map(|d| d.full_def()) {
Some(DefVariant(..)) | Some(DefStruct(..)) => true,
_ => false
}
}
2012-08-03 19:59:04 -07:00
_ => false
}
}
2015-07-31 00:04:06 -07:00
pub fn pat_is_const(dm: &DefMap, pat: &hir::Pat) -> bool {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(_, _, None) | hir::PatEnum(..) | hir::PatQPath(..) => {
match dm.borrow().get(&pat.id).map(|d| d.full_def()) {
Some(DefConst(..)) | Some(DefAssociatedConst(..)) => true,
_ => false
}
}
_ => false
}
}
// Same as above, except that partially-resolved defs cause `false` to be
// returned instead of a panic.
2015-07-31 00:04:06 -07:00
pub fn pat_is_resolved_const(dm: &DefMap, pat: &hir::Pat) -> bool {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(_, _, None) | hir::PatEnum(..) | hir::PatQPath(..) => {
match dm.borrow().get(&pat.id)
.and_then(|d| if d.depth == 0 { Some(d.base_def) }
else { None } ) {
Some(DefConst(..)) | Some(DefAssociatedConst(..)) => true,
_ => false
}
}
_ => false
}
}
2015-07-31 00:04:06 -07:00
pub fn pat_is_binding(dm: &DefMap, pat: &hir::Pat) -> bool {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(..) => {
!pat_is_variant_or_struct(dm, pat) &&
!pat_is_const(dm, pat)
}
_ => false
}
}
2015-07-31 00:04:06 -07:00
pub fn pat_is_binding_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(..) => pat_is_binding(dm, pat),
hir::PatWild(_) => true,
_ => false
}
}
/// Call `it` on every "binding" in a pattern, e.g., on `a` in
/// `match foo() { Some(a) => (), None => () }`
2015-07-31 00:04:06 -07:00
pub fn pat_bindings<I>(dm: &DefMap, pat: &hir::Pat, mut it: I) where
I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Name>),
{
walk_pat(pat, |p| {
match p.node {
hir::PatIdent(binding_mode, ref pth, _) if pat_is_binding(dm, p) => {
it(binding_mode, p.id, p.span, &respan(pth.span, pth.node.name));
}
_ => {}
}
true
});
}
pub fn pat_bindings_hygienic<I>(dm: &DefMap, pat: &hir::Pat, mut it: I) where
I: FnMut(hir::BindingMode, ast::NodeId, Span, &Spanned<ast::Ident>),
2014-12-08 20:26:43 -05:00
{
walk_pat(pat, |p| {
2012-08-06 12:34:08 -07:00
match p.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(binding_mode, ref pth, _) if pat_is_binding(dm, p) => {
it(binding_mode, p.id, p.span, &respan(pth.span, pth.node));
}
2012-08-03 19:59:04 -07:00
_ => {}
}
true
});
}
/// Checks if the pattern contains any patterns that bind something to
2013-11-28 12:22:53 -08:00
/// an ident, e.g. `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
2015-07-31 00:04:06 -07:00
pub fn pat_contains_bindings(dm: &DefMap, pat: &hir::Pat) -> bool {
let mut contains_bindings = false;
walk_pat(pat, |p| {
if pat_is_binding(dm, p) {
contains_bindings = true;
false // there's at least one binding, can short circuit now.
} else {
true
}
});
contains_bindings
}
/// Checks if the pattern contains any `ref` or `ref mut` bindings,
/// and if yes wether its containing mutable ones or just immutables ones.
2015-07-31 00:04:06 -07:00
pub fn pat_contains_ref_binding(dm: &DefMap, pat: &hir::Pat) -> Option<hir::Mutability> {
let mut result = None;
When matching against a pattern (either via `match` or `let`) that contains ref-bindings, do not permit any upcasting from the type of the value being matched. Similarly, do not permit coercion in a `let`. This is a [breaking-change] in that it closes a type hole that previously existed, and in that coercion is not performed. You should be able to work around the latter by converting: ```rust let ref mut x: T = expr; ``` into ```rust let x: T = expr; let ref mut x = x; ``` Restricting coercion not to apply in the case of `let ref` or `let ref mut` is sort of unexciting to me, but seems the best solution: 1. Mixing coercion and `let ref` or `let ref mut` is a bit odd, because you are taking the address of a (coerced) temporary, but only sometimes. It's not syntactically evident, in other words, what's going on. When you're doing a coercion, you're kind of 2. Put another way, I would like to preserve the relationship that `equality <= subtyping <= coercion <= as-coercion`, where this is an indication of the number of `(T1,T2)` pairs that are accepted by the various relations. Trying to mix `let ref mut` and coercion would create another kind of relation that is like coercion, but acts differently in the case where a precise match is needed. 3. In any case, this is strictly more conservative than what we had before and we can undo it in the future if we find a way to make coercion mix with type equality. The change to match I feel ok about but similarly unthrilled. There is some subtle text already concerning whether to use eqtype or subtype for identifier bindings. The best fix I think would be to always have match use strict equality but use subtyping on identifier bindings, but the comment `(*)` explains why that's not working at the moment. As above, I think we can change this as we clean up the code there.
2015-03-06 10:14:12 -05:00
pat_bindings(dm, pat, |mode, _, _, _| {
match mode {
2015-07-31 00:04:06 -07:00
hir::BindingMode::BindByRef(m) => {
// Pick Mutable as maximum
match result {
2015-07-31 00:04:06 -07:00
None | Some(hir::MutImmutable) => result = Some(m),
_ => (),
}
}
2015-07-31 00:04:06 -07:00
hir::BindingMode::BindByValue(_) => { }
When matching against a pattern (either via `match` or `let`) that contains ref-bindings, do not permit any upcasting from the type of the value being matched. Similarly, do not permit coercion in a `let`. This is a [breaking-change] in that it closes a type hole that previously existed, and in that coercion is not performed. You should be able to work around the latter by converting: ```rust let ref mut x: T = expr; ``` into ```rust let x: T = expr; let ref mut x = x; ``` Restricting coercion not to apply in the case of `let ref` or `let ref mut` is sort of unexciting to me, but seems the best solution: 1. Mixing coercion and `let ref` or `let ref mut` is a bit odd, because you are taking the address of a (coerced) temporary, but only sometimes. It's not syntactically evident, in other words, what's going on. When you're doing a coercion, you're kind of 2. Put another way, I would like to preserve the relationship that `equality <= subtyping <= coercion <= as-coercion`, where this is an indication of the number of `(T1,T2)` pairs that are accepted by the various relations. Trying to mix `let ref mut` and coercion would create another kind of relation that is like coercion, but acts differently in the case where a precise match is needed. 3. In any case, this is strictly more conservative than what we had before and we can undo it in the future if we find a way to make coercion mix with type equality. The change to match I feel ok about but similarly unthrilled. There is some subtle text already concerning whether to use eqtype or subtype for identifier bindings. The best fix I think would be to always have match use strict equality but use subtyping on identifier bindings, but the comment `(*)` explains why that's not working at the moment. As above, I think we can change this as we clean up the code there.
2015-03-06 10:14:12 -05:00
}
});
result
}
/// Checks if the patterns for this arm contain any `ref` or `ref mut`
/// bindings, and if yes wether its containing mutable ones or just immutables ones.
2015-07-31 00:04:06 -07:00
pub fn arm_contains_ref_binding(dm: &DefMap, arm: &hir::Arm) -> Option<hir::Mutability> {
arm.pats.iter()
.filter_map(|pat| pat_contains_ref_binding(dm, pat))
.max_by(|m| match *m {
2015-07-31 00:04:06 -07:00
hir::MutMutable => 1,
hir::MutImmutable => 0,
})
When matching against a pattern (either via `match` or `let`) that contains ref-bindings, do not permit any upcasting from the type of the value being matched. Similarly, do not permit coercion in a `let`. This is a [breaking-change] in that it closes a type hole that previously existed, and in that coercion is not performed. You should be able to work around the latter by converting: ```rust let ref mut x: T = expr; ``` into ```rust let x: T = expr; let ref mut x = x; ``` Restricting coercion not to apply in the case of `let ref` or `let ref mut` is sort of unexciting to me, but seems the best solution: 1. Mixing coercion and `let ref` or `let ref mut` is a bit odd, because you are taking the address of a (coerced) temporary, but only sometimes. It's not syntactically evident, in other words, what's going on. When you're doing a coercion, you're kind of 2. Put another way, I would like to preserve the relationship that `equality <= subtyping <= coercion <= as-coercion`, where this is an indication of the number of `(T1,T2)` pairs that are accepted by the various relations. Trying to mix `let ref mut` and coercion would create another kind of relation that is like coercion, but acts differently in the case where a precise match is needed. 3. In any case, this is strictly more conservative than what we had before and we can undo it in the future if we find a way to make coercion mix with type equality. The change to match I feel ok about but similarly unthrilled. There is some subtle text already concerning whether to use eqtype or subtype for identifier bindings. The best fix I think would be to always have match use strict equality but use subtyping on identifier bindings, but the comment `(*)` explains why that's not working at the moment. As above, I think we can change this as we clean up the code there.
2015-03-06 10:14:12 -05:00
}
/// Checks if the pattern contains any patterns that bind something to
/// an ident or wildcard, e.g. `foo`, or `Foo(_)`, `foo @ Bar(..)`,
2015-07-31 00:04:06 -07:00
pub fn pat_contains_bindings_or_wild(dm: &DefMap, pat: &hir::Pat) -> bool {
let mut contains_bindings = false;
walk_pat(pat, |p| {
if pat_is_binding_or_wild(dm, p) {
contains_bindings = true;
false // there's at least one binding/wildcard, can short circuit now.
} else {
true
}
});
contains_bindings
}
pub fn simple_name<'a>(pat: &'a hir::Pat) -> Option<ast::Name> {
match pat.node {
2015-07-31 00:04:06 -07:00
hir::PatIdent(hir::BindByValue(_), ref path1, None) => {
Some(path1.node.name)
}
_ => {
None
}
}
}
2015-07-31 00:04:06 -07:00
pub fn def_to_path(tcx: &ty::ctxt, id: DefId) -> hir::Path {
tcx.with_path(id, |path| hir::Path {
global: false,
2015-07-31 00:04:06 -07:00
segments: path.last().map(|elem| hir::PathSegment {
identifier: ast::Ident::with_empty_ctxt(elem.name()),
2015-07-31 00:04:06 -07:00
parameters: hir::PathParameters::none(),
2014-09-14 20:27:36 -07:00
}).into_iter().collect(),
span: DUMMY_SP,
})
}
/// Return variants that are necessary to exist for the pattern to match.
pub fn necessary_variants(dm: &DefMap, pat: &hir::Pat) -> Vec<DefId> {
let mut variants = vec![];
walk_pat(pat, |p| {
match p.node {
2015-07-31 00:04:06 -07:00
hir::PatEnum(_, _) |
hir::PatIdent(_, _, None) |
hir::PatStruct(..) => {
match dm.borrow().get(&p.id) {
Some(&PathResolution { base_def: DefVariant(_, id, _), .. }) => {
variants.push(id);
}
_ => ()
}
}
_ => ()
}
true
});
variants.sort();
variants.dedup();
variants
}