Negative case of `len()` -> `is_empty()`

`s/([^\(\s]+\.)len\(\) [(?:!=)>] 0/!$1is_empty()/g`
This commit is contained in:
Tamir Duberstein 2015-03-24 16:54:09 -07:00
parent 29ac04402d
commit 10f15e72e6
61 changed files with 142 additions and 142 deletions

View File

@ -368,7 +368,7 @@ pub fn make_metrics_test_closure(config: &Config, testfile: &Path) -> test::Test
fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> { fn extract_gdb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line { match full_version_line {
Some(ref full_version_line) Some(ref full_version_line)
if full_version_line.trim().len() > 0 => { if !full_version_line.trim().is_empty() => {
let full_version_line = full_version_line.trim(); let full_version_line = full_version_line.trim();
// used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)" // used to be a regex "(^|[^0-9])([0-9]\.[0-9])([^0-9]|$)"
@ -408,7 +408,7 @@ fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
match full_version_line { match full_version_line {
Some(ref full_version_line) Some(ref full_version_line)
if full_version_line.trim().len() > 0 => { if !full_version_line.trim().is_empty() => {
let full_version_line = full_version_line.trim(); let full_version_line = full_version_line.trim();
for (pos, l) in full_version_line.char_indices() { for (pos, l) in full_version_line.char_indices() {
@ -426,7 +426,7 @@ fn extract_lldb_version(full_version_line: Option<String>) -> Option<String> {
let vers = full_version_line[pos + 5..].chars().take_while(|c| { let vers = full_version_line[pos + 5..].chars().take_while(|c| {
c.is_digit(10) c.is_digit(10)
}).collect::<String>(); }).collect::<String>();
if vers.len() > 0 { return Some(vers) } if !vers.is_empty() { return Some(vers) }
} }
println!("Could not extract LLDB version from line '{}'", println!("Could not extract LLDB version from line '{}'",
full_version_line); full_version_line);

View File

@ -1225,7 +1225,7 @@ impl<K, V> Node<K, V> {
/// because we have one too many, and our parent now has one too few /// because we have one too many, and our parent now has one too few
fn split(&mut self) -> (K, V, Node<K, V>) { fn split(&mut self) -> (K, V, Node<K, V>) {
// Necessary for correctness, but in a private function // Necessary for correctness, but in a private function
debug_assert!(self.len() > 0); debug_assert!(!self.is_empty());
let mut right = if self.is_leaf() { let mut right = if self.is_leaf() {
Node::new_leaf(self.capacity()) Node::new_leaf(self.capacity())

View File

@ -227,7 +227,7 @@ impl CharExt for char {
#[inline] #[inline]
pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> { pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
// Marked #[inline] to allow llvm optimizing it away // Marked #[inline] to allow llvm optimizing it away
if code < MAX_ONE_B && dst.len() >= 1 { if code < MAX_ONE_B && !dst.is_empty() {
dst[0] = code as u8; dst[0] = code as u8;
Some(1) Some(1)
} else if code < MAX_TWO_B && dst.len() >= 2 { } else if code < MAX_TWO_B && dst.len() >= 2 {
@ -258,7 +258,7 @@ pub fn encode_utf8_raw(code: u32, dst: &mut [u8]) -> Option<usize> {
#[inline] #[inline]
pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> { pub fn encode_utf16_raw(mut ch: u32, dst: &mut [u16]) -> Option<usize> {
// Marked #[inline] to allow llvm optimizing it away // Marked #[inline] to allow llvm optimizing it away
if (ch & 0xFFFF) == ch && dst.len() >= 1 { if (ch & 0xFFFF) == ch && !dst.is_empty() {
// The BMP falls through (assuming non-surrogate, as it should) // The BMP falls through (assuming non-surrogate, as it should)
dst[0] = ch as u16; dst[0] = ch as u16;
Some(1) Some(1)

View File

@ -371,7 +371,7 @@ impl<'a> Parser<'a> {
None => { None => {
let tmp = self.cur.clone(); let tmp = self.cur.clone();
match self.word() { match self.word() {
word if word.len() > 0 => { word if !word.is_empty() => {
if self.consume('$') { if self.consume('$') {
CountIsName(word) CountIsName(word)
} else { } else {
@ -463,7 +463,7 @@ mod tests {
fn musterr(s: &str) { fn musterr(s: &str) {
let mut p = Parser::new(s); let mut p = Parser::new(s);
p.next(); p.next();
assert!(p.errors.len() != 0); assert!(!p.errors.is_empty());
} }
#[test] #[test]

View File

@ -804,7 +804,7 @@ fn format_option(opt: &OptGroup) -> String {
} }
// Use short_name is possible, but fallback to long_name. // Use short_name is possible, but fallback to long_name.
if opt.short_name.len() > 0 { if !opt.short_name.is_empty() {
line.push('-'); line.push('-');
line.push_str(&opt.short_name[..]); line.push_str(&opt.short_name[..]);
} else { } else {

View File

@ -469,7 +469,7 @@ fn each_auxiliary_node_id<F>(item: &ast::Item, callback: F) -> bool where
ast::ItemStruct(ref struct_def, _) => { ast::ItemStruct(ref struct_def, _) => {
// If this is a newtype struct, return the constructor. // If this is a newtype struct, return the constructor.
match struct_def.ctor_id { match struct_def.ctor_id {
Some(ctor_id) if struct_def.fields.len() > 0 && Some(ctor_id) if !struct_def.fields.is_empty() &&
struct_def.fields[0].node.kind.is_unnamed() => { struct_def.fields[0].node.kind.is_unnamed() => {
continue_ = callback(ctor_id); continue_ = callback(ctor_id);
} }

View File

@ -307,13 +307,13 @@ impl<'a> Context<'a> {
} }
pub fn report_load_errs(&mut self) { pub fn report_load_errs(&mut self) {
let message = if self.rejected_via_hash.len() > 0 { let message = if !self.rejected_via_hash.is_empty() {
format!("found possibly newer version of crate `{}`", format!("found possibly newer version of crate `{}`",
self.ident) self.ident)
} else if self.rejected_via_triple.len() > 0 { } else if !self.rejected_via_triple.is_empty() {
format!("couldn't find crate `{}` with expected target triple {}", format!("couldn't find crate `{}` with expected target triple {}",
self.ident, self.triple) self.ident, self.triple)
} else if self.rejected_via_kind.len() > 0 { } else if !self.rejected_via_kind.is_empty() {
format!("found staticlib `{}` instead of rlib or dylib", self.ident) format!("found staticlib `{}` instead of rlib or dylib", self.ident)
} else { } else {
format!("can't find crate for `{}`", self.ident) format!("can't find crate for `{}`", self.ident)
@ -325,7 +325,7 @@ impl<'a> Context<'a> {
}; };
self.sess.span_err(self.span, &message[..]); self.sess.span_err(self.span, &message[..]);
if self.rejected_via_triple.len() > 0 { if !self.rejected_via_triple.is_empty() {
let mismatches = self.rejected_via_triple.iter(); let mismatches = self.rejected_via_triple.iter();
for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() { for (i, &CrateMismatch{ ref path, ref got }) in mismatches.enumerate() {
self.sess.fileline_note(self.span, self.sess.fileline_note(self.span,
@ -333,7 +333,7 @@ impl<'a> Context<'a> {
self.ident, i+1, got, path.display())); self.ident, i+1, got, path.display()));
} }
} }
if self.rejected_via_hash.len() > 0 { if !self.rejected_via_hash.is_empty() {
self.sess.span_note(self.span, "perhaps this crate needs \ self.sess.span_note(self.span, "perhaps this crate needs \
to be recompiled?"); to be recompiled?");
let mismatches = self.rejected_via_hash.iter(); let mismatches = self.rejected_via_hash.iter();
@ -353,7 +353,7 @@ impl<'a> Context<'a> {
} }
} }
} }
if self.rejected_via_kind.len() > 0 { if !self.rejected_via_kind.is_empty() {
self.sess.fileline_help(self.span, "please recompile this crate using \ self.sess.fileline_help(self.span, "please recompile this crate using \
--crate-type lib"); --crate-type lib");
let mismatches = self.rejected_via_kind.iter(); let mismatches = self.rejected_via_kind.iter();

View File

@ -182,7 +182,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> {
fn mark_live_symbols(&mut self) { fn mark_live_symbols(&mut self) {
let mut scanned = HashSet::new(); let mut scanned = HashSet::new();
while self.worklist.len() > 0 { while !self.worklist.is_empty() {
let id = self.worklist.pop().unwrap(); let id = self.worklist.pop().unwrap();
if scanned.contains(&id) { if scanned.contains(&id) {
continue continue

View File

@ -966,7 +966,7 @@ impl<'a, 'tcx> Rebuilder<'a, 'tcx> {
fn pick_lifetime(&self, fn pick_lifetime(&self,
region_names: &HashSet<ast::Name>) region_names: &HashSet<ast::Name>)
-> (ast::Lifetime, FreshOrKept) { -> (ast::Lifetime, FreshOrKept) {
if region_names.len() > 0 { if !region_names.is_empty() {
// It's not necessary to convert the set of region names to a // It's not necessary to convert the set of region names to a
// vector of string and then sort them. However, it makes the // vector of string and then sort them. However, it makes the
// choice of lifetime name deterministic and thus easier to test. // choice of lifetime name deterministic and thus easier to test.

View File

@ -246,7 +246,7 @@ impl<'a, 'tcx> RegionVarBindings<'a, 'tcx> {
} }
fn in_snapshot(&self) -> bool { fn in_snapshot(&self) -> bool {
self.undo_log.borrow().len() > 0 !self.undo_log.borrow().is_empty()
} }
pub fn start_snapshot(&self) -> RegionSnapshot { pub fn start_snapshot(&self) -> RegionSnapshot {

View File

@ -1527,7 +1527,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {
// for nil return types, it is ok to not return a value expl. // for nil return types, it is ok to not return a value expl.
} else { } else {
let ends_with_stmt = match body.expr { let ends_with_stmt = match body.expr {
None if body.stmts.len() > 0 => None if !body.stmts.is_empty() =>
match body.stmts.first().unwrap().node { match body.stmts.first().unwrap().node {
ast::StmtSemi(ref e, _) => { ast::StmtSemi(ref e, _) => {
ty::expr_ty(self.ir.tcx, &**e) == t_ret ty::expr_ty(self.ir.tcx, &**e) == t_ret

View File

@ -227,7 +227,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
ref bounds, ref bounds,
ref bound_lifetimes, ref bound_lifetimes,
.. }) => { .. }) => {
if bound_lifetimes.len() > 0 { if !bound_lifetimes.is_empty() {
self.trait_ref_hack = true; self.trait_ref_hack = true;
let result = self.with(LateScope(bound_lifetimes, self.scope), let result = self.with(LateScope(bound_lifetimes, self.scope),
|old_scope, this| { |old_scope, this| {
@ -267,7 +267,7 @@ impl<'a, 'v> Visitor<'v> for LifetimeContext<'a> {
_modifier: &ast::TraitBoundModifier) { _modifier: &ast::TraitBoundModifier) {
debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref); debug!("visit_poly_trait_ref trait_ref={:?}", trait_ref);
if !self.trait_ref_hack || trait_ref.bound_lifetimes.len() > 0 { if !self.trait_ref_hack || !trait_ref.bound_lifetimes.is_empty() {
if self.trait_ref_hack { if self.trait_ref_hack {
println!("{:?}", trait_ref.span); println!("{:?}", trait_ref.span);
span_err!(self.sess, trait_ref.span, E0316, span_err!(self.sess, trait_ref.span, E0316,

View File

@ -3665,7 +3665,7 @@ pub fn type_contents<'tcx>(cx: &ctxt<'tcx>, ty: Ty<'tcx>) -> TypeContents {
res = res | TC::OwnsDtor; res = res | TC::OwnsDtor;
} }
if variants.len() != 0 { if !variants.is_empty() {
let repr_hints = lookup_repr_hints(cx, did); let repr_hints = lookup_repr_hints(cx, did);
if repr_hints.len() > 1 { if repr_hints.len() > 1 {
// this is an error later on, but this type isn't safe // this is an error later on, but this type isn't safe
@ -4654,7 +4654,7 @@ pub fn expr_kind(tcx: &ctxt, expr: &ast::Expr) -> ExprKind {
match resolve_expr(tcx, expr) { match resolve_expr(tcx, expr) {
def::DefVariant(tid, vid, _) => { def::DefVariant(tid, vid, _) => {
let variant_info = enum_variant_with_id(tcx, tid, vid); let variant_info = enum_variant_with_id(tcx, tid, vid);
if variant_info.args.len() > 0 { if !variant_info.args.is_empty() {
// N-ary variant. // N-ary variant.
RvalueDatumExpr RvalueDatumExpr
} else { } else {
@ -5259,7 +5259,7 @@ impl<'tcx> VariantInfo<'tcx> {
match ast_variant.node.kind { match ast_variant.node.kind {
ast::TupleVariantKind(ref args) => { ast::TupleVariantKind(ref args) => {
let arg_tys = if args.len() > 0 { let arg_tys = if !args.is_empty() {
// the regions in the argument types come from the // the regions in the argument types come from the
// enum def'n, and hence will all be early bound // enum def'n, and hence will all be early bound
ty::no_late_bound_regions(cx, &ty_fn_args(ctor_ty)).unwrap() ty::no_late_bound_regions(cx, &ty_fn_args(ctor_ty)).unwrap()
@ -5280,7 +5280,7 @@ impl<'tcx> VariantInfo<'tcx> {
ast::StructVariantKind(ref struct_def) => { ast::StructVariantKind(ref struct_def) => {
let fields: &[StructField] = &struct_def.fields; let fields: &[StructField] = &struct_def.fields;
assert!(fields.len() > 0); assert!(!fields.is_empty());
let arg_tys = struct_def.fields.iter() let arg_tys = struct_def.fields.iter()
.map(|field| node_id_to_type(cx, field.node.id)).collect(); .map(|field| node_id_to_type(cx, field.node.id)).collect();

View File

@ -544,7 +544,7 @@ pub fn super_relate_tys<'a,'tcx:'a,R>(relation: &mut R,
.map(|(a, b)| relation.relate(a, b)) .map(|(a, b)| relation.relate(a, b))
.collect::<Result<_, _>>()); .collect::<Result<_, _>>());
Ok(ty::mk_tup(tcx, ts)) Ok(ty::mk_tup(tcx, ts))
} else if as_.len() != 0 && bs.len() != 0 { } else if !(as_.is_empty() || bs.is_empty()) {
Err(ty::terr_tuple_size( Err(ty::terr_tuple_size(
expected_found(relation, &as_.len(), &bs.len()))) expected_found(relation, &as_.len(), &bs.len())))
} else { } else {

View File

@ -558,7 +558,7 @@ pub fn parameterized<'tcx,GG>(cx: &ctxt<'tcx>,
&strs[0][..] &strs[0][..]
}, },
tail) tail)
} else if strs.len() > 0 { } else if !strs.is_empty() {
format!("{}<{}>", base, strs.connect(", ")) format!("{}<{}>", base, strs.connect(", "))
} else { } else {
format!("{}", base) format!("{}", base)

View File

@ -50,7 +50,7 @@ impl TempDir {
let mut rng = thread_rng(); let mut rng = thread_rng();
for _ in 0..NUM_RETRIES { for _ in 0..NUM_RETRIES {
let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect(); let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect();
let leaf = if prefix.len() > 0 { let leaf = if !prefix.is_empty() {
format!("{}.{}", prefix, suffix) format!("{}.{}", prefix, suffix)
} else { } else {
// If we're given an empty string for a prefix, then creating a // If we're given an empty string for a prefix, then creating a

View File

@ -778,7 +778,7 @@ impl NonCamelCaseTypes {
// start with a non-lowercase letter rather than non-uppercase // start with a non-lowercase letter rather than non-uppercase
// ones (some scripts don't have a concept of upper/lowercase) // ones (some scripts don't have a concept of upper/lowercase)
ident.len() > 0 && !ident.char_at(0).is_lowercase() && !ident.contains('_') !ident.is_empty() && !ident.char_at(0).is_lowercase() && !ident.contains('_')
} }
fn to_camel_case(s: &str) -> String { fn to_camel_case(s: &str) -> String {
@ -1900,7 +1900,7 @@ impl LintPass for UnconditionalRecursion {
// doesn't return (e.g. calls a `-> !` function or `loop { /* // doesn't return (e.g. calls a `-> !` function or `loop { /*
// no break */ }`) shouldn't be linted unless it actually // no break */ }`) shouldn't be linted unless it actually
// recurs. // recurs.
if !reached_exit_without_self_call && self_call_spans.len() > 0 { if !reached_exit_without_self_call && !self_call_spans.is_empty() {
cx.span_lint(UNCONDITIONAL_RECURSION, sp, cx.span_lint(UNCONDITIONAL_RECURSION, sp,
"function cannot return without recurring"); "function cannot return without recurring");

View File

@ -1055,7 +1055,7 @@ impl<'a, 'tcx> SanePrivacyVisitor<'a, 'tcx> {
let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| { let check_inherited = |sp: Span, vis: ast::Visibility, note: &str| {
if vis != ast::Inherited { if vis != ast::Inherited {
tcx.sess.span_err(sp, "unnecessary visibility qualifier"); tcx.sess.span_err(sp, "unnecessary visibility qualifier");
if note.len() > 0 { if !note.is_empty() {
tcx.sess.span_note(sp, note); tcx.sess.span_note(sp, note);
} }
} }

View File

@ -3072,7 +3072,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
} }
} }
if values.len() > 0 && if !values.is_empty() &&
values[smallest] != usize::MAX && values[smallest] != usize::MAX &&
values[smallest] < name.len() + 2 && values[smallest] < name.len() + 2 &&
values[smallest] <= max_distance && values[smallest] <= max_distance &&
@ -3228,7 +3228,7 @@ impl<'a, 'tcx> Resolver<'a, 'tcx> {
format!("to call `{}::{}`", path_str, path_name) format!("to call `{}::{}`", path_str, path_name)
}; };
if msg.len() > 0 { if !msg.is_empty() {
msg = format!(". Did you mean {}?", msg) msg = format!(". Did you mean {}?", msg)
} }

View File

@ -269,7 +269,7 @@ pub fn sanitize(s: &str) -> String {
} }
// Underscore-qualify anything that didn't start as an ident. // Underscore-qualify anything that didn't start as an ident.
if result.len() > 0 && if !result.is_empty() &&
result.as_bytes()[0] != '_' as u8 && result.as_bytes()[0] != '_' as u8 &&
! (result.as_bytes()[0] as char).is_xid_start() { ! (result.as_bytes()[0] as char).is_xid_start() {
return format!("_{}", &result[..]); return format!("_{}", &result[..]);

View File

@ -1119,7 +1119,7 @@ impl<'l, 'tcx, 'v> Visitor<'v> for DxrVisitor<'l, 'tcx> {
let glob_map = glob_map.as_ref().unwrap(); let glob_map = glob_map.as_ref().unwrap();
if glob_map.contains_key(&item.id) { if glob_map.contains_key(&item.id) {
for n in glob_map.get(&item.id).unwrap() { for n in glob_map.get(&item.id).unwrap() {
if name_string.len() > 0 { if !name_string.is_empty() {
name_string.push_str(", "); name_string.push_str(", ");
} }
name_string.push_str(n.as_str()); name_string.push_str(n.as_str());

View File

@ -1112,7 +1112,7 @@ fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
let mut kind = NoBranch; let mut kind = NoBranch;
let mut test_val = val; let mut test_val = val;
debug!("test_val={}", bcx.val_to_string(test_val)); debug!("test_val={}", bcx.val_to_string(test_val));
if opts.len() > 0 { if !opts.is_empty() {
match opts[0] { match opts[0] {
ConstantValue(..) | ConstantRange(..) => { ConstantValue(..) | ConstantRange(..) => {
test_val = load_if_immediate(bcx, val, left_ty); test_val = load_if_immediate(bcx, val, left_ty);

View File

@ -2392,7 +2392,7 @@ pub fn get_item_val(ccx: &CrateContext, id: ast::NodeId) -> ValueRef {
ccx.sess().bug("struct variant kind unexpected in get_item_val") ccx.sess().bug("struct variant kind unexpected in get_item_val")
} }
}; };
assert!(args.len() != 0); assert!(!args.is_empty());
let ty = ty::node_id_to_type(ccx.tcx(), id); let ty = ty::node_id_to_type(ccx.tcx(), id);
let parent = ccx.tcx().map.get_parent(id); let parent = ccx.tcx().map.get_parent(id);
let enm = ccx.tcx().map.expect_item(parent); let enm = ccx.tcx().map.expect_item(parent);

View File

@ -184,7 +184,7 @@ fn trans<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, expr: &ast::Expr)
bcx.fcx.param_substs); bcx.fcx.param_substs);
// Nullary variants are not callable // Nullary variants are not callable
assert!(vinfo.args.len() > 0); assert!(!vinfo.args.is_empty());
Callee { Callee {
bcx: bcx, bcx: bcx,
@ -495,7 +495,7 @@ pub fn trans_fn_ref_with_substs<'a, 'tcx>(
match map_node { match map_node {
ast_map::NodeVariant(v) => match v.node.kind { ast_map::NodeVariant(v) => match v.node.kind {
ast::TupleVariantKind(ref args) => args.len() > 0, ast::TupleVariantKind(ref args) => !args.is_empty(),
_ => false _ => false
}, },
ast_map::NodeStructCtor(_) => true, ast_map::NodeStructCtor(_) => true,

View File

@ -781,7 +781,7 @@ fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
let vinfo = ty::enum_variant_with_id(cx.tcx(), let vinfo = ty::enum_variant_with_id(cx.tcx(),
enum_did, enum_did,
variant_did); variant_did);
if vinfo.args.len() > 0 { if !vinfo.args.is_empty() {
// N-ary variant. // N-ary variant.
expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
} else { } else {

View File

@ -532,7 +532,7 @@ impl<'tcx> TypeMap<'tcx> {
// Maybe check that there is no self type here. // Maybe check that there is no self type here.
let tps = substs.types.get_slice(subst::TypeSpace); let tps = substs.types.get_slice(subst::TypeSpace);
if tps.len() > 0 { if !tps.is_empty() {
output.push('<'); output.push('<');
for &type_parameter in tps { for &type_parameter in tps {
@ -1102,7 +1102,7 @@ pub fn get_cleanup_debug_loc_for_ast_node<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
if let Ok(code_snippet) = code_snippet { if let Ok(code_snippet) = code_snippet {
let bytes = code_snippet.as_bytes(); let bytes = code_snippet.as_bytes();
if bytes.len() > 0 && &bytes[bytes.len()-1..] == b"}" { if !bytes.is_empty() && &bytes[bytes.len()-1..] == b"}" {
cleanup_span = Span { cleanup_span = Span {
lo: node_span.hi - codemap::BytePos(1), lo: node_span.hi - codemap::BytePos(1),
hi: node_span.hi, hi: node_span.hi,
@ -3834,7 +3834,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
output.push_str("fn("); output.push_str("fn(");
let sig = ty::erase_late_bound_regions(cx.tcx(), sig); let sig = ty::erase_late_bound_regions(cx.tcx(), sig);
if sig.inputs.len() > 0 { if !sig.inputs.is_empty() {
for &parameter_type in &sig.inputs { for &parameter_type in &sig.inputs {
push_debuginfo_type_name(cx, parameter_type, true, output); push_debuginfo_type_name(cx, parameter_type, true, output);
output.push_str(", "); output.push_str(", ");
@ -3844,7 +3844,7 @@ fn push_debuginfo_type_name<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
} }
if sig.variadic { if sig.variadic {
if sig.inputs.len() > 0 { if !sig.inputs.is_empty() {
output.push_str(", ..."); output.push_str(", ...");
} else { } else {
output.push_str("..."); output.push_str("...");

View File

@ -1135,7 +1135,7 @@ fn trans_def_dps_unadjusted<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
match def { match def {
def::DefVariant(tid, vid, _) => { def::DefVariant(tid, vid, _) => {
let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid); let variant_info = ty::enum_variant_with_id(bcx.tcx(), tid, vid);
if variant_info.args.len() > 0 { if !variant_info.args.is_empty() {
// N-ary variant. // N-ary variant.
let llfn = callee::trans_fn_ref(bcx.ccx(), vid, let llfn = callee::trans_fn_ref(bcx.ccx(), vid,
ExprId(ref_expr.id), ExprId(ref_expr.id),

View File

@ -2025,7 +2025,7 @@ fn compute_object_lifetime_bound<'tcx>(
"only a single explicit lifetime bound is permitted"); "only a single explicit lifetime bound is permitted");
} }
if explicit_region_bounds.len() != 0 { if !explicit_region_bounds.is_empty() {
// Explicitly specified region bound. Use that. // Explicitly specified region bound. Use that.
let r = explicit_region_bounds[0]; let r = explicit_region_bounds[0];
return ast_region_to_region(tcx, r); return ast_region_to_region(tcx, r);
@ -2130,11 +2130,11 @@ pub fn partition_bounds<'a>(tcx: &ty::ctxt,
&mut builtin_bounds) { &mut builtin_bounds) {
let segments = &b.trait_ref.path.segments; let segments = &b.trait_ref.path.segments;
let parameters = &segments[segments.len() - 1].parameters; let parameters = &segments[segments.len() - 1].parameters;
if parameters.types().len() > 0 { if !parameters.types().is_empty() {
check_type_argument_count(tcx, b.trait_ref.path.span, check_type_argument_count(tcx, b.trait_ref.path.span,
parameters.types().len(), 0, 0); parameters.types().len(), 0, 0);
} }
if parameters.lifetimes().len() > 0 { if !parameters.lifetimes().is_empty() {
report_lifetime_number_error(tcx, b.trait_ref.path.span, report_lifetime_number_error(tcx, b.trait_ref.path.span,
parameters.lifetimes().len(), 0); parameters.lifetimes().len(), 0);
} }

View File

@ -67,7 +67,7 @@ pub fn report_error<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
} }
} }
if static_sources.len() > 0 { if !static_sources.is_empty() {
fcx.tcx().sess.fileline_note( fcx.tcx().sess.fileline_note(
span, span,
"found defined static methods, maybe a `self` is missing?"); "found defined static methods, maybe a `self` is missing?");
@ -200,7 +200,7 @@ fn suggest_traits_to_import<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
}) })
.collect::<Vec<_>>(); .collect::<Vec<_>>();
if candidates.len() > 0 { if !candidates.is_empty() {
// sort from most relevant to least relevant // sort from most relevant to least relevant
candidates.sort_by(|a, b| a.cmp(b).reverse()); candidates.sort_by(|a, b| a.cmp(b).reverse());
candidates.dedup(); candidates.dedup();

View File

@ -4258,7 +4258,7 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
// //
// The first step then is to categorize the segments appropriately. // The first step then is to categorize the segments appropriately.
assert!(segments.len() >= 1); assert!(!segments.is_empty());
let mut ufcs_method = None; let mut ufcs_method = None;
let mut segment_spaces: Vec<_>; let mut segment_spaces: Vec<_>;
@ -4480,7 +4480,7 @@ pub fn instantiate_path<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
} }
} }
if data.bindings.len() > 0 { if !data.bindings.is_empty() {
span_err!(fcx.tcx().sess, data.bindings[0].span, E0182, span_err!(fcx.tcx().sess, data.bindings[0].span, E0182,
"unexpected binding of associated item in expression path \ "unexpected binding of associated item in expression path \
(only allowed in type paths)"); (only allowed in type paths)");

View File

@ -174,7 +174,7 @@ impl<'ccx, 'tcx> CheckTypeWellFormedVisitor<'ccx, 'tcx> {
} }
// For DST, all intermediate types must be sized. // For DST, all intermediate types must be sized.
if variant.fields.len() > 0 { if !variant.fields.is_empty() {
for field in variant.fields.init() { for field in variant.fields.init() {
fcx.register_builtin_bound( fcx.register_builtin_bound(
field.ty, field.ty,
@ -658,7 +658,7 @@ fn enum_variants<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
enum_def.variants.iter() enum_def.variants.iter()
.map(|variant| { .map(|variant| {
match variant.node.kind { match variant.node.kind {
ast::TupleVariantKind(ref args) if args.len() > 0 => { ast::TupleVariantKind(ref args) if !args.is_empty() => {
let ctor_ty = ty::node_id_to_type(fcx.tcx(), variant.node.id); let ctor_ty = ty::node_id_to_type(fcx.tcx(), variant.node.id);
// the regions in the argument types come from the // the regions in the argument types come from the

View File

@ -576,7 +576,7 @@ fn get_enum_variant_types<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
// Nullary enum constructors get turned into constants; n-ary enum // Nullary enum constructors get turned into constants; n-ary enum
// constructors get turned into functions. // constructors get turned into functions.
let result_ty = match variant.node.kind { let result_ty = match variant.node.kind {
ast::TupleVariantKind(ref args) if args.len() > 0 => { ast::TupleVariantKind(ref args) if !args.is_empty() => {
let rs = ExplicitRscope; let rs = ExplicitRscope;
let input_tys: Vec<_> = args.iter().map(|va| icx.to_ty(&rs, &*va.ty)).collect(); let input_tys: Vec<_> = args.iter().map(|va| icx.to_ty(&rs, &*va.ty)).collect();
ty::mk_ctor_fn(tcx, variant_def_id, &input_tys, enum_scheme.ty) ty::mk_ctor_fn(tcx, variant_def_id, &input_tys, enum_scheme.ty)

View File

@ -712,7 +712,7 @@ impl<'tcx> Clean<Option<Vec<TyParamBound>>> for subst::Substs<'tcx> {
trait_: t.clean(cx), trait_: t.clean(cx),
lifetimes: vec![] lifetimes: vec![]
}, ast::TraitBoundModifier::None))); }, ast::TraitBoundModifier::None)));
if v.len() > 0 {Some(v)} else {None} if !v.is_empty() {Some(v)} else {None}
} }
} }

View File

@ -104,8 +104,8 @@ impl fmt::Display for clean::Generics {
try!(write!(f, "{}", *life)); try!(write!(f, "{}", *life));
} }
if self.type_params.len() > 0 { if !self.type_params.is_empty() {
if self.lifetimes.len() > 0 { if !self.lifetimes.is_empty() {
try!(f.write_str(", ")); try!(f.write_str(", "));
} }
for (i, tp) in self.type_params.iter().enumerate() { for (i, tp) in self.type_params.iter().enumerate() {
@ -114,7 +114,7 @@ impl fmt::Display for clean::Generics {
} }
try!(f.write_str(&tp.name)); try!(f.write_str(&tp.name));
if tp.bounds.len() > 0 { if !tp.bounds.is_empty() {
try!(write!(f, ": {}", TyParamBounds(&tp.bounds))); try!(write!(f, ": {}", TyParamBounds(&tp.bounds)));
} }
@ -175,7 +175,7 @@ impl fmt::Display for clean::Lifetime {
impl fmt::Display for clean::PolyTrait { impl fmt::Display for clean::PolyTrait {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
if self.lifetimes.len() > 0 { if !self.lifetimes.is_empty() {
try!(f.write_str("for&lt;")); try!(f.write_str("for&lt;"));
for (i, lt) in self.lifetimes.iter().enumerate() { for (i, lt) in self.lifetimes.iter().enumerate() {
if i > 0 { if i > 0 {
@ -212,7 +212,7 @@ impl fmt::Display for clean::PathParameters {
clean::PathParameters::AngleBracketed { clean::PathParameters::AngleBracketed {
ref lifetimes, ref types, ref bindings ref lifetimes, ref types, ref bindings
} => { } => {
if lifetimes.len() > 0 || types.len() > 0 || bindings.len() > 0 { if !lifetimes.is_empty() || !types.is_empty() || !bindings.is_empty() {
try!(f.write_str("&lt;")); try!(f.write_str("&lt;"));
let mut comma = false; let mut comma = false;
for lifetime in lifetimes { for lifetime in lifetimes {
@ -541,7 +541,7 @@ impl fmt::Display for clean::Arguments {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for (i, input) in self.values.iter().enumerate() { for (i, input) in self.values.iter().enumerate() {
if i > 0 { try!(write!(f, ", ")); } if i > 0 { try!(write!(f, ", ")); }
if input.name.len() > 0 { if !input.name.is_empty() {
try!(write!(f, "{}: ", input.name)); try!(write!(f, "{}: ", input.name));
} }
try!(write!(f, "{}", input.type_)); try!(write!(f, "{}", input.type_));
@ -585,8 +585,8 @@ impl<'a> fmt::Display for Method<'a> {
} }
} }
for (i, input) in d.inputs.values.iter().enumerate() { for (i, input) in d.inputs.values.iter().enumerate() {
if i > 0 || args.len() > 0 { args.push_str(", "); } if i > 0 || !args.is_empty() { args.push_str(", "); }
if input.name.len() > 0 { if !input.name.is_empty() {
args.push_str(&format!("{}: ", input.name)); args.push_str(&format!("{}: ", input.name));
} }
args.push_str(&format!("{}", input.type_)); args.push_str(&format!("{}", input.type_));
@ -734,7 +734,7 @@ impl<'a> fmt::Display for ConciseStability<'a> {
}; };
write!(f, "<a class='stability {lvl}' title='{lvl}{colon}{reason}'></a>", write!(f, "<a class='stability {lvl}' title='{lvl}{colon}{reason}'></a>",
lvl = Escape(&*lvl), lvl = Escape(&*lvl),
colon = if stability.reason.len() > 0 { ": " } else { "" }, colon = if !stability.reason.is_empty() { ": " } else { "" },
reason = Escape(&*stability.reason)) reason = Escape(&*stability.reason))
} }
None => { None => {

View File

@ -973,7 +973,7 @@ impl DocFolder for Cache {
// Keep track of the fully qualified path for this item. // Keep track of the fully qualified path for this item.
let pushed = if item.name.is_some() { let pushed = if item.name.is_some() {
let n = item.name.as_ref().unwrap(); let n = item.name.as_ref().unwrap();
if n.len() > 0 { if !n.is_empty() {
self.stack.push(n.to_string()); self.stack.push(n.to_string());
true true
} else { false } } else { false }
@ -1208,7 +1208,7 @@ impl Context {
let mut title = cx.current.connect("::"); let mut title = cx.current.connect("::");
if pushname { if pushname {
if title.len() > 0 { if !title.is_empty() {
title.push_str("::"); title.push_str("::");
} }
title.push_str(it.name.as_ref().unwrap()); title.push_str(it.name.as_ref().unwrap());
@ -1736,8 +1736,8 @@ fn item_function(w: &mut fmt::Formatter, it: &clean::Item,
fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item, fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
t: &clean::Trait) -> fmt::Result { t: &clean::Trait) -> fmt::Result {
let mut bounds = String::new(); let mut bounds = String::new();
if t.bounds.len() > 0 { if !t.bounds.is_empty() {
if bounds.len() > 0 { if !bounds.is_empty() {
bounds.push(' '); bounds.push(' ');
} }
bounds.push_str(": "); bounds.push_str(": ");
@ -1775,7 +1775,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
try!(render_method(w, t, MethodLink::Anchor)); try!(render_method(w, t, MethodLink::Anchor));
try!(write!(w, ";\n")); try!(write!(w, ";\n"));
} }
if types.len() > 0 && required.len() > 0 { if !types.is_empty() && !required.is_empty() {
try!(w.write_str("\n")); try!(w.write_str("\n"));
} }
for m in &required { for m in &required {
@ -1783,7 +1783,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
try!(render_method(w, m, MethodLink::Anchor)); try!(render_method(w, m, MethodLink::Anchor));
try!(write!(w, ";\n")); try!(write!(w, ";\n"));
} }
if required.len() > 0 && provided.len() > 0 { if !required.is_empty() && !provided.is_empty() {
try!(w.write_str("\n")); try!(w.write_str("\n"));
} }
for m in &provided { for m in &provided {
@ -1810,7 +1810,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
Ok(()) Ok(())
} }
if types.len() > 0 { if !types.is_empty() {
try!(write!(w, " try!(write!(w, "
<h2 id='associated-types'>Associated Types</h2> <h2 id='associated-types'>Associated Types</h2>
<div class='methods'> <div class='methods'>
@ -1822,7 +1822,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
} }
// Output the documentation for each function individually // Output the documentation for each function individually
if required.len() > 0 { if !required.is_empty() {
try!(write!(w, " try!(write!(w, "
<h2 id='required-methods'>Required Methods</h2> <h2 id='required-methods'>Required Methods</h2>
<div class='methods'> <div class='methods'>
@ -1832,7 +1832,7 @@ fn item_trait(w: &mut fmt::Formatter, cx: &Context, it: &clean::Item,
} }
try!(write!(w, "</div>")); try!(write!(w, "</div>"));
} }
if provided.len() > 0 { if !provided.is_empty() {
try!(write!(w, " try!(write!(w, "
<h2 id='provided-methods'>Provided Methods</h2> <h2 id='provided-methods'>Provided Methods</h2>
<div class='methods'> <div class='methods'>
@ -1882,7 +1882,7 @@ fn assoc_type(w: &mut fmt::Formatter, it: &clean::Item,
default: &Option<clean::Type>) default: &Option<clean::Type>)
-> fmt::Result { -> fmt::Result {
try!(write!(w, "type {}", it.name.as_ref().unwrap())); try!(write!(w, "type {}", it.name.as_ref().unwrap()));
if bounds.len() > 0 { if !bounds.is_empty() {
try!(write!(w, ": {}", TyParamBounds(bounds))) try!(write!(w, ": {}", TyParamBounds(bounds)))
} }
if let Some(ref default) = *default { if let Some(ref default) = *default {
@ -2031,7 +2031,7 @@ fn item_enum(w: &mut fmt::Formatter, it: &clean::Item,
try!(write!(w, "</pre>")); try!(write!(w, "</pre>"));
try!(document(w, it)); try!(document(w, it));
if e.variants.len() > 0 { if !e.variants.is_empty() {
try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>")); try!(write!(w, "<h2 class='variants'>Variants</h2>\n<table>"));
for variant in &e.variants { for variant in &e.variants {
try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>", try!(write!(w, "<tr><td id='variant.{name}'>{stab}<code>{name}</code></td><td>",
@ -2170,13 +2170,13 @@ fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
}; };
let (non_trait, traits): (Vec<_>, _) = v.into_iter() let (non_trait, traits): (Vec<_>, _) = v.into_iter()
.partition(|i| i.impl_.trait_.is_none()); .partition(|i| i.impl_.trait_.is_none());
if non_trait.len() > 0 { if !non_trait.is_empty() {
try!(write!(w, "<h2 id='methods'>Methods</h2>")); try!(write!(w, "<h2 id='methods'>Methods</h2>"));
for i in &non_trait { for i in &non_trait {
try!(render_impl(w, i, MethodLink::Anchor)); try!(render_impl(w, i, MethodLink::Anchor));
} }
} }
if traits.len() > 0 { if !traits.is_empty() {
try!(write!(w, "<h2 id='implementations'>Trait \ try!(write!(w, "<h2 id='implementations'>Trait \
Implementations</h2>")); Implementations</h2>"));
let (derived, manual): (Vec<_>, _) = traits.into_iter() let (derived, manual): (Vec<_>, _) = traits.into_iter()
@ -2185,7 +2185,7 @@ fn render_methods(w: &mut fmt::Formatter, it: &clean::Item) -> fmt::Result {
let did = i.trait_did().unwrap(); let did = i.trait_did().unwrap();
try!(render_impl(w, i, MethodLink::GotoSource(did))); try!(render_impl(w, i, MethodLink::GotoSource(did)));
} }
if derived.len() > 0 { if !derived.is_empty() {
try!(write!(w, "<h3 id='derived_implementations'>\ try!(write!(w, "<h3 id='derived_implementations'>\
Derived Implementations \ Derived Implementations \
</h3>")); </h3>"));

View File

@ -294,7 +294,7 @@ pub fn collapse_docs(krate: clean::Crate) -> plugins::PluginResult {
&clean::NameValue(ref x, _) if "doc" == *x => false, &clean::NameValue(ref x, _) if "doc" == *x => false,
_ => true _ => true
}).cloned().collect(); }).cloned().collect();
if docstr.len() > 0 { if !docstr.is_empty() {
a.push(clean::NameValue("doc".to_string(), docstr)); a.push(clean::NameValue("doc".to_string(), docstr));
} }
i.attrs = a; i.attrs = a;
@ -350,7 +350,7 @@ pub fn unindent(s: &str) -> String {
} }
}); });
if lines.len() >= 1 { if !lines.is_empty() {
let mut unindented = vec![ lines[0].trim().to_string() ]; let mut unindented = vec![ lines[0].trim().to_string() ];
unindented.push_all(&lines.tail().iter().map(|&line| { unindented.push_all(&lines.tail().iter().map(|&line| {
if line.chars().all(|c| c.is_whitespace()) { if line.chars().all(|c| c.is_whitespace()) {

View File

@ -349,7 +349,7 @@ pub trait Write {
/// This function will return the first error that `write` returns. /// This function will return the first error that `write` returns.
#[stable(feature = "rust1", since = "1.0.0")] #[stable(feature = "rust1", since = "1.0.0")]
fn write_all(&mut self, mut buf: &[u8]) -> Result<()> { fn write_all(&mut self, mut buf: &[u8]) -> Result<()> {
while buf.len() > 0 { while !buf.is_empty() {
match self.write(buf) { match self.write(buf) {
Ok(0) => return Err(Error::new(ErrorKind::WriteZero, Ok(0) => return Err(Error::new(ErrorKind::WriteZero,
"failed to write whole buffer")), "failed to write whole buffer")),

View File

@ -218,7 +218,7 @@ mod platform {
return Some(DeviceNS(u8_slice_as_os_str(slice))); return Some(DeviceNS(u8_slice_as_os_str(slice)));
} }
match parse_two_comps(path, is_sep_byte) { match parse_two_comps(path, is_sep_byte) {
Some((server, share)) if server.len() > 0 && share.len() > 0 => { Some((server, share)) if !server.is_empty() && !share.is_empty() => {
// \\server\share // \\server\share
return Some(UNC(u8_slice_as_os_str(server), return Some(UNC(u8_slice_as_os_str(server),
u8_slice_as_os_str(share))); u8_slice_as_os_str(share)));
@ -401,7 +401,7 @@ unsafe fn u8_slice_as_os_str(s: &[u8]) -> &OsStr {
/// Says whether the first byte after the prefix is a separator. /// Says whether the first byte after the prefix is a separator.
fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool { fn has_physical_root(s: &[u8], prefix: Option<Prefix>) -> bool {
let path = if let Some(p) = prefix { &s[p.len()..] } else { s }; let path = if let Some(p) = prefix { &s[p.len()..] } else { s };
path.len() > 0 && is_sep_byte(path[0]) !path.is_empty() && is_sep_byte(path[0])
} }
// basic workhorse for splitting stem and extension // basic workhorse for splitting stem and extension
@ -810,7 +810,7 @@ impl<'a> Iterator for Components<'a> {
State::StartDir => { State::StartDir => {
self.front = State::Body; self.front = State::Body;
if self.has_physical_root { if self.has_physical_root {
debug_assert!(self.path.len() > 0); debug_assert!(!self.path.is_empty());
self.path = &self.path[1..]; self.path = &self.path[1..];
return Some(Component::RootDir) return Some(Component::RootDir)
} else if let Some(p) = self.prefix { } else if let Some(p) = self.prefix {
@ -818,7 +818,7 @@ impl<'a> Iterator for Components<'a> {
return Some(Component::RootDir) return Some(Component::RootDir)
} }
} else if self.include_cur_dir() { } else if self.include_cur_dir() {
debug_assert!(self.path.len() > 0); debug_assert!(!self.path.is_empty());
self.path = &self.path[1..]; self.path = &self.path[1..];
return Some(Component::CurDir) return Some(Component::CurDir)
} }
@ -1055,7 +1055,7 @@ impl PathBuf {
}; };
let extension = extension.as_ref(); let extension = extension.as_ref();
if os_str_as_u8_slice(extension).len() > 0 { if !os_str_as_u8_slice(extension).is_empty() {
stem.push("."); stem.push(".");
stem.push(extension); stem.push(extension);
} }

View File

@ -51,7 +51,7 @@ impl<R: Read> Rng for ReaderRng<R> {
unsafe { *(bytes.as_ptr() as *const u64) } unsafe { *(bytes.as_ptr() as *const u64) }
} }
fn fill_bytes(&mut self, mut v: &mut [u8]) { fn fill_bytes(&mut self, mut v: &mut [u8]) {
while v.len() > 0 { while !v.is_empty() {
let t = v; let t = v;
match self.reader.read(t) { match self.reader.read(t) {
Ok(0) => panic!("ReaderRng.fill_bytes: EOF reached"), Ok(0) => panic!("ReaderRng.fill_bytes: EOF reached"),

View File

@ -76,7 +76,7 @@ pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> {
try!(writer.write_all(s.as_bytes())); try!(writer.write_all(s.as_bytes()));
} else { } else {
let mut first = true; let mut first = true;
while inner.len() > 0 { while !inner.is_empty() {
if !first { if !first {
try!(writer.write_all(b"::")); try!(writer.write_all(b"::"));
} else { } else {
@ -89,7 +89,7 @@ pub fn demangle(writer: &mut Write, s: &str) -> io::Result<()> {
let i: usize = inner[.. (inner.len() - rest.len())].parse().unwrap(); let i: usize = inner[.. (inner.len() - rest.len())].parse().unwrap();
inner = &rest[i..]; inner = &rest[i..];
rest = &rest[..i]; rest = &rest[..i];
while rest.len() > 0 { while !rest.is_empty() {
if rest.starts_with("$") { if rest.starts_with("$") {
macro_rules! demangle { macro_rules! demangle {
($($pat:expr, => $demangled:expr),*) => ({ ($($pat:expr, => $demangled:expr),*) => ({

View File

@ -429,14 +429,14 @@ pub struct Generics {
} }
impl Generics { impl Generics {
pub fn is_parameterized(&self) -> bool {
self.lifetimes.len() + self.ty_params.len() > 0
}
pub fn is_lt_parameterized(&self) -> bool { pub fn is_lt_parameterized(&self) -> bool {
self.lifetimes.len() > 0 !self.lifetimes.is_empty()
} }
pub fn is_type_parameterized(&self) -> bool { pub fn is_type_parameterized(&self) -> bool {
self.ty_params.len() > 0 !self.ty_params.is_empty()
}
pub fn is_parameterized(&self) -> bool {
self.is_lt_parameterized() || self.is_type_parameterized()
} }
} }

View File

@ -360,7 +360,7 @@ impl Encodable for FileMap {
// store the length // store the length
try! { s.emit_u32(lines.len() as u32) }; try! { s.emit_u32(lines.len() as u32) };
if lines.len() > 0 { if !lines.is_empty() {
// In order to preserve some space, we exploit the fact that // In order to preserve some space, we exploit the fact that
// the lines list is sorted and individual lines are // the lines list is sorted and individual lines are
// probably not that long. Because of that we can store lines // probably not that long. Because of that we can store lines
@ -569,7 +569,7 @@ impl CodeMap {
// accidentally overflowing into the next filemap in case the last byte // accidentally overflowing into the next filemap in case the last byte
// of span is also the last byte of filemap, which leads to incorrect // of span is also the last byte of filemap, which leads to incorrect
// results from CodeMap.span_to_*. // results from CodeMap.span_to_*.
if src.len() > 0 && !src.ends_with("\n") { if !src.is_empty() && !src.ends_with("\n") {
src.push('\n'); src.push('\n');
} }
@ -808,7 +808,7 @@ impl CodeMap {
loop { loop {
let lines = files[a].lines.borrow(); let lines = files[a].lines.borrow();
let lines = lines; let lines = lines;
if lines.len() > 0 { if !lines.is_empty() {
break; break;
} }
if a == 0 { if a == 0 {

View File

@ -90,7 +90,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
p.token != token::Colon && p.token != token::Colon &&
p.token != token::ModSep { p.token != token::ModSep {
if outputs.len() != 0 { if !outputs.is_empty() {
panictry!(p.eat(&token::Comma)); panictry!(p.eat(&token::Comma));
} }
@ -130,7 +130,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
p.token != token::Colon && p.token != token::Colon &&
p.token != token::ModSep { p.token != token::ModSep {
if inputs.len() != 0 { if !inputs.is_empty() {
panictry!(p.eat(&token::Comma)); panictry!(p.eat(&token::Comma));
} }
@ -154,7 +154,7 @@ pub fn expand_asm<'cx>(cx: &'cx mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
p.token != token::Colon && p.token != token::Colon &&
p.token != token::ModSep { p.token != token::ModSep {
if clobs.len() != 0 { if !clobs.is_empty() {
panictry!(p.eat(&token::Comma)); panictry!(p.eat(&token::Comma));
} }

View File

@ -774,7 +774,7 @@ pub fn check_zero_tts(cx: &ExtCtxt,
sp: Span, sp: Span,
tts: &[ast::TokenTree], tts: &[ast::TokenTree],
name: &str) { name: &str) {
if tts.len() != 0 { if !tts.is_empty() {
cx.span_err(sp, &format!("{} takes no arguments", name)); cx.span_err(sp, &format!("{} takes no arguments", name));
} }
} }

View File

@ -89,7 +89,7 @@ fn cs_clone(
} }
} }
if all_fields.len() >= 1 && all_fields[0].name.is_none() { if !all_fields.is_empty() && all_fields[0].name.is_none() {
// enum-like // enum-like
let subcalls = all_fields.iter().map(subcall).collect(); let subcalls = all_fields.iter().map(subcall).collect();
let path = cx.expr_path(ctor_path); let path = cx.expr_path(ctor_path);

View File

@ -240,7 +240,7 @@ fn encodable_substructure(cx: &mut ExtCtxt, trait_span: Span,
let encoder = cx.expr_ident(trait_span, blkarg); let encoder = cx.expr_ident(trait_span, blkarg);
let emit_variant_arg = cx.ident_of("emit_enum_variant_arg"); let emit_variant_arg = cx.ident_of("emit_enum_variant_arg");
let mut stmts = Vec::new(); let mut stmts = Vec::new();
if fields.len() > 0 { if !fields.is_empty() {
let last = fields.len() - 1; let last = fields.len() - 1;
for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() { for (i, &FieldInfo { ref self_, span, .. }) in fields.iter().enumerate() {
let enc = cx.expr_method_call(span, self_.clone(), let enc = cx.expr_method_call(span, self_.clone(),

View File

@ -912,7 +912,7 @@ impl<'a> MethodDef<'a> {
} }
// transpose raw_fields // transpose raw_fields
let fields = if raw_fields.len() > 0 { let fields = if !raw_fields.is_empty() {
let mut raw_fields = raw_fields.into_iter().map(|v| v.into_iter()); let mut raw_fields = raw_fields.into_iter().map(|v| v.into_iter());
let first_field = raw_fields.next().unwrap(); let first_field = raw_fields.next().unwrap();
let mut other_fields: Vec<vec::IntoIter<(Span, Option<Ident>, P<Expr>)>> let mut other_fields: Vec<vec::IntoIter<(Span, Option<Ident>, P<Expr>)>>

View File

@ -688,7 +688,7 @@ pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
loop { loop {
match parser.next() { match parser.next() {
Some(piece) => { Some(piece) => {
if parser.errors.len() > 0 { break } if !parser.errors.is_empty() { break }
cx.verify_piece(&piece); cx.verify_piece(&piece);
match cx.trans_piece(&piece) { match cx.trans_piece(&piece) {
Some(piece) => { Some(piece) => {

View File

@ -266,7 +266,7 @@ pub fn outer_mark(ctxt: SyntaxContext) -> Mrk {
/// Push a name... unless it matches the one on top, in which /// Push a name... unless it matches the one on top, in which
/// case pop and discard (so two of the same marks cancel) /// case pop and discard (so two of the same marks cancel)
fn xor_push(marks: &mut Vec<Mrk>, mark: Mrk) { fn xor_push(marks: &mut Vec<Mrk>, mark: Mrk) {
if (marks.len() > 0) && (*marks.last().unwrap() == mark) { if (!marks.is_empty()) && (*marks.last().unwrap() == mark) {
marks.pop().unwrap(); marks.pop().unwrap();
} else { } else {
marks.push(mark); marks.push(mark);

View File

@ -457,7 +457,7 @@ pub fn parse(sess: &ParseSess,
return Failure(sp, "unexpected end of macro invocation".to_string()); return Failure(sp, "unexpected end of macro invocation".to_string());
} }
} else { } else {
if (bb_eis.len() > 0 && next_eis.len() > 0) if (!bb_eis.is_empty() && !next_eis.is_empty())
|| bb_eis.len() > 1 { || bb_eis.len() > 1 {
let nts = bb_eis.iter().map(|ei| { let nts = bb_eis.iter().map(|ei| {
match ei.top_elts.get_tt(ei.idx) { match ei.top_elts.get_tt(ei.idx) {
@ -475,9 +475,9 @@ pub fn parse(sess: &ParseSess,
} else if bb_eis.is_empty() && next_eis.is_empty() { } else if bb_eis.is_empty() && next_eis.is_empty() {
return Failure(sp, format!("no rules expected the token `{}`", return Failure(sp, format!("no rules expected the token `{}`",
pprust::token_to_string(&tok)).to_string()); pprust::token_to_string(&tok)).to_string());
} else if next_eis.len() > 0 { } else if !next_eis.is_empty() {
/* Now process the next token */ /* Now process the next token */
while next_eis.len() > 0 { while !next_eis.is_empty() {
cur_eis.push(next_eis.pop().unwrap()); cur_eis.push(next_eis.pop().unwrap());
} }
rdr.next_token(); rdr.next_token();
@ -504,7 +504,7 @@ pub fn parse(sess: &ParseSess,
} }
} }
assert!(cur_eis.len() > 0); assert!(!cur_eis.is_empty());
} }
} }

View File

@ -63,7 +63,7 @@ pub fn strip_doc_comment_decoration(comment: &str) -> String {
let mut i = 0; let mut i = 0;
let mut j = lines.len(); let mut j = lines.len();
// first line of all-stars should be omitted // first line of all-stars should be omitted
if lines.len() > 0 && if !lines.is_empty() &&
lines[0].chars().all(|c| c == '*') { lines[0].chars().all(|c| c == '*') {
i += 1; i += 1;
} }
@ -294,7 +294,7 @@ fn read_block_comment(rdr: &mut StringReader,
} }
} }
} }
if curr_line.len() != 0 { if !curr_line.is_empty() {
trim_whitespace_prefix_and_push_line(&mut lines, trim_whitespace_prefix_and_push_line(&mut lines,
curr_line, curr_line,
col); col);

View File

@ -2254,7 +2254,7 @@ impl<'a> Parser<'a> {
(Vec::new(), Vec::new(), Vec::new()) (Vec::new(), Vec::new(), Vec::new())
}; };
if bindings.len() > 0 { if !bindings.is_empty() {
let last_span = self.last_span; let last_span = self.last_span;
self.span_err(last_span, "type bindings are only permitted on trait paths"); self.span_err(last_span, "type bindings are only permitted on trait paths");
} }
@ -3024,7 +3024,7 @@ impl<'a> Parser<'a> {
try!(self.expect(&token::Comma)); try!(self.expect(&token::Comma));
if self.token == token::CloseDelim(token::Bracket) if self.token == token::CloseDelim(token::Bracket)
&& (before_slice || after.len() != 0) { && (before_slice || !after.is_empty()) {
break break
} }
} }

View File

@ -565,7 +565,7 @@ impl<'a> Printer<'a> {
Token::End => { Token::End => {
debug!("print End -> pop End"); debug!("print End -> pop End");
let print_stack = &mut self.print_stack; let print_stack = &mut self.print_stack;
assert!((print_stack.len() != 0)); assert!((!print_stack.is_empty()));
print_stack.pop().unwrap(); print_stack.pop().unwrap();
Ok(()) Ok(())
} }

View File

@ -1656,7 +1656,7 @@ impl<'a> State<'a> {
try!(self.print_expr(&*args[0])); try!(self.print_expr(&*args[0]));
try!(word(&mut self.s, ".")); try!(word(&mut self.s, "."));
try!(self.print_ident(ident.node)); try!(self.print_ident(ident.node));
if tys.len() > 0 { if !tys.is_empty() {
try!(word(&mut self.s, "::<")); try!(word(&mut self.s, "::<"));
try!(self.commasep(Inconsistent, tys, try!(self.commasep(Inconsistent, tys,
|s, ty| s.print_type(&**ty))); |s, ty| s.print_type(&**ty)));
@ -1956,7 +1956,7 @@ impl<'a> State<'a> {
options.push("intel"); options.push("intel");
} }
if options.len() > 0 { if !options.is_empty() {
try!(space(&mut self.s)); try!(space(&mut self.s));
try!(self.word_space(":")); try!(self.word_space(":"));
try!(self.commasep(Inconsistent, &*options, try!(self.commasep(Inconsistent, &*options,
@ -2214,7 +2214,7 @@ impl<'a> State<'a> {
}, },
|f| f.node.pat.span)); |f| f.node.pat.span));
if etc { if etc {
if fields.len() != 0 { try!(self.word_space(",")); } if !fields.is_empty() { try!(self.word_space(",")); }
try!(word(&mut self.s, "..")); try!(word(&mut self.s, ".."));
} }
try!(space(&mut self.s)); try!(space(&mut self.s));
@ -2727,7 +2727,7 @@ impl<'a> State<'a> {
opt_explicit_self: Option<&ast::ExplicitSelf_>) opt_explicit_self: Option<&ast::ExplicitSelf_>)
-> io::Result<()> { -> io::Result<()> {
try!(self.ibox(indent_unit)); try!(self.ibox(indent_unit));
if generics.lifetimes.len() > 0 || generics.ty_params.len() > 0 { if !generics.lifetimes.is_empty() || !generics.ty_params.is_empty() {
try!(word(&mut self.s, "for")); try!(word(&mut self.s, "for"));
try!(self.print_generics(generics)); try!(self.print_generics(generics));
} }

View File

@ -123,7 +123,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
Percent => { Percent => {
match cur { match cur {
'%' => { output.push(c); state = Nothing }, '%' => { output.push(c); state = Nothing },
'c' => if stack.len() > 0 { 'c' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
// if c is 0, use 0200 (128) for ncurses compatibility // if c is 0, use 0200 (128) for ncurses compatibility
Number(c) => { Number(c) => {
@ -141,7 +141,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
'g' => state = GetVar, 'g' => state = GetVar,
'\'' => state = CharConstant, '\'' => state = CharConstant,
'{' => state = IntConstant(0), '{' => state = IntConstant(0),
'l' => if stack.len() > 0 { 'l' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Words(s) => stack.push(Number(s.len() as isize)), Words(s) => stack.push(Number(s.len() as isize)),
_ => return Err("a non-str was used with %l".to_string()) _ => return Err("a non-str was used with %l".to_string())
@ -231,14 +231,14 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
_ => return Err("non-numbers on stack with logical or".to_string()) _ => return Err("non-numbers on stack with logical or".to_string())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_string()) },
'!' => if stack.len() > 0 { '!' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Number(0) => stack.push(Number(1)), Number(0) => stack.push(Number(1)),
Number(_) => stack.push(Number(0)), Number(_) => stack.push(Number(0)),
_ => return Err("non-number on stack with logical not".to_string()) _ => return Err("non-number on stack with logical not".to_string())
} }
} else { return Err("stack is empty".to_string()) }, } else { return Err("stack is empty".to_string()) },
'~' => if stack.len() > 0 { '~' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Number(x) => stack.push(Number(!x)), Number(x) => stack.push(Number(!x)),
_ => return Err("non-number on stack with %~".to_string()) _ => return Err("non-number on stack with %~".to_string())
@ -253,7 +253,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
}, },
// printf-style support for %doxXs // printf-style support for %doxXs
'd'|'o'|'x'|'X'|'s' => if stack.len() > 0 { 'd'|'o'|'x'|'X'|'s' => if !stack.is_empty() {
let flags = Flags::new(); let flags = Flags::new();
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags); let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), flags);
if res.is_err() { return res } if res.is_err() { return res }
@ -278,7 +278,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
// conditionals // conditionals
'?' => (), '?' => (),
't' => if stack.len() > 0 { 't' => if !stack.is_empty() {
match stack.pop().unwrap() { match stack.pop().unwrap() {
Number(0) => state = SeekIfElse(0), Number(0) => state = SeekIfElse(0),
Number(_) => (), Number(_) => (),
@ -303,12 +303,12 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
}, },
SetVar => { SetVar => {
if cur >= 'A' && cur <= 'Z' { if cur >= 'A' && cur <= 'Z' {
if stack.len() > 0 { if !stack.is_empty() {
let idx = (cur as u8) - b'A'; let idx = (cur as u8) - b'A';
vars.sta[idx as usize] = stack.pop().unwrap(); vars.sta[idx as usize] = stack.pop().unwrap();
} else { return Err("stack is empty".to_string()) } } else { return Err("stack is empty".to_string()) }
} else if cur >= 'a' && cur <= 'z' { } else if cur >= 'a' && cur <= 'z' {
if stack.len() > 0 { if !stack.is_empty() {
let idx = (cur as u8) - b'a'; let idx = (cur as u8) - b'a';
vars.dyn[idx as usize] = stack.pop().unwrap(); vars.dyn[idx as usize] = stack.pop().unwrap();
} else { return Err("stack is empty".to_string()) } } else { return Err("stack is empty".to_string()) }
@ -352,7 +352,7 @@ pub fn expand(cap: &[u8], params: &[Param], vars: &mut Variables)
FormatPattern(ref mut flags, ref mut fstate) => { FormatPattern(ref mut flags, ref mut fstate) => {
old_state = Nothing; old_state = Nothing;
match (*fstate, cur) { match (*fstate, cur) {
(_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if stack.len() > 0 { (_,'d')|(_,'o')|(_,'x')|(_,'X')|(_,'s') => if !stack.is_empty() {
let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), *flags); let res = format(stack.pop().unwrap(), FormatOp::from_char(cur), *flags);
if res.is_err() { return res } if res.is_err() { return res }
output.push_all(&res.unwrap()); output.push_all(&res.unwrap());

View File

@ -373,7 +373,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
if matches.opt_present("h") { usage(&args[0]); return None; } if matches.opt_present("h") { usage(&args[0]); return None; }
let filter = if matches.free.len() > 0 { let filter = if !matches.free.is_empty() {
Some(matches.free[0].clone()) Some(matches.free[0].clone())
} else { } else {
None None
@ -588,14 +588,14 @@ impl<T: Write> ConsoleTestState<T> {
let mut fail_out = String::new(); let mut fail_out = String::new();
for &(ref f, ref stdout) in &self.failures { for &(ref f, ref stdout) in &self.failures {
failures.push(f.name.to_string()); failures.push(f.name.to_string());
if stdout.len() > 0 { if !stdout.is_empty() {
fail_out.push_str(&format!("---- {} stdout ----\n\t", f.name)); fail_out.push_str(&format!("---- {} stdout ----\n\t", f.name));
let output = String::from_utf8_lossy(stdout); let output = String::from_utf8_lossy(stdout);
fail_out.push_str(&output); fail_out.push_str(&output);
fail_out.push_str("\n"); fail_out.push_str("\n");
} }
} }
if fail_out.len() > 0 { if !fail_out.is_empty() {
try!(self.write_plain("\n")); try!(self.write_plain("\n"));
try!(self.write_plain(&fail_out)); try!(self.write_plain(&fail_out));
} }

View File

@ -196,17 +196,17 @@ impl<T: Float + FromPrimitive> Stats<T> for [T] {
} }
fn min(&self) -> T { fn min(&self) -> T {
assert!(self.len() != 0); assert!(!self.is_empty());
self.iter().fold(self[0], |p, q| p.min(*q)) self.iter().fold(self[0], |p, q| p.min(*q))
} }
fn max(&self) -> T { fn max(&self) -> T {
assert!(self.len() != 0); assert!(!self.is_empty());
self.iter().fold(self[0], |p, q| p.max(*q)) self.iter().fold(self[0], |p, q| p.max(*q))
} }
fn mean(&self) -> T { fn mean(&self) -> T {
assert!(self.len() != 0); assert!(!self.is_empty());
self.sum() / FromPrimitive::from_usize(self.len()).unwrap() self.sum() / FromPrimitive::from_usize(self.len()).unwrap()
} }
@ -284,7 +284,7 @@ impl<T: Float + FromPrimitive> Stats<T> for [T] {
// linear interpolation. If samples are not sorted, return nonsensical value. // linear interpolation. If samples are not sorted, return nonsensical value.
fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T], fn percentile_of_sorted<T: Float + FromPrimitive>(sorted_samples: &[T],
pct: T) -> T { pct: T) -> T {
assert!(sorted_samples.len() != 0); assert!(!sorted_samples.is_empty());
if sorted_samples.len() == 1 { if sorted_samples.len() == 1 {
return sorted_samples[0]; return sorted_samples[0];
} }

View File

@ -43,7 +43,7 @@ fn maybe_run_test<F>(argv: &[String], name: String, test: F) where F: FnOnce() {
if env::var_os("RUST_BENCH").is_some() { if env::var_os("RUST_BENCH").is_some() {
run_test = true run_test = true
} else if argv.len() > 0 { } else if !argv.is_empty() {
run_test = argv.iter().any(|x| x == &"all".to_string()) || argv.iter().any(|x| x == &name) run_test = argv.iter().any(|x| x == &"all".to_string()) || argv.iter().any(|x| x == &name)
} }
@ -60,7 +60,7 @@ fn shift_push() {
let mut v1 = repeat(1).take(30000).collect::<Vec<_>>(); let mut v1 = repeat(1).take(30000).collect::<Vec<_>>();
let mut v2 = Vec::new(); let mut v2 = Vec::new();
while v1.len() > 0 { while !v1.is_empty() {
v2.push(v1.remove(0)); v2.push(v1.remove(0));
} }
} }

View File

@ -252,7 +252,7 @@ fn generate_frequencies(mut input: &[u8], frame: usize) -> Table {
} }
frequencies.lookup(code, BumpCallback); frequencies.lookup(code, BumpCallback);
while input.len() != 0 && input[0] != ('>' as u8) { while !input.is_empty() && input[0] != ('>' as u8) {
code = code.rotate(input[0], frame); code = code.rotate(input[0], frame);
frequencies.lookup(code, BumpCallback); frequencies.lookup(code, BumpCallback);
input = &input[1..]; input = &input[1..];

View File

@ -30,7 +30,7 @@ fn main() {
let middle = XYZ{x: 0, y: 0, z: 0}; let middle = XYZ{x: 0, y: 0, z: 0};
border.insert(middle); border.insert(middle);
while border.len() > 0 && connected.len() < 10000 { while !border.is_empty() && connected.len() < 10000 {
let choice = *(border.iter().next().unwrap()); let choice = *(border.iter().next().unwrap());
border.remove(&choice); border.remove(&choice);
connected.insert(choice); connected.insert(choice);

View File

@ -44,5 +44,5 @@ pub fn main()
"foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string(), "foo".to_string(),
"foo".to_string()); "foo".to_string());
let v = format!("{:?}", u); // this is the line that causes the seg fault let v = format!("{:?}", u); // this is the line that causes the seg fault
assert!(v.len() > 0); assert!(!v.is_empty());
} }