1
Fork 0

Auto merge of #54151 - ljedrz:cleanup_hir, r=michaelwoerister

A few cleanups for hir

- prefer `if let` to `match` when only 1 branch matters
- `chain` iterable items that are looped over in sequence
- `sort_by_key` instead of `sort_by` when possible
- change cloning `map`s to `cloned()`
- use `unwrap_or_else` and `ok` when applicable
- a few other minor readability improvements
- whitespace fixes
This commit is contained in:
bors 2018-09-15 02:56:13 +00:00
commit ed45f9cbf4
11 changed files with 93 additions and 155 deletions

View file

@ -125,7 +125,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
.iter() .iter()
.filter(|attr| attr.name() == "repr") .filter(|attr| attr.name() == "repr")
.filter_map(|attr| attr.meta_item_list()) .filter_map(|attr| attr.meta_item_list())
.flat_map(|hints| hints) .flatten()
.collect(); .collect();
let mut int_reprs = 0; let mut int_reprs = 0;
@ -185,7 +185,7 @@ impl<'a, 'tcx> CheckAttrVisitor<'a, 'tcx> {
continue continue
} }
} }
"i8" | "u8" | "i16" | "u16" | "i8" | "u8" | "i16" | "u16" |
"i32" | "u32" | "i64" | "u64" | "i32" | "u32" | "i64" | "u64" |
"isize" | "usize" => { "isize" | "usize" => {
int_reprs += 1; int_reprs += 1;

View file

@ -50,7 +50,6 @@ use super::itemlikevisit::DeepVisitor;
use std::cmp; use std::cmp;
use std::u32; use std::u32;
use std::result::Result::Err;
#[derive(Copy, Clone)] #[derive(Copy, Clone)]
pub enum FnKind<'a> { pub enum FnKind<'a> {
@ -1067,31 +1066,26 @@ pub fn walk_expr<'v, V: Visitor<'v>>(visitor: &mut V, expression: &'v Expr) {
ExprKind::Break(ref destination, ref opt_expr) => { ExprKind::Break(ref destination, ref opt_expr) => {
if let Some(ref label) = destination.label { if let Some(ref label) = destination.label {
visitor.visit_label(label); visitor.visit_label(label);
match destination.target_id { if let Ok(node_id) = destination.target_id {
Ok(node_id) => visitor.visit_def_mention(Def::Label(node_id)), visitor.visit_def_mention(Def::Label(node_id))
Err(_) => {}, }
};
} }
walk_list!(visitor, visit_expr, opt_expr); walk_list!(visitor, visit_expr, opt_expr);
} }
ExprKind::Continue(ref destination) => { ExprKind::Continue(ref destination) => {
if let Some(ref label) = destination.label { if let Some(ref label) = destination.label {
visitor.visit_label(label); visitor.visit_label(label);
match destination.target_id { if let Ok(node_id) = destination.target_id {
Ok(node_id) => visitor.visit_def_mention(Def::Label(node_id)), visitor.visit_def_mention(Def::Label(node_id))
Err(_) => {}, }
};
} }
} }
ExprKind::Ret(ref optional_expression) => { ExprKind::Ret(ref optional_expression) => {
walk_list!(visitor, visit_expr, optional_expression); walk_list!(visitor, visit_expr, optional_expression);
} }
ExprKind::InlineAsm(_, ref outputs, ref inputs) => { ExprKind::InlineAsm(_, ref outputs, ref inputs) => {
for output in outputs { for expr in outputs.iter().chain(inputs.iter()) {
visitor.visit_expr(output) visitor.visit_expr(expr)
}
for input in inputs {
visitor.visit_expr(input)
} }
} }
ExprKind::Yield(ref subexpression) => { ExprKind::Yield(ref subexpression) => {
@ -1156,7 +1150,6 @@ impl IdRange {
self.min = cmp::min(self.min, id); self.min = cmp::min(self.min, id);
self.max = cmp::max(self.max, NodeId::from_u32(id.as_u32() + 1)); self.max = cmp::max(self.max, NodeId::from_u32(id.as_u32() + 1));
} }
} }

View file

@ -597,7 +597,7 @@ impl<'a> LoweringContext<'a> {
}) })
} }
fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item=Def> { fn expect_full_def_from_use(&mut self, id: NodeId) -> impl Iterator<Item = Def> {
self.resolver.get_import(id).present_items().map(|pr| { self.resolver.get_import(id).present_items().map(|pr| {
if pr.unresolved_segments() != 0 { if pr.unresolved_segments() != 0 {
bug!("path not fully resolved: {:?}", pr); bug!("path not fully resolved: {:?}", pr);
@ -990,7 +990,7 @@ impl<'a> LoweringContext<'a> {
None => { None => {
self.loop_scopes self.loop_scopes
.last() .last()
.map(|innermost_loop_id| *innermost_loop_id) .cloned()
.map(|id| Ok(self.lower_node_id(id).node_id)) .map(|id| Ok(self.lower_node_id(id).node_id))
.unwrap_or(Err(hir::LoopIdError::OutsideLoopScope)) .unwrap_or(Err(hir::LoopIdError::OutsideLoopScope))
.into() .into()

View file

@ -161,27 +161,27 @@ impl<'a> FnLikeNode<'a> {
} }
pub fn body(self) -> ast::BodyId { pub fn body(self) -> ast::BodyId {
self.handle(|i: ItemFnParts<'a>| i.body, self.handle(|i: ItemFnParts<'a>| i.body,
|_, _, _: &'a ast::MethodSig, _, body: ast::BodyId, _, _| body, |_, _, _: &'a ast::MethodSig, _, body: ast::BodyId, _, _| body,
|c: ClosureParts<'a>| c.body) |c: ClosureParts<'a>| c.body)
} }
pub fn decl(self) -> &'a FnDecl { pub fn decl(self) -> &'a FnDecl {
self.handle(|i: ItemFnParts<'a>| &*i.decl, self.handle(|i: ItemFnParts<'a>| &*i.decl,
|_, _, sig: &'a ast::MethodSig, _, _, _, _| &sig.decl, |_, _, sig: &'a ast::MethodSig, _, _, _, _| &sig.decl,
|c: ClosureParts<'a>| c.decl) |c: ClosureParts<'a>| c.decl)
} }
pub fn span(self) -> Span { pub fn span(self) -> Span {
self.handle(|i: ItemFnParts| i.span, self.handle(|i: ItemFnParts| i.span,
|_, _, _: &'a ast::MethodSig, _, _, span, _| span, |_, _, _: &'a ast::MethodSig, _, _, span, _| span,
|c: ClosureParts| c.span) |c: ClosureParts| c.span)
} }
pub fn id(self) -> NodeId { pub fn id(self) -> NodeId {
self.handle(|i: ItemFnParts| i.id, self.handle(|i: ItemFnParts| i.id,
|id, _, _: &'a ast::MethodSig, _, _, _, _| id, |id, _, _: &'a ast::MethodSig, _, _, _, _| id,
|c: ClosureParts| c.id) |c: ClosureParts| c.id)
} }
pub fn constness(self) -> ast::Constness { pub fn constness(self) -> ast::Constness {
@ -260,9 +260,7 @@ impl<'a> FnLikeNode<'a> {
ast::ImplItemKind::Method(ref sig, body) => { ast::ImplItemKind::Method(ref sig, body) => {
method(ii.id, ii.ident, sig, Some(&ii.vis), body, ii.span, &ii.attrs) method(ii.id, ii.ident, sig, Some(&ii.vis), body, ii.span, &ii.attrs)
} }
_ => { _ => bug!("impl method FnLikeNode that is not fn-like")
bug!("impl method FnLikeNode that is not fn-like")
}
} }
}, },
map::Node::Expr(e) => match e.node { map::Node::Expr(e) => match e.node {

View file

@ -67,7 +67,6 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
// them explicitly here. // them explicitly here.
ref attrs, ref attrs,
span, span,
// These fields are handled separately: // These fields are handled separately:
exported_macros: _, exported_macros: _,
items: _, items: _,
@ -128,14 +127,14 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
cstore: &dyn CrateStore, cstore: &dyn CrateStore,
source_map: &SourceMap, source_map: &SourceMap,
commandline_args_hash: u64) commandline_args_hash: u64)
-> (Vec<Option<Entry<'hir>>>, Svh) { -> (Vec<Option<Entry<'hir>>>, Svh)
self.hir_body_nodes {
.sort_unstable_by(|&(ref d1, _), &(ref d2, _)| d1.cmp(d2)); self.hir_body_nodes.sort_unstable_by_key(|bn| bn.0);
let node_hashes = self let node_hashes = self
.hir_body_nodes .hir_body_nodes
.iter() .iter()
.fold(Fingerprint::ZERO, |fingerprint , &(def_path_hash, dep_node_index)| { .fold(Fingerprint::ZERO, |fingerprint, &(def_path_hash, dep_node_index)| {
fingerprint.combine( fingerprint.combine(
def_path_hash.0.combine(self.dep_graph.fingerprint_of(dep_node_index)) def_path_hash.0.combine(self.dep_graph.fingerprint_of(dep_node_index))
) )
@ -143,15 +142,12 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
let mut upstream_crates: Vec<_> = cstore.crates_untracked().iter().map(|&cnum| { let mut upstream_crates: Vec<_> = cstore.crates_untracked().iter().map(|&cnum| {
let name = cstore.crate_name_untracked(cnum).as_str(); let name = cstore.crate_name_untracked(cnum).as_str();
let disambiguator = cstore.crate_disambiguator_untracked(cnum) let disambiguator = cstore.crate_disambiguator_untracked(cnum).to_fingerprint();
.to_fingerprint();
let hash = cstore.crate_hash_untracked(cnum); let hash = cstore.crate_hash_untracked(cnum);
(name, disambiguator, hash) (name, disambiguator, hash)
}).collect(); }).collect();
upstream_crates.sort_unstable_by(|&(name1, dis1, _), &(name2, dis2, _)| { upstream_crates.sort_unstable_by_key(|&(name, dis, _)| (name, dis));
(name1, dis1).cmp(&(name2, dis2))
});
// We hash the final, remapped names of all local source files so we // We hash the final, remapped names of all local source files so we
// don't have to include the path prefix remapping commandline args. // don't have to include the path prefix remapping commandline args.
@ -229,7 +225,6 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
} }
self.insert_entry(id, entry); self.insert_entry(id, entry);
} }
fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_id: NodeId, f: F) { fn with_parent<F: FnOnce(&mut Self)>(&mut self, parent_id: NodeId, f: F) {
@ -311,14 +306,11 @@ impl<'a, 'hir> Visitor<'hir> for NodeCollector<'a, 'hir> {
self.with_dep_node_owner(i.hir_id.owner, i, |this| { self.with_dep_node_owner(i.hir_id.owner, i, |this| {
this.insert(i.id, Node::Item(i)); this.insert(i.id, Node::Item(i));
this.with_parent(i.id, |this| { this.with_parent(i.id, |this| {
match i.node { if let ItemKind::Struct(ref struct_def, _) = i.node {
ItemKind::Struct(ref struct_def, _) => { // If this is a tuple-like struct, register the constructor.
// If this is a tuple-like struct, register the constructor. if !struct_def.is_struct() {
if !struct_def.is_struct() { this.insert(struct_def.id(), Node::StructCtor(struct_def));
this.insert(struct_def.id(), Node::StructCtor(struct_def));
}
} }
_ => {}
} }
intravisit::walk_item(this, i); intravisit::walk_item(this, i);
}); });

View file

@ -348,13 +348,10 @@ impl<'a> visit::Visitor<'a> for DefCollector<'a> {
fn visit_token(&mut self, t: Token) { fn visit_token(&mut self, t: Token) {
if let Token::Interpolated(nt) = t { if let Token::Interpolated(nt) = t {
match nt.0 { if let token::NtExpr(ref expr) = nt.0 {
token::NtExpr(ref expr) => { if let ExprKind::Mac(..) = expr.node {
if let ExprKind::Mac(..) = expr.node { self.visit_macro_invoc(expr.id);
self.visit_macro_invoc(expr.id);
}
} }
_ => {}
} }
} }
} }

View file

@ -317,10 +317,8 @@ pub enum DefPathData {
// they are treated specially by the `def_path` function. // they are treated specially by the `def_path` function.
/// The crate root (marker) /// The crate root (marker)
CrateRoot, CrateRoot,
// Catch-all for random DefId things like DUMMY_NODE_ID // Catch-all for random DefId things like DUMMY_NODE_ID
Misc, Misc,
// Different kinds of items and item-like things: // Different kinds of items and item-like things:
/// An impl /// An impl
Impl, Impl,
@ -342,7 +340,6 @@ pub enum DefPathData {
MacroDef(InternedString), MacroDef(InternedString),
/// A closure expression /// A closure expression
ClosureExpr, ClosureExpr,
// Subportions of items // Subportions of items
/// A type parameter (generic parameter) /// A type parameter (generic parameter)
TypeParam(InternedString), TypeParam(InternedString),
@ -358,7 +355,6 @@ pub enum DefPathData {
AnonConst, AnonConst,
/// An `impl Trait` type node /// An `impl Trait` type node
ImplTrait, ImplTrait,
/// GlobalMetaData identifies a piece of crate metadata that is global to /// GlobalMetaData identifies a piece of crate metadata that is global to
/// a whole crate (as opposed to just one item). GlobalMetaData components /// a whole crate (as opposed to just one item). GlobalMetaData components
/// are only supposed to show up right below the crate root. /// are only supposed to show up right below the crate root.
@ -656,10 +652,8 @@ impl DefPathData {
GlobalMetaData(name) => { GlobalMetaData(name) => {
return name return name
} }
// note that this does not show up in user printouts // note that this does not show up in user printouts
CrateRoot => "{{root}}", CrateRoot => "{{root}}",
Impl => "{{impl}}", Impl => "{{impl}}",
Misc => "{{?}}", Misc => "{{?}}",
ClosureExpr => "{{closure}}", ClosureExpr => "{{closure}}",

View file

@ -100,8 +100,8 @@ impl<'a, 'hir: 'a> HirIdValidator<'a, 'hir> {
if max != self.hir_ids_seen.len() - 1 { if max != self.hir_ids_seen.len() - 1 {
// Collect the missing ItemLocalIds // Collect the missing ItemLocalIds
let missing: Vec<_> = (0 .. max + 1) let missing: Vec<_> = (0 .. max as u32 + 1)
.filter(|&i| !self.hir_ids_seen.contains_key(&ItemLocalId(i as u32))) .filter(|&i| !self.hir_ids_seen.contains_key(&ItemLocalId(i)))
.collect(); .collect();
// Try to map those to something more useful // Try to map those to something more useful

View file

@ -291,8 +291,7 @@ impl<'hir> Map<'hir> {
}; };
match item.node { match item.node {
ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), ItemKind::Static(_, m, _) => Some(Def::Static(def_id(), m == MutMutable)),
m == MutMutable)),
ItemKind::Const(..) => Some(Def::Const(def_id())), ItemKind::Const(..) => Some(Def::Const(def_id())),
ItemKind::Fn(..) => Some(Def::Fn(def_id())), ItemKind::Fn(..) => Some(Def::Fn(def_id())),
ItemKind::Mod(..) => Some(Def::Mod(def_id())), ItemKind::Mod(..) => Some(Def::Mod(def_id())),
@ -408,7 +407,7 @@ impl<'hir> Map<'hir> {
pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> { pub fn fn_decl(&self, node_id: ast::NodeId) -> Option<FnDecl> {
if let Some(entry) = self.find_entry(node_id) { if let Some(entry) = self.find_entry(node_id) {
entry.fn_decl().map(|fd| fd.clone()) entry.fn_decl().cloned()
} else { } else {
bug!("no entry for node_id `{}`", node_id) bug!("no entry for node_id `{}`", node_id)
} }
@ -471,18 +470,13 @@ impl<'hir> Map<'hir> {
match self.get(id) { match self.get(id) {
Node::Item(&Item { node: ItemKind::Trait(..), .. }) => id, Node::Item(&Item { node: ItemKind::Trait(..), .. }) => id,
Node::GenericParam(_) => self.get_parent_node(id), Node::GenericParam(_) => self.get_parent_node(id),
_ => { _ => bug!("ty_param_owner: {} not a type parameter", self.node_to_string(id))
bug!("ty_param_owner: {} not a type parameter",
self.node_to_string(id))
}
} }
} }
pub fn ty_param_name(&self, id: NodeId) -> Name { pub fn ty_param_name(&self, id: NodeId) -> Name {
match self.get(id) { match self.get(id) {
Node::Item(&Item { node: ItemKind::Trait(..), .. }) => { Node::Item(&Item { node: ItemKind::Trait(..), .. }) => keywords::SelfType.name(),
keywords::SelfType.name()
}
Node::GenericParam(param) => param.name.ident().name, Node::GenericParam(param) => param.name.ident().name,
_ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)), _ => bug!("ty_param_name: {} not a type parameter", self.node_to_string(id)),
} }
@ -521,10 +515,8 @@ impl<'hir> Map<'hir> {
/// Retrieve the Node corresponding to `id`, panicking if it cannot /// Retrieve the Node corresponding to `id`, panicking if it cannot
/// be found. /// be found.
pub fn get(&self, id: NodeId) -> Node<'hir> { pub fn get(&self, id: NodeId) -> Node<'hir> {
match self.find(id) { // read recorded by `find`
Some(node) => node, // read recorded by `find` self.find(id).unwrap_or_else(|| bug!("couldn't find node id {} in the AST map", id))
None => bug!("couldn't find node id {} in the AST map", id)
}
} }
pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> { pub fn get_if_local(&self, id: DefId) -> Option<Node<'hir>> {
@ -697,10 +689,7 @@ impl<'hir> Map<'hir> {
} }
}; };
match self.walk_parent_nodes(id, match_fn, match_non_returning_block) { self.walk_parent_nodes(id, match_fn, match_non_returning_block).ok()
Ok(id) => Some(id),
Err(_) => None,
}
} }
/// Retrieve the NodeId for `id`'s parent item, or `id` itself if no /// Retrieve the NodeId for `id`'s parent item, or `id` itself if no
@ -738,17 +727,14 @@ impl<'hir> Map<'hir> {
/// and associated types probably shouldn't, for example. Behavior in this /// and associated types probably shouldn't, for example. Behavior in this
/// regard should be expected to be highly unstable. /// regard should be expected to be highly unstable.
pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> { pub fn get_enclosing_scope(&self, id: NodeId) -> Option<NodeId> {
match self.walk_parent_nodes(id, |node| match *node { self.walk_parent_nodes(id, |node| match *node {
Node::Item(_) | Node::Item(_) |
Node::ForeignItem(_) | Node::ForeignItem(_) |
Node::TraitItem(_) | Node::TraitItem(_) |
Node::ImplItem(_) | Node::ImplItem(_) |
Node::Block(_) => true, Node::Block(_) => true,
_ => false, _ => false,
}, |_| false) { }, |_| false).ok()
Ok(id) => Some(id),
Err(_) => None,
}
} }
pub fn get_parent_did(&self, id: NodeId) -> DefId { pub fn get_parent_did(&self, id: NodeId) -> DefId {
@ -758,13 +744,11 @@ impl<'hir> Map<'hir> {
pub fn get_foreign_abi(&self, id: NodeId) -> Abi { pub fn get_foreign_abi(&self, id: NodeId) -> Abi {
let parent = self.get_parent(id); let parent = self.get_parent(id);
if let Some(entry) = self.find_entry(parent) { if let Some(entry) = self.find_entry(parent) {
match entry { if let Entry {
Entry { node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } node: Node::Item(Item { node: ItemKind::ForeignMod(ref nm), .. }), .. } = entry
=> { {
self.read(id); // reveals some of the content of a node self.read(id); // reveals some of the content of a node
return nm.abi; return nm.abi;
}
_ => {}
} }
} }
bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent)) bug!("expected foreign mod or inlined parent, found {}", self.node_to_string(parent))
@ -797,18 +781,12 @@ impl<'hir> Map<'hir> {
match i.node { match i.node {
ItemKind::Struct(ref struct_def, _) | ItemKind::Struct(ref struct_def, _) |
ItemKind::Union(ref struct_def, _) => struct_def, ItemKind::Union(ref struct_def, _) => struct_def,
_ => { _ => bug!("struct ID bound to non-struct {}", self.node_to_string(id))
bug!("struct ID bound to non-struct {}",
self.node_to_string(id));
}
} }
} }
Some(Node::StructCtor(data)) => data, Some(Node::StructCtor(data)) => data,
Some(Node::Variant(variant)) => &variant.node.data, Some(Node::Variant(variant)) => &variant.node.data,
_ => { _ => bug!("expected struct or variant, found {}", self.node_to_string(id))
bug!("expected struct or variant, found {}",
self.node_to_string(id));
}
} }
} }
@ -866,9 +844,7 @@ impl<'hir> Map<'hir> {
Some(Node::GenericParam(param)) => Some(&param.attrs[..]), Some(Node::GenericParam(param)) => Some(&param.attrs[..]),
// unit/tuple structs take the attributes straight from // unit/tuple structs take the attributes straight from
// the struct definition. // the struct definition.
Some(Node::StructCtor(_)) => { Some(Node::StructCtor(_)) => return self.attrs(self.get_parent(id)),
return self.attrs(self.get_parent(id));
}
_ => None _ => None
}; };
attrs.unwrap_or(&[]) attrs.unwrap_or(&[])
@ -917,7 +893,6 @@ impl<'hir> Map<'hir> {
Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v), Some(Node::Visibility(v)) => bug!("unexpected Visibility {:?}", v),
Some(Node::Local(local)) => local.span, Some(Node::Local(local)) => local.span,
Some(Node::MacroDef(macro_def)) => macro_def.span, Some(Node::MacroDef(macro_def)) => macro_def.span,
Some(Node::Crate) => self.forest.krate.span, Some(Node::Crate) => self.forest.krate.span,
None => bug!("hir::map::Map::span: id not in map: {:?}", id), None => bug!("hir::map::Map::span: id not in map: {:?}", id),
} }
@ -976,10 +951,10 @@ impl<'a, 'hir> NodesMatchingSuffix<'a, 'hir> {
// chain, then returns `None`. // chain, then returns `None`.
fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> { fn find_first_mod_parent<'a>(map: &'a Map, mut id: NodeId) -> Option<(NodeId, Name)> {
loop { loop {
match map.find(id)? { if let Node::Item(item) = map.find(id)? {
Node::Item(item) if item_is_mod(&item) => if item_is_mod(&item) {
return Some((id, item.name)), return Some((id, item.name))
_ => {} }
} }
let parent = map.get_parent(id); let parent = map.get_parent(id);
if parent == id { return None } if parent == id { return None }
@ -1041,7 +1016,6 @@ impl Named for StructField { fn name(&self) -> Name { self.ident.name } }
impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } } impl Named for TraitItem { fn name(&self) -> Name { self.ident.name } }
impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } } impl Named for ImplItem { fn name(&self) -> Name { self.ident.name } }
pub fn map_crate<'hir>(sess: &::session::Session, pub fn map_crate<'hir>(sess: &::session::Session,
cstore: &dyn CrateStore, cstore: &dyn CrateStore,
forest: &'hir mut Forest, forest: &'hir mut Forest,
@ -1142,7 +1116,7 @@ impl<'a> print::State<'a> {
Node::StructCtor(_) => bug!("cannot print isolated StructCtor"), Node::StructCtor(_) => bug!("cannot print isolated StructCtor"),
Node::Local(a) => self.print_local_decl(&a), Node::Local(a) => self.print_local_decl(&a),
Node::MacroDef(_) => bug!("cannot print MacroDef"), Node::MacroDef(_) => bug!("cannot print MacroDef"),
Node::Crate => bug!("cannot print Crate"), Node::Crate => bug!("cannot print Crate"),
} }
} }
} }

View file

@ -831,9 +831,10 @@ impl Pat {
s.walk_(it) s.walk_(it)
} }
PatKind::Slice(ref before, ref slice, ref after) => { PatKind::Slice(ref before, ref slice, ref after) => {
before.iter().all(|p| p.walk_(it)) && before.iter()
slice.iter().all(|p| p.walk_(it)) && .chain(slice.iter())
after.iter().all(|p| p.walk_(it)) .chain(after.iter())
.all(|p| p.walk_(it))
} }
PatKind::Wild | PatKind::Wild |
PatKind::Lit(_) | PatKind::Lit(_) |
@ -872,23 +873,23 @@ pub struct FieldPat {
/// inference. /// inference.
#[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)] #[derive(Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, Copy)]
pub enum BindingAnnotation { pub enum BindingAnnotation {
/// No binding annotation given: this means that the final binding mode /// No binding annotation given: this means that the final binding mode
/// will depend on whether we have skipped through a `&` reference /// will depend on whether we have skipped through a `&` reference
/// when matching. For example, the `x` in `Some(x)` will have binding /// when matching. For example, the `x` in `Some(x)` will have binding
/// mode `None`; if you do `let Some(x) = &Some(22)`, it will /// mode `None`; if you do `let Some(x) = &Some(22)`, it will
/// ultimately be inferred to be by-reference. /// ultimately be inferred to be by-reference.
/// ///
/// Note that implicit reference skipping is not implemented yet (#42640). /// Note that implicit reference skipping is not implemented yet (#42640).
Unannotated, Unannotated,
/// Annotated with `mut x` -- could be either ref or not, similar to `None`. /// Annotated with `mut x` -- could be either ref or not, similar to `None`.
Mutable, Mutable,
/// Annotated as `ref`, like `ref x` /// Annotated as `ref`, like `ref x`
Ref, Ref,
/// Annotated as `ref mut x`. /// Annotated as `ref mut x`.
RefMut, RefMut,
} }
#[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)] #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug)]
@ -1658,7 +1659,6 @@ pub struct TypeBinding {
pub span: Span, pub span: Span,
} }
#[derive(Clone, RustcEncodable, RustcDecodable)] #[derive(Clone, RustcEncodable, RustcDecodable)]
pub struct Ty { pub struct Ty {
pub id: NodeId, pub id: NodeId,
@ -2284,7 +2284,6 @@ pub type TraitMap = NodeMap<Vec<TraitCandidate>>;
// imported. // imported.
pub type GlobMap = NodeMap<FxHashSet<Name>>; pub type GlobMap = NodeMap<FxHashSet<Name>>;
pub fn provide(providers: &mut Providers) { pub fn provide(providers: &mut Providers) {
providers.describe_def = map::describe_def; providers.describe_def = map::describe_def;
} }

View file

@ -251,6 +251,7 @@ impl<'a> State<'a> {
pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> { pub fn bclose_(&mut self, span: syntax_pos::Span, indented: usize) -> io::Result<()> {
self.bclose_maybe_open(span, indented, true) self.bclose_maybe_open(span, indented, true)
} }
pub fn bclose_maybe_open(&mut self, pub fn bclose_maybe_open(&mut self,
span: syntax_pos::Span, span: syntax_pos::Span,
indented: usize, indented: usize,
@ -264,6 +265,7 @@ impl<'a> State<'a> {
} }
Ok(()) Ok(())
} }
pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> { pub fn bclose(&mut self, span: syntax_pos::Span) -> io::Result<()> {
self.bclose_(span, indent_unit) self.bclose_(span, indent_unit)
} }
@ -274,12 +276,14 @@ impl<'a> State<'a> {
None => false, None => false,
} }
} }
pub fn space_if_not_bol(&mut self) -> io::Result<()> { pub fn space_if_not_bol(&mut self) -> io::Result<()> {
if !self.is_bol() { if !self.is_bol() {
self.s.space()?; self.s.space()?;
} }
Ok(()) Ok(())
} }
pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> { pub fn break_offset_if_not_bol(&mut self, n: usize, off: isize) -> io::Result<()> {
if !self.is_bol() { if !self.is_bol() {
self.s.break_offset(n, off) self.s.break_offset(n, off)
@ -304,7 +308,6 @@ impl<'a> State<'a> {
self.s.word("*/") self.s.word("*/")
} }
pub fn commasep_cmnt<T, F, G>(&mut self, pub fn commasep_cmnt<T, F, G>(&mut self,
b: Breaks, b: Breaks,
elts: &[T], elts: &[T],
@ -689,20 +692,14 @@ impl<'a> State<'a> {
self.s.space()?; self.s.space()?;
} }
match polarity { if let hir::ImplPolarity::Negative = polarity {
hir::ImplPolarity::Negative => { self.s.word("!")?;
self.s.word("!")?;
}
_ => {}
} }
match opt_trait { if let Some(ref t) = opt_trait {
&Some(ref t) => { self.print_trait_ref(t)?;
self.print_trait_ref(t)?; self.s.space()?;
self.s.space()?; self.word_space("for")?;
self.word_space("for")?;
}
&None => {}
} }
self.print_type(&ty)?; self.print_type(&ty)?;
@ -1061,13 +1058,10 @@ impl<'a> State<'a> {
for st in &blk.stmts { for st in &blk.stmts {
self.print_stmt(st)?; self.print_stmt(st)?;
} }
match blk.expr { if let Some(ref expr) = blk.expr {
Some(ref expr) => { self.space_if_not_bol()?;
self.space_if_not_bol()?; self.print_expr(&expr)?;
self.print_expr(&expr)?; self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
self.maybe_print_trailing_comment(expr.span, Some(blk.span.hi()))?;
}
_ => (),
} }
self.bclose_maybe_open(blk.span, indented, close_box)?; self.bclose_maybe_open(blk.span, indented, close_box)?;
self.ann.post(self, AnnNode::Block(blk)) self.ann.post(self, AnnNode::Block(blk))
@ -1479,12 +1473,9 @@ impl<'a> State<'a> {
} }
hir::ExprKind::Ret(ref result) => { hir::ExprKind::Ret(ref result) => {
self.s.word("return")?; self.s.word("return")?;
match *result { if let Some(ref expr) = *result {
Some(ref expr) => { self.s.word(" ")?;
self.s.word(" ")?; self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
self.print_expr_maybe_paren(&expr, parser::PREC_JUMP)?;
}
_ => (),
} }
} }
hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => { hir::ExprKind::InlineAsm(ref a, ref outputs, ref inputs) => {