Skip to content

Add a lint for unnecessary parens on control flow statements. #11663

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 3 additions & 8 deletions src/compiletest/compiletest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,14 +140,9 @@ pub fn parse_config(args: ~[~str]) -> config {
adb_test_dir:
opt_str2(matches.opt_str("adb-test-dir")).to_str(),
adb_device_status:
if (opt_str2(matches.opt_str("target")) ==
~"arm-linux-androideabi") {
if (opt_str2(matches.opt_str("adb-test-dir")) !=
~"(none)" &&
opt_str2(matches.opt_str("adb-test-dir")) !=
~"") { true }
else { false }
} else { false },
"arm-linux-androideabi" == opt_str2(matches.opt_str("target")) &&
"(none)" != opt_str2(matches.opt_str("adb-test-dir")) &&
!opt_str2(matches.opt_str("adb-test-dir")).is_empty(),
test_shard: test::opt_shard(matches.opt_str("test-shard")),
verbose: matches.opt_present("verbose")
}
Expand Down
4 changes: 2 additions & 2 deletions src/compiletest/runtest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -532,9 +532,9 @@ fn check_expected_errors(expected_errors: ~[errors::ExpectedError],
if !found_flags[i] {
debug!("prefix={} ee.kind={} ee.msg={} line={}",
prefixes[i], ee.kind, ee.msg, line);
if (prefix_matches(line, prefixes[i]) &&
if prefix_matches(line, prefixes[i]) &&
line.contains(ee.kind) &&
line.contains(ee.msg)) {
line.contains(ee.msg) {
found_flags[i] = true;
was_expected = true;
break;
Expand Down
16 changes: 8 additions & 8 deletions src/libextra/ebml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1025,15 +1025,15 @@ mod bench {
pub fn vuint_at_A_aligned(bh: &mut BenchHarness) {
use std::vec;
let data = vec::from_fn(4*100, |i| {
match (i % 2) {
match i % 2 {
0 => 0x80u8,
_ => i as u8,
}
});
let mut sum = 0u;
bh.iter(|| {
let mut i = 0;
while (i < data.len()) {
while i < data.len() {
sum += reader::vuint_at(data, i).val;
i += 4;
}
Expand All @@ -1044,15 +1044,15 @@ mod bench {
pub fn vuint_at_A_unaligned(bh: &mut BenchHarness) {
use std::vec;
let data = vec::from_fn(4*100+1, |i| {
match (i % 2) {
match i % 2 {
1 => 0x80u8,
_ => i as u8
}
});
let mut sum = 0u;
bh.iter(|| {
let mut i = 1;
while (i < data.len()) {
while i < data.len() {
sum += reader::vuint_at(data, i).val;
i += 4;
}
Expand All @@ -1063,7 +1063,7 @@ mod bench {
pub fn vuint_at_D_aligned(bh: &mut BenchHarness) {
use std::vec;
let data = vec::from_fn(4*100, |i| {
match (i % 4) {
match i % 4 {
0 => 0x10u8,
3 => i as u8,
_ => 0u8
Expand All @@ -1072,7 +1072,7 @@ mod bench {
let mut sum = 0u;
bh.iter(|| {
let mut i = 0;
while (i < data.len()) {
while i < data.len() {
sum += reader::vuint_at(data, i).val;
i += 4;
}
Expand All @@ -1083,7 +1083,7 @@ mod bench {
pub fn vuint_at_D_unaligned(bh: &mut BenchHarness) {
use std::vec;
let data = vec::from_fn(4*100+1, |i| {
match (i % 4) {
match i % 4 {
1 => 0x10u8,
0 => i as u8,
_ => 0u8
Expand All @@ -1092,7 +1092,7 @@ mod bench {
let mut sum = 0u;
bh.iter(|| {
let mut i = 1;
while (i < data.len()) {
while i < data.len() {
sum += reader::vuint_at(data, i).val;
i += 4;
}
Expand Down
2 changes: 1 addition & 1 deletion src/libextra/enum_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ impl<E:CLike> Items<E> {

impl<E:CLike> Iterator<E> for Items<E> {
fn next(&mut self) -> Option<E> {
if (self.bits == 0) {
if self.bits == 0 {
return None;
}

Expand Down
4 changes: 2 additions & 2 deletions src/libextra/getopts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ impl Matches {

fn opt_val(&self, nm: &str) -> Option<Optval> {
let vals = self.opt_vals(nm);
if (vals.is_empty()) {
if vals.is_empty() {
None
} else {
Some(vals[0].clone())
Expand Down Expand Up @@ -797,7 +797,7 @@ pub mod groups {
let slice: || = || { cont = it(ss.slice(slice_start, last_end)) };

// if the limit is larger than the string, lower it to save cycles
if (lim >= fake_i) {
if lim >= fake_i {
lim = fake_i;
}

Expand Down
4 changes: 2 additions & 2 deletions src/libextra/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -929,7 +929,7 @@ impl<T : Iterator<char>> Parser<T> {
return self.error(~"EOF while parsing string");
}

if (escape) {
if escape {
match self.ch {
'"' => res.push_char('"'),
'\\' => res.push_char('\\'),
Expand Down Expand Up @@ -1360,7 +1360,7 @@ impl serialize::Decoder for Decoder {
/// Test if two json values are less than one another
impl Ord for Json {
fn lt(&self, other: &Json) -> bool {
match (*self) {
match *self {
Number(f0) => {
match *other {
Number(f1) => f0 < f1,
Expand Down
4 changes: 2 additions & 2 deletions src/libextra/num/bigint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,9 +561,9 @@ impl ToPrimitive for BigUint {
impl FromPrimitive for BigUint {
#[inline]
fn from_i64(n: i64) -> Option<BigUint> {
if (n > 0) {
if n > 0 {
FromPrimitive::from_u64(n as u64)
} else if (n == 0) {
} else if n == 0 {
Some(Zero::zero())
} else {
None
Expand Down
2 changes: 1 addition & 1 deletion src/libextra/terminfo/parser/compiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ pub fn parse(file: &mut io::Reader,

// Check magic number
let magic = file.read_le_u16();
if (magic != 0x011A) {
if magic != 0x011A {
return Err(format!("invalid magic number: expected {:x} but found {:x}",
0x011A, magic as uint));
}
Expand Down
6 changes: 3 additions & 3 deletions src/libextra/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -808,7 +808,7 @@ pub fn strptime(s: &str, format: &str) -> Result<Tm, ~str> {
/// Formats the time according to the format string.
pub fn strftime(format: &str, tm: &Tm) -> ~str {
fn days_in_year(year: int) -> i32 {
if ((year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0))) {
if (year % 4 == 0) && ((year % 100 != 0) || (year % 400 == 0)) {
366 /* Days in a leap year */
} else {
365 /* Days in a non-leap year */
Expand Down Expand Up @@ -838,14 +838,14 @@ pub fn strftime(format: &str, tm: &Tm) -> ~str {
let mut year: int = tm.tm_year as int + 1900;
let mut days: int = iso_week_days (tm.tm_yday, tm.tm_wday);

if (days < 0) {
if days < 0 {
/* This ISO week belongs to the previous year. */
year -= 1;
days = iso_week_days (tm.tm_yday + (days_in_year(year)), tm.tm_wday);
} else {
let d: int = iso_week_days (tm.tm_yday - (days_in_year(year)),
tm.tm_wday);
if (0 <= d) {
if 0 <= d {
/* This ISO week belongs to the next year. */
year += 1;
days = d;
Expand Down
8 changes: 4 additions & 4 deletions src/libextra/uuid.rs
Original file line number Diff line number Diff line change
Expand Up @@ -614,16 +614,16 @@ mod test {

// Test error reporting
let e = Uuid::parse_string("67e5504410b1426f9247bb680e5fe0c").unwrap_err();
assert!(match(e){ ErrorInvalidLength(n) => n==31, _ => false });
assert!(match e { ErrorInvalidLength(n) => n==31, _ => false });

let e = Uuid::parse_string("67e550X410b1426f9247bb680e5fe0cd").unwrap_err();
assert!(match(e){ ErrorInvalidCharacter(c, n) => c=='X' && n==6, _ => false });
assert!(match e { ErrorInvalidCharacter(c, n) => c=='X' && n==6, _ => false });

let e = Uuid::parse_string("67e550-4105b1426f9247bb680e5fe0c").unwrap_err();
assert!(match(e){ ErrorInvalidGroups(n) => n==2, _ => false });
assert!(match e { ErrorInvalidGroups(n) => n==2, _ => false });

let e = Uuid::parse_string("F9168C5E-CEB2-4faa-B6BF1-02BF39FA1E4").unwrap_err();
assert!(match(e){ ErrorInvalidGroupLength(g, n, e) => g==3 && n==5 && e==4, _ => false });
assert!(match e { ErrorInvalidGroupLength(g, n, e) => g==3 && n==5 && e==4, _ => false });
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion src/libgreen/sched.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1323,7 +1323,7 @@ mod test {
fn roundtrip(id: int, n_tasks: int,
p: &Port<(int, Chan<()>)>,
ch: &Chan<(int, Chan<()>)>) {
while (true) {
loop {
match p.recv() {
(1, end_chan) => {
debug!("{}\n", id);
Expand Down
4 changes: 2 additions & 2 deletions src/libnative/io/file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,11 +508,11 @@ pub fn readdir(p: &CString) -> IoResult<~[Path]> {

let dir_ptr = p.with_ref(|buf| opendir(buf));

if (dir_ptr as uint != 0) {
if dir_ptr as uint != 0 {
let mut paths = ~[];
debug!("os::list_dir -- opendir() SUCCESS");
let mut entry_ptr = readdir(dir_ptr);
while (entry_ptr as uint != 0) {
while entry_ptr as uint != 0 {
let cstr = CString::new(rust_list_dir_val(entry_ptr), false);
paths.push(Path::new(cstr));
entry_ptr = readdir(dir_ptr);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/metadata/encoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1956,7 +1956,7 @@ fn encode_metadata_inner(wr: &mut MemWriter, parms: EncodeParams, crate: &Crate)

ecx.stats.total_bytes.set(ebml_w.writer.tell());

if (tcx.sess.meta_stats()) {
if tcx.sess.meta_stats() {
for e in ebml_w.writer.get_ref().iter() {
if *e == 0 {
ecx.stats.zero_bytes.set(ecx.stats.zero_bytes.get() + 1);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/check_match.rs
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ fn check_exhaustive(cx: &MatchCheckCtxt, sp: Span, pats: ~[@Pat]) {
useful(ty, ref ctor) => {
match ty::get(ty).sty {
ty::ty_bool => {
match (*ctor) {
match *ctor {
val(const_bool(true)) => Some(@"true"),
val(const_bool(false)) => Some(@"false"),
_ => None
Expand Down
29 changes: 28 additions & 1 deletion src/librustc/middle/lint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub enum Lint {
NonCamelCaseTypes,
NonUppercaseStatics,
NonUppercasePatternStatics,
UnnecessaryParens,
TypeLimits,
TypeOverflow,
UnusedUnsafe,
Expand Down Expand Up @@ -162,7 +163,7 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[
("while_true",
LintSpec {
lint: WhileTrue,
desc: "suggest using loop { } instead of while(true) { }",
desc: "suggest using `loop { }` instead of `while true { }`",
default: warn
}),

Expand Down Expand Up @@ -201,6 +202,13 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[
default: warn
}),

("unnecessary_parens",
LintSpec {
lint: UnnecessaryParens,
desc: "`if`, `match`, `while` and `return` do not need parentheses",
default: warn
}),

("managed_heap_memory",
LintSpec {
lint: ManagedHeapMemory,
Expand Down Expand Up @@ -1080,6 +1088,24 @@ fn check_pat_non_uppercase_statics(cx: &Context, p: &ast::Pat) {
}
}

fn check_unnecessary_parens(cx: &Context, e: &ast::Expr) {
let (value, msg) = match e.node {
ast::ExprIf(cond, _, _) => (cond, "`if` condition"),
ast::ExprWhile(cond, _) => (cond, "`while` condition"),
ast::ExprMatch(head, _) => (head, "`match` head expression"),
ast::ExprRet(Some(value)) => (value, "`return` value"),
_ => return
};

match value.node {
ast::ExprParen(_) => {
cx.span_lint(UnnecessaryParens, value.span,
format!("unnecessary parentheses around {}", msg))
}
_ => {}
}
}

fn check_unused_unsafe(cx: &Context, e: &ast::Expr) {
match e.node {
// Don't warn about generated blocks, that'll just pollute the output.
Expand Down Expand Up @@ -1438,6 +1464,7 @@ impl<'a> Visitor<()> for Context<'a> {

check_while_true_expr(self, e);
check_stability(self, e);
check_unnecessary_parens(self, e);
check_unused_unsafe(self, e);
check_unsafe_block(self, e);
check_unnecessary_allocation(self, e);
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/resolve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1039,7 +1039,7 @@ impl Resolver {
let mut duplicate_type = NoError;
let ns = match duplicate_checking_mode {
ForbidDuplicateModules => {
if (child.get_module_if_available().is_some()) {
if child.get_module_if_available().is_some() {
duplicate_type = ModuleError;
}
Some(TypeNS)
Expand Down Expand Up @@ -1074,7 +1074,7 @@ impl Resolver {
}
OverwriteDuplicates => None
};
if (duplicate_type != NoError) {
if duplicate_type != NoError {
// Return an error here by looking up the namespace that
// had the duplicate.
let ns = ns.unwrap();
Expand Down
4 changes: 2 additions & 2 deletions src/librustc/middle/trans/adt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ pub fn trans_field_ptr(bcx: &Block, r: &Repr, val: ValueRef, discr: Disr,
}
NullablePointer{ nonnull: ref nonnull, nullfields: ref nullfields,
nndiscr, .. } => {
if (discr == nndiscr) {
if discr == nndiscr {
struct_field_ptr(bcx, nonnull, val, ix, false)
} else {
// The unit-like case might have a nonzero number of unit-like fields.
Expand Down Expand Up @@ -783,7 +783,7 @@ fn build_const_struct(ccx: &CrateContext, st: &Struct, vals: &[ValueRef])
/*bad*/as u64;
let target_offset = roundup(offset, type_align);
offset = roundup(offset, val_align);
if (offset != target_offset) {
if offset != target_offset {
cfields.push(padding(target_offset - offset));
offset = target_offset;
}
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/trans/base.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2156,7 +2156,7 @@ pub fn get_item_val(ccx: @CrateContext, id: ast::NodeId) -> ValueRef {
_ => fail!("get_item_val: weird result in table")
};

match (attr::first_attr_value_str_by_name(i.attrs, "link_section")) {
match attr::first_attr_value_str_by_name(i.attrs, "link_section") {
Some(sect) => unsafe {
sect.with_c_str(|buf| {
llvm::LLVMSetSection(v, buf);
Expand Down
3 changes: 1 addition & 2 deletions src/librustc/middle/trans/tvec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ pub fn iter_vec_raw<'r,
let fcx = bcx.fcx;

let vt = vec_types(bcx, vec_ty);
if (vt.llunit_alloc_size == 0) {
if vt.llunit_alloc_size == 0 {
// Special-case vectors with elements of size 0 so they don't go out of bounds (#9890)
iter_vec_loop(bcx, data_ptr, &vt, fill, f)
} else {
Expand Down Expand Up @@ -740,4 +740,3 @@ pub fn iter_vec_unboxed<'r,
let dataptr = get_dataptr(bcx, body_ptr);
return iter_vec_raw(bcx, dataptr, vec_ty, fill, f);
}

2 changes: 1 addition & 1 deletion src/librustc/middle/ty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2883,7 +2883,7 @@ pub fn adjust_ty(cx: ctxt,
AutoDerefRef(ref adj) => {
let mut adjusted_ty = unadjusted_ty;

if (!ty::type_is_error(adjusted_ty)) {
if !ty::type_is_error(adjusted_ty) {
for i in range(0, adj.autoderefs) {
match ty::deref(adjusted_ty, true) {
Some(mt) => { adjusted_ty = mt.ty; }
Expand Down
Loading