Auto merge of #34638 - zackmdavis:if_let_over_none_empty_block_arm, r=jseyfried

prefer `if let` to match with `None => {}` arm in some places

This is a spiritual succesor to #34268 / 8531d581, in which we replaced a
number of matches of None to the unit value with `if let` conditionals
where it was judged that this made for clearer/simpler code (as would be
recommended by Manishearth/rust-clippy's `single_match` lint). The same
rationale applies to matches of None to the empty block.

----

r? @jseyfried
This commit is contained in:
bors 2016-07-04 02:18:46 -07:00 committed by GitHub
commit d508de6cf7
47 changed files with 213 additions and 347 deletions

View File

@ -840,11 +840,8 @@ pub fn write(output: &mut Write, args: Arguments) -> Result {
}
// There can be only one trailing string piece left.
match pieces.next() {
Some(piece) => {
formatter.buf.write_str(*piece)?;
}
None => {}
if let Some(piece) = pieces.next() {
formatter.buf.write_str(*piece)?;
}
Ok(())

View File

@ -144,9 +144,8 @@ impl Rand for char {
// Rejection sampling. About 0.2% of numbers with at most
// 21-bits are invalid codepoints (surrogates), so this
// will succeed first go almost every time.
match char::from_u32(rng.next_u32() & CHAR_MASK) {
Some(c) => return c,
None => {}
if let Some(c) = char::from_u32(rng.next_u32() & CHAR_MASK) {
return c;
}
}
}

View File

@ -1697,13 +1697,10 @@ impl<'a> State<'a> {
self.commasep(Inconsistent, &data.inputs, |s, ty| s.print_type(&ty))?;
word(&mut self.s, ")")?;
match data.output {
None => {}
Some(ref ty) => {
self.space_if_not_bol()?;
self.word_space("->")?;
self.print_type(&ty)?;
}
if let Some(ref ty) = data.output {
self.space_if_not_bol()?;
self.word_space("->")?;
self.print_type(&ty)?;
}
}
}

View File

@ -842,11 +842,8 @@ impl<'a, 'gcx, 'tcx> RegionVarBindings<'a, 'gcx, 'tcx> {
where F: FnMut(&RegionVarBindings<'a, 'gcx, 'tcx>, Region, Region)
{
let vars = TwoRegions { a: a, b: b };
match self.combine_map(t).borrow().get(&vars) {
Some(&c) => {
return ReVar(c);
}
None => {}
if let Some(&c) = self.combine_map(t).borrow().get(&vars) {
return ReVar(c);
}
let c = self.new_region_var(MiscVariable(origin.span()));
self.combine_map(t).borrow_mut().insert(vars, c);

View File

@ -1055,13 +1055,10 @@ impl<'a> ast_visit::Visitor for EarlyContext<'a> {
// Output any lints that were previously added to the session.
impl<'a, 'tcx> IdVisitingOperation for LateContext<'a, 'tcx> {
fn visit_id(&mut self, id: ast::NodeId) {
match self.sess().lints.borrow_mut().remove(&id) {
None => {}
Some(lints) => {
debug!("LateContext::visit_id: id={:?} lints={:?}", id, lints);
for (lint_id, span, msg) in lints {
self.span_lint(lint_id.lint, span, &msg[..])
}
if let Some(lints) = self.sess().lints.borrow_mut().remove(&id) {
debug!("LateContext::visit_id: id={:?} lints={:?}", id, lints);
for (lint_id, span, msg) in lints {
self.span_lint(lint_id.lint, span, &msg[..])
}
}
}

View File

@ -168,9 +168,8 @@ fn build_nodeid_to_index(decl: Option<&hir::FnDecl>,
// into cfg itself? i.e. introduce a fn-based flow-graph in
// addition to the current block-based flow-graph, rather than
// have to put traversals like this here?
match decl {
None => {}
Some(decl) => add_entries_from_fn_decl(&mut index, decl, cfg.entry)
if let Some(decl) = decl {
add_entries_from_fn_decl(&mut index, decl, cfg.entry);
}
cfg.graph.each_node(|node_idx, node| {

View File

@ -105,9 +105,8 @@ fn calculate_type(sess: &session::Session,
// If the global prefer_dynamic switch is turned off, first attempt
// static linkage (this can fail).
config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
if let Some(v) = attempt_static(sess) {
return v;
}
}
@ -119,9 +118,8 @@ fn calculate_type(sess: &session::Session,
// to be found, we generate some nice pretty errors.
config::CrateTypeStaticlib |
config::CrateTypeCdylib => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
if let Some(v) = attempt_static(sess) {
return v;
}
for cnum in sess.cstore.crates() {
let src = sess.cstore.used_crate_source(cnum);
@ -136,9 +134,8 @@ fn calculate_type(sess: &session::Session,
// to try to eagerly statically link all dependencies. This is normally
// done for end-product dylibs, not intermediate products.
config::CrateTypeDylib if !sess.opts.cg.prefer_dynamic => {
match attempt_static(sess) {
Some(v) => return v,
None => {}
if let Some(v) = attempt_static(sess) {
return v;
}
}

View File

@ -735,26 +735,23 @@ impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> {
for i in 0..autoderefs {
let deref_id = ty::MethodCall::autoderef(expr.id, i as u32);
match self.mc.infcx.node_method_ty(deref_id) {
None => {}
Some(method_ty) => {
let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
if let Some(method_ty) = self.mc.infcx.node_method_ty(deref_id) {
let cmt = return_if_err!(self.mc.cat_expr_autoderefd(expr, i));
// the method call infrastructure should have
// replaced all late-bound regions with variables:
let self_ty = method_ty.fn_sig().input(0);
let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
// the method call infrastructure should have
// replaced all late-bound regions with variables:
let self_ty = method_ty.fn_sig().input(0);
let self_ty = self.tcx().no_late_bound_regions(&self_ty).unwrap();
let (m, r) = match self_ty.sty {
ty::TyRef(r, ref m) => (m.mutbl, r),
_ => span_bug!(expr.span,
"bad overloaded deref type {:?}",
method_ty)
};
let bk = ty::BorrowKind::from_mutbl(m);
self.delegate.borrow(expr.id, expr.span, cmt,
*r, bk, AutoRef);
}
let (m, r) = match self_ty.sty {
ty::TyRef(r, ref m) => (m.mutbl, r),
_ => span_bug!(expr.span,
"bad overloaded deref type {:?}",
method_ty)
};
let bk = ty::BorrowKind::from_mutbl(m);
self.delegate.borrow(expr.id, expr.span, cmt,
*r, bk, AutoRef);
}
}
}

View File

@ -598,11 +598,8 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
fn arm_pats_bindings<F>(&mut self, pat: Option<&hir::Pat>, f: F) where
F: FnMut(&mut Liveness<'a, 'tcx>, LiveNode, Variable, Span, NodeId),
{
match pat {
Some(pat) => {
self.pat_bindings(pat, f);
}
None => {}
if let Some(pat) = pat {
self.pat_bindings(pat, f);
}
}

View File

@ -284,9 +284,8 @@ impl<'a, 'tcx, 'v> Visitor<'v> for LifetimeContext<'a, 'tcx> {
fn visit_generics(&mut self, generics: &hir::Generics) {
for ty_param in generics.ty_params.iter() {
walk_list!(self, visit_ty_param_bound, &ty_param.bounds);
match ty_param.default {
Some(ref ty) => self.visit_ty(&ty),
None => {}
if let Some(ref ty) = ty_param.default {
self.visit_ty(&ty);
}
}
for predicate in &generics.where_clause.predicates {

View File

@ -123,9 +123,8 @@ impl<'a> Context<'a> {
impl<'a, 'v> Visitor<'v> for Context<'a> {
fn visit_foreign_item(&mut self, i: &hir::ForeignItem) {
match lang_items::extract(&i.attrs) {
None => {}
Some(lang_item) => self.register(&lang_item, i.span),
if let Some(lang_item) = lang_items::extract(&i.attrs) {
self.register(&lang_item, i.span);
}
intravisit::walk_foreign_item(self, i)
}

View File

@ -250,15 +250,12 @@ impl Session {
msg: String) {
let lint_id = lint::LintId::of(lint);
let mut lints = self.lints.borrow_mut();
match lints.get_mut(&id) {
Some(arr) => {
let tuple = (lint_id, sp, msg);
if !arr.contains(&tuple) {
arr.push(tuple);
}
return;
if let Some(arr) = lints.get_mut(&id) {
let tuple = (lint_id, sp, msg);
if !arr.contains(&tuple) {
arr.push(tuple);
}
None => {}
return;
}
lints.insert(id, vec!((lint_id, sp, msg)));
}

View File

@ -168,13 +168,12 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
// which is incorrect. This value was computed based on the crutch
// value for the type contents of list. The correct value is
// TC::OwnsOwned. This manifested as issue #4821.
match cache.get(&ty) {
Some(tc) => { return *tc; }
None => {}
if let Some(tc) = cache.get(&ty) {
return *tc;
}
match tcx.tc_cache.borrow().get(&ty) { // Must check both caches!
Some(tc) => { return *tc; }
None => {}
// Must check both caches!
if let Some(tc) = tcx.tc_cache.borrow().get(&ty) {
return *tc;
}
cache.insert(ty, TC::None);

View File

@ -521,9 +521,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.0 }
fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
match self.tcx().normalized_cache.borrow().get(&ty).cloned() {
None => {}
Some(u) => return u
if let Some(u) = self.tcx().normalized_cache.borrow().get(&ty).cloned() {
return u;
}
// FIXME(eddyb) should local contexts have a cache too?
@ -714,4 +713,3 @@ impl<'tcx> TypeVisitor<'tcx> for LateBoundRegionsCollector {
false
}
}

View File

@ -712,16 +712,13 @@ impl<'a, 'tcx> ty::TyS<'tcx> {
// struct Foo;
// struct Bar<T> { x: Bar<Foo> }
match iter.next() {
Some(&seen_type) => {
if same_struct_or_enum(seen_type, def) {
debug!("SelfRecursive: {:?} contains {:?}",
seen_type,
ty);
return Representability::SelfRecursive;
}
if let Some(&seen_type) = iter.next() {
if same_struct_or_enum(seen_type, def) {
debug!("SelfRecursive: {:?} contains {:?}",
seen_type,
ty);
return Representability::SelfRecursive;
}
None => {}
}
// We also need to know whether the first item contains other types

View File

@ -274,11 +274,8 @@ impl<'a, 'tcx> MoveData<'tcx> {
/// `lp` and any of its base paths that do not yet have an index.
pub fn move_path(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
lp: Rc<LoanPath<'tcx>>) -> MovePathIndex {
match self.path_map.borrow().get(&lp) {
Some(&index) => {
return index;
}
None => {}
if let Some(&index) = self.path_map.borrow().get(&lp) {
return index;
}
let index = match lp.kind {

View File

@ -176,9 +176,8 @@ fn check_expr(cx: &mut MatchCheckCtxt, ex: &hir::Expr) {
// Second, if there is a guard on each arm, make sure it isn't
// assigning or borrowing anything mutably.
match arm.guard {
Some(ref guard) => check_for_mutation_in_guard(cx, &guard),
None => {}
if let Some(ref guard) = arm.guard {
check_for_mutation_in_guard(cx, &guard);
}
}

View File

@ -150,12 +150,9 @@ impl LateLintPass for UnusedResults {
if attr.check_name("must_use") {
let mut msg = "unused result which must be used".to_string();
// check for #[must_use="..."]
match attr.value_str() {
None => {}
Some(s) => {
msg.push_str(": ");
msg.push_str(&s);
}
if let Some(s) = attr.value_str() {
msg.push_str(": ");
msg.push_str(&s);
}
cx.span_lint(UNUSED_MUST_USE, sp, &msg);
return true;

View File

@ -24,19 +24,17 @@ fn main() {
let llvm_config = env::var_os("LLVM_CONFIG")
.map(PathBuf::from)
.unwrap_or_else(|| {
match env::var_os("CARGO_TARGET_DIR").map(PathBuf::from) {
Some(dir) => {
let to_test = dir.parent()
.unwrap()
.parent()
.unwrap()
.join(&target)
.join("llvm/bin/llvm-config");
if Command::new(&to_test).output().is_ok() {
return to_test;
}
if let Some(dir) = env::var_os("CARGO_TARGET_DIR")
.map(PathBuf::from) {
let to_test = dir.parent()
.unwrap()
.parent()
.unwrap()
.join(&target)
.join("llvm/bin/llvm-config");
if Command::new(&to_test).output().is_ok() {
return to_test;
}
None => {}
}
PathBuf::from("llvm-config")
});

View File

@ -682,15 +682,12 @@ fn each_child_of_item_or_crate<F, G>(intr: Rc<IdentInterner>,
};
// Get the item.
match crate_data.get_item(child_def_id.index) {
None => {}
Some(child_item_doc) => {
// Hand off the item to the callback.
let child_name = item_name(&intr, child_item_doc);
let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
let visibility = item_visibility(child_item_doc);
callback(def_like, child_name, visibility);
}
if let Some(child_item_doc) = crate_data.get_item(child_def_id.index) {
// Hand off the item to the callback.
let child_name = item_name(&intr, child_item_doc);
let def_like = item_to_def_like(crate_data, child_item_doc, child_def_id);
let visibility = item_visibility(child_item_doc);
callback(def_like, child_name, visibility);
}
}

View File

@ -503,19 +503,11 @@ impl<'a> Context<'a> {
self.crate_name);
err.note("candidates:");
for (_, lib) in libraries {
match lib.dylib {
Some((ref p, _)) => {
err.note(&format!("path: {}",
p.display()));
}
None => {}
if let Some((ref p, _)) = lib.dylib {
err.note(&format!("path: {}", p.display()));
}
match lib.rlib {
Some((ref p, _)) => {
err.note(&format!("path: {}",
p.display()));
}
None => {}
if let Some((ref p, _)) = lib.rlib {
err.note(&format!("path: {}", p.display()));
}
let data = lib.metadata.as_slice();
let name = decoder::get_crate_name(data);

View File

@ -396,16 +396,13 @@ impl<'a,'tcx> TyDecoder<'a,'tcx> {
let pos = self.parse_vuint();
let key = ty::CReaderCacheKey { cnum: self.krate, pos: pos };
match tcx.rcache.borrow().get(&key).cloned() {
Some(tt) => {
// If there is a closure buried in the type some where, then we
// need to re-convert any def ids (see case 'k', below). That means
// we can't reuse the cached version.
if !tt.has_closure_types() {
return tt;
}
if let Some(tt) = tcx.rcache.borrow().get(&key).cloned() {
// If there is a closure buried in the type some where, then we
// need to re-convert any def ids (see case 'k', below). That means
// we can't reuse the cached version.
if !tt.has_closure_types() {
return tt;
}
None => {}
}
let mut substate = TyDecoder::new(self.data,

View File

@ -64,9 +64,9 @@ pub struct ty_abbrev {
pub type abbrev_map<'tcx> = RefCell<FnvHashMap<Ty<'tcx>, ty_abbrev>>;
pub fn enc_ty<'a, 'tcx>(w: &mut Cursor<Vec<u8>>, cx: &ctxt<'a, 'tcx>, t: Ty<'tcx>) {
match cx.abbrevs.borrow_mut().get(&t) {
Some(a) => { w.write_all(&a.s); return; }
None => {}
if let Some(a) = cx.abbrevs.borrow_mut().get(&t) {
w.write_all(&a.s);
return;
}
let pos = w.position();

View File

@ -299,12 +299,10 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> {
let mut result = String::from("<");
result.push_str(&rustc::hir::print::ty_to_string(&ty));
match self.tcx.trait_of_item(self.tcx.map.local_def_id(id)) {
Some(def_id) => {
result.push_str(" as ");
result.push_str(&self.tcx.item_path_str(def_id));
}
None => {}
if let Some(def_id) = self.tcx
.trait_of_item(self.tcx.map.local_def_id(id)) {
result.push_str(" as ");
result.push_str(&self.tcx.item_path_str(def_id));
}
result.push_str(">");
result

View File

@ -1706,17 +1706,13 @@ pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
//
// In such cases, the more general path is unsafe, because
// it assumes it is matching against a valid value.
match simple_name(pat) {
Some(name) => {
let var_scope = cleanup::var_scope(tcx, local.id);
return mk_binding_alloca(
bcx, pat.id, name, var_scope, (),
"_match::store_local",
|(), bcx, Datum { val: v, .. }| expr::trans_into(bcx, &init_expr,
expr::SaveIn(v)));
}
None => {}
if let Some(name) = simple_name(pat) {
let var_scope = cleanup::var_scope(tcx, local.id);
return mk_binding_alloca(
bcx, pat.id, name, var_scope, (),
"_match::store_local",
|(), bcx, Datum { val: v, .. }| expr::trans_into(bcx, &init_expr,
expr::SaveIn(v)));
}
// General path.

View File

@ -191,9 +191,8 @@ pub fn represent_type<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
t: Ty<'tcx>)
-> Rc<Repr<'tcx>> {
debug!("Representing: {}", t);
match cx.adt_reprs().borrow().get(&t) {
Some(repr) => return repr.clone(),
None => {}
if let Some(repr) = cx.adt_reprs().borrow().get(&t) {
return repr.clone();
}
let repr = Rc::new(represent_type_uncached(cx, t));

View File

@ -136,11 +136,8 @@ pub struct _InsnCtxt {
impl Drop for _InsnCtxt {
fn drop(&mut self) {
TASK_LOCAL_INSN_KEY.with(|slot| {
match slot.borrow_mut().as_mut() {
Some(ctx) => {
ctx.pop();
}
None => {}
if let Some(ctx) = slot.borrow_mut().as_mut() {
ctx.pop();
}
})
}

View File

@ -138,18 +138,15 @@ pub fn addr_of(ccx: &CrateContext,
align: machine::llalign,
kind: &str)
-> ValueRef {
match ccx.const_globals().borrow().get(&cv) {
Some(&gv) => {
unsafe {
// Upgrade the alignment in cases where the same constant is used with different
// alignment requirements
if align > llvm::LLVMGetAlignment(gv) {
llvm::LLVMSetAlignment(gv, align);
}
if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
unsafe {
// Upgrade the alignment in cases where the same constant is used with different
// alignment requirements
if align > llvm::LLVMGetAlignment(gv) {
llvm::LLVMSetAlignment(gv, align);
}
return gv;
}
None => {}
return gv;
}
let gv = addr_of_mut(ccx, cv, align, kind);
unsafe {

View File

@ -572,11 +572,8 @@ impl<'bcx, 'tcx> MirContext<'bcx, 'tcx> {
// will only succeed if both operands are constant.
// This is necessary to determine when an overflow Assert
// will always panic at runtime, and produce a warning.
match const_scalar_checked_binop(bcx.tcx(), op, lhs, rhs, input_ty) {
Some((val, of)) => {
return OperandValue::Pair(val, C_bool(bcx.ccx(), of));
}
None => {}
if let Some((val, of)) = const_scalar_checked_binop(bcx.tcx(), op, lhs, rhs, input_ty) {
return OperandValue::Pair(val, C_bool(bcx.ccx(), of));
}
let (val, of) = match op {

View File

@ -864,9 +864,8 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
// THE ACTUAL SEARCH
fn pick(mut self) -> PickResult<'tcx> {
match self.pick_core() {
Some(r) => return r,
None => {}
if let Some(r) = self.pick_core() {
return r;
}
let static_candidates = mem::replace(&mut self.static_candidates, vec![]);
@ -929,9 +928,8 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
return None;
}
match self.pick_by_value_method(step) {
Some(result) => return Some(result),
None => {}
if let Some(result) = self.pick_by_value_method(step) {
return Some(result);
}
self.pick_autorefd_method(step)
@ -1003,12 +1001,10 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> {
let mut possibly_unsatisfied_predicates = Vec::new();
debug!("searching inherent candidates");
match self.consider_candidates(self_ty, &self.inherent_candidates,
&mut possibly_unsatisfied_predicates) {
None => {}
Some(pick) => {
return Some(pick);
}
if let Some(pick) = self.consider_candidates(self_ty,
&self.inherent_candidates,
&mut possibly_unsatisfied_predicates) {
return Some(pick);
}
debug!("searching extension candidates");

View File

@ -334,13 +334,8 @@ impl<'cx, 'gcx, 'tcx> WritebackCx<'cx, 'gcx, 'tcx> {
};
//NB(jroesch): We need to match twice to avoid a double borrow which would cause an ICE
match new_method {
Some(method) => {
self.tcx().tables.borrow_mut().method_map.insert(
method_call,
method);
}
None => {}
if let Some(method) = new_method {
self.tcx().tables.borrow_mut().method_map.insert(method_call, method);
}
}

View File

@ -174,12 +174,9 @@ impl<'a, 'gcx, 'tcx> CoherenceChecker<'a, 'gcx, 'tcx> {
}
fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
match self.inherent_impls.borrow().get(&base_def_id) {
Some(implementation_list) => {
implementation_list.borrow_mut().push(impl_def_id);
return;
}
None => {}
if let Some(implementation_list) = self.inherent_impls.borrow().get(&base_def_id) {
implementation_list.borrow_mut().push(impl_def_id);
return;
}
self.inherent_impls.borrow_mut().insert(

View File

@ -312,14 +312,13 @@ fn check_start_fn_ty(ccx: &CrateCtxt,
fn check_for_entry_fn(ccx: &CrateCtxt) {
let tcx = ccx.tcx;
let _task = tcx.dep_graph.in_task(DepNode::CheckEntryFn);
match *tcx.sess.entry_fn.borrow() {
Some((id, sp)) => match tcx.sess.entry_type.get() {
if let Some((id, sp)) = *tcx.sess.entry_fn.borrow() {
match tcx.sess.entry_type.get() {
Some(config::EntryMain) => check_main_fn_ty(ccx, id, sp),
Some(config::EntryStart) => check_start_fn_ty(ccx, id, sp),
Some(config::EntryNone) => {}
None => bug!("entry function without a type")
},
None => {}
}
}
}

View File

@ -131,9 +131,8 @@ impl fmt::Display for clean::Generics {
write!(f, ":&nbsp;{}", TyParamBounds(&tp.bounds))?;
}
match tp.default {
Some(ref ty) => { write!(f, "&nbsp;=&nbsp;{}", ty)?; },
None => {}
if let Some(ref ty) = tp.default {
write!(f, "&nbsp;=&nbsp;{}", ty)?;
};
}
}
@ -401,15 +400,12 @@ fn primitive_link(f: &mut fmt::Formatter,
}
(_, render::Unknown) => None,
};
match loc {
Some(root) => {
write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
root,
path.0.first().unwrap(),
prim.to_url_str())?;
needs_termination = true;
}
None => {}
if let Some(root) = loc {
write!(f, "<a class='primitive' href='{}{}/primitive.{}.html'>",
root,
path.0.first().unwrap(),
prim.to_url_str())?;
needs_termination = true;
}
}
None => {}

View File

@ -352,9 +352,8 @@ fn write_header(class: Option<&str>,
out: &mut Write)
-> io::Result<()> {
write!(out, "<pre ")?;
match id {
Some(id) => write!(out, "id='{}' ", id)?,
None => {}
if let Some(id) = id {
write!(out, "id='{}' ", id)?;
}
write!(out, "class='rust {}'>\n", class.unwrap_or(""))
}

View File

@ -589,19 +589,16 @@ fn build_index(krate: &clean::Crate, cache: &mut Cache) -> String {
// Attach all orphan methods to the type's definition if the type
// has since been learned.
for &(did, ref item) in orphan_methods {
match paths.get(&did) {
Some(&(ref fqp, _)) => {
search_index.push(IndexItem {
ty: shortty(item),
name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].join("::"),
desc: Escape(&shorter(item.doc_value())).to_string(),
parent: Some(did),
parent_idx: None,
search_type: get_index_search_type(&item),
});
},
None => {}
if let Some(&(ref fqp, _)) = paths.get(&did) {
search_index.push(IndexItem {
ty: shortty(item),
name: item.name.clone().unwrap(),
path: fqp[..fqp.len() - 1].join("::"),
desc: Escape(&shorter(item.doc_value())).to_string(),
parent: Some(did),
parent_idx: None,
search_type: get_index_search_type(&item),
});
}
}
@ -2093,15 +2090,12 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
<h2 id='implementors'>Implementors</h2>
<ul class='item-list' id='implementors-list'>
")?;
match cache.implementors.get(&it.def_id) {
Some(implementors) => {
for i in implementors {
write!(w, "<li><code>")?;
fmt_impl_for_trait_page(&i.impl_, w)?;
writeln!(w, "</code></li>")?;
}
if let Some(implementors) = cache.implementors.get(&it.def_id) {
for i in implementors {
write!(w, "<li><code>")?;
fmt_impl_for_trait_page(&i.impl_, w)?;
writeln!(w, "</code></li>")?;
}
None => {}
}
write!(w, "</ul>")?;
write!(w, r#"<script type="text/javascript" async

View File

@ -1764,9 +1764,8 @@ impl<T: Iterator<Item=char>> Parser<T> {
return self.parse_array(first);
}
ParseArrayComma => {
match self.parse_array_comma_or_end() {
Some(evt) => { return evt; }
None => {}
if let Some(evt) = self.parse_array_comma_or_end() {
return evt;
}
}
ParseObject(first) => {
@ -2583,9 +2582,8 @@ impl<'a, T: Encodable> fmt::Display for AsPrettyJson<'a, T> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let mut shim = FormatShim { inner: f };
let mut encoder = PrettyEncoder::new(&mut shim);
match self.indent {
Some(n) => encoder.set_indent(n),
None => {}
if let Some(n) = self.indent {
encoder.set_indent(n);
}
match self.inner.encode(&mut encoder) {
Ok(_) => Ok(()),

View File

@ -944,9 +944,8 @@ impl SyntaxEnv {
pub fn find(&self, k: Name) -> Option<Rc<SyntaxExtension>> {
for frame in self.chain.iter().rev() {
match frame.map.get(&k) {
Some(v) => return Some(v.clone()),
None => {}
if let Some(v) = frame.map.get(&k) {
return Some(v.clone());
}
}
None

View File

@ -225,12 +225,9 @@ pub fn tt_next_token(r: &mut TtReader) -> TokenAndSpan {
} else { /* repeat */
*r.repeat_idx.last_mut().unwrap() += 1;
r.stack.last_mut().unwrap().idx = 0;
match r.stack.last().unwrap().sep.clone() {
Some(tk) => {
r.cur_tok = tk; /* repeat same span, I guess */
return ret_val;
}
None => {}
if let Some(tk) = r.stack.last().unwrap().sep.clone() {
r.cur_tok = tk; // repeat same span, I guess
return ret_val;
}
}
}

View File

@ -160,12 +160,9 @@ impl<'a> Parser<'a> {
_ => None,
};
match nt_meta {
Some(meta) => {
self.bump();
return Ok(meta);
}
None => {}
if let Some(meta) = nt_meta {
self.bump();
return Ok(meta);
}
let lo = self.span.lo;

View File

@ -470,15 +470,12 @@ impl<'a> StringReader<'a> {
/// PRECONDITION: self.curr is not whitespace
/// Eats any kind of comment.
fn scan_comment(&mut self) -> Option<TokenAndSpan> {
match self.curr {
Some(c) => {
if c.is_whitespace() {
self.span_diagnostic.span_err(syntax_pos::mk_sp(self.last_pos, self.last_pos),
"called consume_any_line_comment, but there \
was whitespace");
}
if let Some(c) = self.curr {
if c.is_whitespace() {
self.span_diagnostic.span_err(syntax_pos::mk_sp(self.last_pos, self.last_pos),
"called consume_any_line_comment, but there \
was whitespace");
}
None => {}
}
if self.curr_is('/') {

View File

@ -2752,9 +2752,8 @@ impl<'a> Parser<'a> {
}
};
match parse_kleene_op(self)? {
Some(kleene_op) => return Ok((None, kleene_op)),
None => {}
if let Some(kleene_op) = parse_kleene_op(self)? {
return Ok((None, kleene_op));
}
let separator = self.bump_and_get();
@ -5691,15 +5690,12 @@ impl<'a> Parser<'a> {
}
_ => None
};
match nt_item {
Some(mut item) => {
self.bump();
let mut attrs = attrs;
mem::swap(&mut item.attrs, &mut attrs);
item.attrs.extend(attrs);
return Ok(Some(P(item)));
}
None => {}
if let Some(mut item) = nt_item {
self.bump();
let mut attrs = attrs;
mem::swap(&mut item.attrs, &mut attrs);
item.attrs.extend(attrs);
return Ok(Some(P(item)));
}
let lo = self.span.lo;

View File

@ -1264,13 +1264,10 @@ impl<'a> State<'a> {
_ => {}
}
match *opt_trait {
Some(ref t) => {
try!(self.print_trait_ref(t));
try!(space(&mut self.s));
try!(self.word_space("for"));
}
None => {}
if let Some(ref t) = *opt_trait {
try!(self.print_trait_ref(t));
try!(space(&mut self.s));
try!(self.word_space("for"));
}
try!(self.print_type(&ty));
@ -1470,11 +1467,8 @@ impl<'a> State<'a> {
try!(self.print_tt(tt_elt));
}
try!(word(&mut self.s, ")"));
match seq.separator {
Some(ref tk) => {
try!(word(&mut self.s, &token_to_string(tk)));
}
None => {},
if let Some(ref tk) = seq.separator {
try!(word(&mut self.s, &token_to_string(tk)));
}
match seq.op {
tokenstream::KleeneOp::ZeroOrMore => word(&mut self.s, "*"),

View File

@ -360,13 +360,10 @@ fn find_type_parameters(ty: &ast::Ty, ty_param_names: &[ast::Name], span: Span,
fn visit_ty(&mut self, ty: &ast::Ty) {
match ty.node {
ast::TyKind::Path(_, ref path) if !path.global => {
match path.segments.first() {
Some(segment) => {
if self.ty_param_names.contains(&segment.identifier.name) {
self.types.push(P(ty.clone()));
}
if let Some(segment) = path.segments.first() {
if self.ty_param_names.contains(&segment.identifier.name) {
self.types.push(P(ty.clone()));
}
None => {}
}
}
_ => {}

View File

@ -88,12 +88,9 @@ pub fn expand_env<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[tokenstream::Token
}
};
match exprs.next() {
None => {}
Some(_) => {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
if let Some(_) = exprs.next() {
cx.span_err(sp, "env! takes 1 or 2 arguments");
return DummyResult::expr(sp);
}
let e = match env::var(&var[..]) {

View File

@ -126,16 +126,13 @@ fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[tokenstream::TokenTree])
panictry!(p.expect(&token::Eq));
let e = panictry!(p.parse_expr());
match names.get(name) {
None => {}
Some(prev) => {
ecx.struct_span_err(e.span,
&format!("duplicate argument named `{}`",
name))
.span_note(prev.span, "previously here")
.emit();
continue
}
if let Some(prev) = names.get(name) {
ecx.struct_span_err(e.span,
&format!("duplicate argument named `{}`",
name))
.span_note(prev.span, "previously here")
.emit();
continue;
}
order.push(name.to_string());
names.insert(name.to_string(), e);
@ -665,13 +662,10 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
Some(piece) => {
if !parser.errors.is_empty() { break }
cx.verify_piece(&piece);
match cx.trans_piece(&piece) {
Some(piece) => {
let s = cx.trans_literal_string();
cx.str_pieces.push(s);
cx.pieces.push(piece);
}
None => {}
if let Some(piece) = cx.trans_piece(&piece) {
let s = cx.trans_literal_string();
cx.str_pieces.push(s);
cx.pieces.push(piece);
}
}
None => break

View File

@ -747,12 +747,9 @@ pub fn run_tests_console(opts: &TestOpts, tests: Vec<TestDescAndFn>) -> io::Resu
PadOnRight => t.desc.name.as_slice().len(),
}
}
match tests.iter().max_by_key(|t| len_if_padded(*t)) {
Some(t) => {
let n = t.desc.name.as_slice();
st.max_name_len = n.len();
}
None => {}
if let Some(t) = tests.iter().max_by_key(|t| len_if_padded(*t)) {
let n = t.desc.name.as_slice();
st.max_name_len = n.len();
}
run_tests(opts, tests, |x| callback(&x, &mut st))?;
return st.write_run_finish();