From 67f9569bce2204e96b1ef763e5d8e9777ff4167b Mon Sep 17 00:00:00 2001 From: Florian Hahn Date: Sun, 22 Dec 2013 00:07:21 +0100 Subject: [PATCH 1/3] Add lint for unnecessary casts --- src/librustc/middle/cfg/construct.rs | 2 +- src/librustc/middle/check_const.rs | 2 +- src/librustc/middle/const_eval.rs | 4 +- src/librustc/middle/dataflow.rs | 2 +- src/librustc/middle/kind.rs | 2 +- src/librustc/middle/lint.rs | 64 ++++++++++++++- src/librustc/middle/liveness.rs | 2 +- src/librustc/middle/moves.rs | 2 +- src/librustc/middle/trans/consts.rs | 2 +- src/librustc/middle/trans/debuginfo.rs | 2 +- src/librustc/middle/trans/expr.rs | 4 +- src/librustc/middle/ty.rs | 5 ++ src/librustc/middle/typeck/check/mod.rs | 3 +- src/librustc/middle/typeck/check/regionck.rs | 2 +- src/librustc/middle/typeck/check/vtable.rs | 2 +- src/librustc/middle/typeck/infer/mod.rs | 14 ++++ src/libsyntax/ast.rs | 2 +- src/libsyntax/ext/build.rs | 2 +- src/libsyntax/ext/expand.rs | 78 ++++++++++++++++++- src/libsyntax/fold.rs | 4 +- src/libsyntax/parse/parser.rs | 2 +- src/libsyntax/print/pprust.rs | 2 +- src/libsyntax/visit.rs | 2 +- .../compile-fail/lint-unnecessary-casts.rs | 5 ++ .../run-pass/lint-unnecessary-casts-ffi.rs | 14 ++++ .../run-pass/lint-unnecessary-casts-macros.rs | 19 +++++ 26 files changed, 216 insertions(+), 28 deletions(-) create mode 100644 src/test/compile-fail/lint-unnecessary-casts.rs create mode 100644 src/test/run-pass/lint-unnecessary-casts-ffi.rs create mode 100644 src/test/run-pass/lint-unnecessary-casts-macros.rs diff --git a/src/librustc/middle/cfg/construct.rs b/src/librustc/middle/cfg/construct.rs index d5823e025be10..126b3c59a3dc8 100644 --- a/src/librustc/middle/cfg/construct.rs +++ b/src/librustc/middle/cfg/construct.rs @@ -396,7 +396,7 @@ impl CFGBuilder { ast::ExprAddrOf(_, e) | ast::ExprDoBody(e) | - ast::ExprCast(e, _) | + ast::ExprCast(e, _, _) | ast::ExprUnary(_, _, e) | ast::ExprParen(e) | ast::ExprVstore(e, _) | diff --git a/src/librustc/middle/check_const.rs b/src/librustc/middle/check_const.rs index c56a268c48fd3..58332d3286460 100644 --- a/src/librustc/middle/check_const.rs +++ b/src/librustc/middle/check_const.rs @@ -130,7 +130,7 @@ pub fn check_expr(v: &mut CheckCrateVisitor, } } ExprLit(_) => (), - ExprCast(_, _) => { + ExprCast(..) => { let ety = ty::expr_ty(tcx, e); if !ty::type_is_numeric(ety) && !ty::type_is_unsafe_ptr(ety) { sess.span_err(e.span, ~"can not cast to `" + diff --git a/src/librustc/middle/const_eval.rs b/src/librustc/middle/const_eval.rs index 20db51861d670..c73bea34e15e1 100644 --- a/src/librustc/middle/const_eval.rs +++ b/src/librustc/middle/const_eval.rs @@ -248,7 +248,7 @@ impl ConstEvalVisitor { join_all(cs) } - ast::ExprCast(base, _) => { + ast::ExprCast(base, _, _) => { let ty = ty::expr_ty(self.tcx, e); let base = self.classify(base); if ty::type_is_integral(ty) { @@ -447,7 +447,7 @@ pub fn eval_const_expr_partial(tcx: &T, e: &Expr) _ => Err(~"Bad operands for binary") } } - ExprCast(base, _) => { + ExprCast(base, _, _) => { let ety = tcx.expr_ty(e); let base = eval_const_expr_partial(tcx, base); match base { diff --git a/src/librustc/middle/dataflow.rs b/src/librustc/middle/dataflow.rs index b0ca03181f8d1..edf2d3b51bd9b 100644 --- a/src/librustc/middle/dataflow.rs +++ b/src/librustc/middle/dataflow.rs @@ -713,7 +713,7 @@ impl<'a, O:DataFlowOperator> PropagationContext<'a, O> { ast::ExprAddrOf(_, e) | ast::ExprDoBody(e) | - ast::ExprCast(e, _) | + ast::ExprCast(e, _, _) | ast::ExprUnary(_, _, e) | ast::ExprParen(e) | ast::ExprVstore(e, _) | diff --git a/src/librustc/middle/kind.rs b/src/librustc/middle/kind.rs index 49e57306c1216..6f67a5749dc07 100644 --- a/src/librustc/middle/kind.rs +++ b/src/librustc/middle/kind.rs @@ -310,7 +310,7 @@ pub fn check_expr(cx: &mut Context, e: @Expr) { let interior_type = ty::expr_ty(cx.tcx, interior); let _ = check_durable(cx.tcx, interior_type, interior.span); } - ExprCast(source, _) => { + ExprCast(source, _, _) => { let source_ty = ty::expr_ty(cx.tcx, source); let target_ty = ty::expr_ty(cx.tcx, e); check_trait_cast(cx, source_ty, target_ty, source.span); diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 666c7d84a9a90..db43898a03bcb 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -41,6 +41,10 @@ use middle::typeck; use middle::pat_util; use metadata::csearch; use util::ppaux::{ty_to_str}; +use std::to_str::ToStr; + +use middle::typeck::infer; +use middle::typeck::astconv::{ast_ty_to_ty, AstConv}; use std::cmp; use std::hashmap::HashMap; @@ -91,6 +95,7 @@ pub enum lint { unused_mut, unnecessary_allocation, dead_code, + unnecessary_cast, missing_doc, unreachable_code, @@ -267,6 +272,13 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[ default: warn }), + ("unnecessary_cast", + LintSpec { + lint: unnecessary_cast, + desc: "detects unnecessary type casts, that can be removed", + default: allow, + }), + ("unused_mut", LintSpec { lint: unused_mut, @@ -336,7 +348,6 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[ desc: "unknown features found in crate-level #[feature] directives", default: deny, }), - ("unknown_crate_type", LintSpec { lint: unknown_crate_type, @@ -569,6 +580,56 @@ fn check_while_true_expr(cx: &Context, e: &ast::Expr) { _ => () } } +impl<'a> AstConv for Context<'a>{ + fn tcx(&self) -> ty::ctxt { self.tcx } + + fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty { + ty::lookup_item_type(self.tcx, id) + } + + fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef { + ty::lookup_trait_def(self.tcx, id) + } + + fn ty_infer(&self, _span: Span) -> ty::t { + let infcx: @mut infer::InferCtxt = infer::new_infer_ctxt(self.tcx); + infcx.next_ty_var() + } +} + + +fn check_unused_casts(cx: &Context, e: &ast::Expr) { + fn check_cast(cx: &Context, expr: &ast::Expr, ty: &ast::Ty) { + let infcx: @mut infer::InferCtxt = infer::new_infer_ctxt(cx.tcx); + let t_t = ast_ty_to_ty(cx, &infcx, ty); + if ty::get(ty::expr_ty(cx.tcx, expr)).sty == ty::get(t_t).sty { + cx.span_lint(unnecessary_cast, ty.span, + "unnecessary type cast"); + } + } + + return match e.node { + ast::ExprCast(e1, t, expanded) => { + let ffi_type: bool = match t.node { + ast::ty_path(ref p, _, _) => { + let type_name = token::interner_get( + p.segments[p.segments.len()-1].identifier.name + ); + if type_name == @"size_t" { + true + } else { + false + } + } + _ => false + }; + if !ffi_type && !expanded { + check_cast(cx, e1, t); + } + } + _ => () + }; +} fn check_type_limits(cx: &Context, e: &ast::Expr) { return match e.node { @@ -1361,6 +1422,7 @@ impl<'a> Visitor<()> for Context<'a> { check_heap_expr(self, e); check_type_limits(self, e); + check_unused_casts(self, e); visit::walk_expr(self, e, ()); } diff --git a/src/librustc/middle/liveness.rs b/src/librustc/middle/liveness.rs index 94c7efbe7474b..a1ee4a4b850dd 100644 --- a/src/librustc/middle/liveness.rs +++ b/src/librustc/middle/liveness.rs @@ -1250,7 +1250,7 @@ impl Liveness { ExprAddrOf(_, e) | ExprDoBody(e) | - ExprCast(e, _) | + ExprCast(e, _, _) | ExprUnary(_, _, e) | ExprParen(e) => { self.propagate_through_expr(e, succ) diff --git a/src/librustc/middle/moves.rs b/src/librustc/middle/moves.rs index f4f0c5c8073d5..fcd3e13d2d36a 100644 --- a/src/librustc/middle/moves.rs +++ b/src/librustc/middle/moves.rs @@ -549,7 +549,7 @@ impl VisitContext { self.consume_expr(rhs); } - ExprCast(base, _) => { + ExprCast(base, _, _) => { self.consume_expr(base); } diff --git a/src/librustc/middle/trans/consts.rs b/src/librustc/middle/trans/consts.rs index 9c3a7f4f671c8..df17c748e0172 100644 --- a/src/librustc/middle/trans/consts.rs +++ b/src/librustc/middle/trans/consts.rs @@ -448,7 +448,7 @@ fn const_expr_unadjusted(cx: @CrateContext, } (const_get_elt(cx, arr, [iv as c_uint]), inlineable) } - ast::ExprCast(base, _) => { + ast::ExprCast(base, _, _) => { let ety = ty::expr_ty(cx.tcx, e); let llty = type_of::type_of(cx, ety); let basety = ty::expr_ty(cx.tcx, base); diff --git a/src/librustc/middle/trans/debuginfo.rs b/src/librustc/middle/trans/debuginfo.rs index 49577a1395390..8d63345ed3998 100644 --- a/src/librustc/middle/trans/debuginfo.rs +++ b/src/librustc/middle/trans/debuginfo.rs @@ -2613,7 +2613,7 @@ fn populate_scope_map(cx: &CrateContext, ast::ExprPath(_) => (), ast::ExprVstore(@ref sub_exp, _) | - ast::ExprCast(@ref sub_exp, _) | + ast::ExprCast(@ref sub_exp, _, _) | ast::ExprAddrOf(_, @ref sub_exp) | ast::ExprField(@ref sub_exp, _, _) | ast::ExprParen(@ref sub_exp) => walk_expr(cx, sub_exp, scope_stack, scope_map), diff --git a/src/librustc/middle/trans/expr.rs b/src/librustc/middle/trans/expr.rs index 640f9339a7d12..d8ae889ec88c0 100644 --- a/src/librustc/middle/trans/expr.rs +++ b/src/librustc/middle/trans/expr.rs @@ -617,7 +617,7 @@ fn trans_rvalue_datum_unadjusted(bcx: @Block, expr: &ast::Expr) -> DatumBlock { ast::ExprAddrOf(_, x) => { return trans_addr_of(bcx, expr, x); } - ast::ExprCast(val, _) => { + ast::ExprCast(val, _, _) => { return trans_imm_cast(bcx, val, expr.id); } ast::ExprParen(e) => { @@ -789,7 +789,7 @@ fn trans_rvalue_dps_unadjusted(bcx: @Block, expr: &ast::Expr, expr_ty(bcx, expr), dest); } - ast::ExprCast(val, _) => { + ast::ExprCast(val, _, _) => { match ty::get(node_id_type(bcx, expr.id)).sty { ty::ty_trait(_, _, store, _, _) => { return meth::trans_trait_cast(bcx, val, expr.id, diff --git a/src/librustc/middle/ty.rs b/src/librustc/middle/ty.rs index 3ae29eade7778..9ed374ac8d543 100644 --- a/src/librustc/middle/ty.rs +++ b/src/librustc/middle/ty.rs @@ -2871,6 +2871,11 @@ pub fn expr_ty(cx: ctxt, expr: &ast::Expr) -> t { return node_id_to_type(cx, expr.id); } +pub fn ast_ty_to_ty(cx: ctxt, expr: &ast::Ty) -> t { + return node_id_to_type(cx, expr.id); +} + + pub fn expr_ty_adjusted(cx: ctxt, expr: &ast::Expr) -> t { /*! * diff --git a/src/librustc/middle/typeck/check/mod.rs b/src/librustc/middle/typeck/check/mod.rs index 088104e84ef41..e7f29bcb7baa3 100644 --- a/src/librustc/middle/typeck/check/mod.rs +++ b/src/librustc/middle/typeck/check/mod.rs @@ -101,7 +101,6 @@ use middle::typeck::check::vtable::{LocationInfo, VtableContext}; use middle::typeck::CrateCtxt; use middle::typeck::infer::{resolve_type, force_tvar}; use middle::typeck::infer; -use middle::typeck::rscope::RegionScope; use middle::typeck::{lookup_def_ccx}; use middle::typeck::no_params; use middle::typeck::{require_same_types, method_map, vtable_map}; @@ -3037,7 +3036,7 @@ pub fn check_expr_with_unifier(fcx: @FnCtxt, fcx.write_bot(id); } } - ast::ExprCast(e, t) => { + ast::ExprCast(e, t, _) => { check_expr(fcx, e); let t_1 = fcx.to_ty(t); let t_e = fcx.expr_ty(e); diff --git a/src/librustc/middle/typeck/check/regionck.rs b/src/librustc/middle/typeck/check/regionck.rs index 03fe9dc41b8b7..0c7d81b5de078 100644 --- a/src/librustc/middle/typeck/check/regionck.rs +++ b/src/librustc/middle/typeck/check/regionck.rs @@ -400,7 +400,7 @@ fn visit_expr(rcx: &mut Rcx, expr: @ast::Expr) { visit::walk_expr(rcx, expr, ()); } - ast::ExprCast(source, _) => { + ast::ExprCast(source, _, _) => { // Determine if we are casting `source` to an trait // instance. If so, we have to be sure that the type of // the source obeys the trait's region bound. diff --git a/src/librustc/middle/typeck/check/vtable.rs b/src/librustc/middle/typeck/check/vtable.rs index fcf219323e1cc..a4fe97f15e98d 100644 --- a/src/librustc/middle/typeck/check/vtable.rs +++ b/src/librustc/middle/typeck/check/vtable.rs @@ -730,7 +730,7 @@ pub fn early_resolve_expr(ex: @ast::Expr, None => () } } - ast::ExprCast(src, _) => { + ast::ExprCast(src, _, _) => { debug!("vtable resolution on expr {}", ex.repr(fcx.tcx())); let target_ty = fcx.expr_ty(ex); resolve_object_cast(src, target_ty); diff --git a/src/librustc/middle/typeck/infer/mod.rs b/src/librustc/middle/typeck/infer/mod.rs index 9b71da4f767f6..1c954393d342b 100644 --- a/src/librustc/middle/typeck/infer/mod.rs +++ b/src/librustc/middle/typeck/infer/mod.rs @@ -47,6 +47,7 @@ use util::common::indent; use util::ppaux::{bound_region_to_str, ty_to_str, trait_ref_to_str, Repr}; use util::ppaux::{UserString}; +use middle::typeck::rscope::RegionScope; pub mod doc; pub mod macros; pub mod combine; @@ -97,6 +98,19 @@ pub struct InferCtxt { region_vars: RegionVarBindings, } +impl RegionScope for @mut InferCtxt { + + fn anon_regions(&self, + span: Span, + count: uint) -> Result<~[ty::Region], ()> { + Ok(vec::from_fn( + count, + |_| self.next_region_var(MiscVariable(span)))) + } +} + + + /// Why did we require that the two types be related? /// /// See `error_reporting.rs` for more details diff --git a/src/libsyntax/ast.rs b/src/libsyntax/ast.rs index 3523d63ef60de..7e669e7ce0f5b 100644 --- a/src/libsyntax/ast.rs +++ b/src/libsyntax/ast.rs @@ -554,7 +554,7 @@ pub enum Expr_ { ExprBinary(NodeId, BinOp, @Expr, @Expr), ExprUnary(NodeId, UnOp, @Expr), ExprLit(@lit), - ExprCast(@Expr, P), + ExprCast(@Expr, P, bool), ExprIf(@Expr, P, Option<@Expr>), ExprWhile(@Expr, P), // FIXME #6993: change to Option diff --git a/src/libsyntax/ext/build.rs b/src/libsyntax/ext/build.rs index 481472e8f0b12..a696530df3fa3 100644 --- a/src/libsyntax/ext/build.rs +++ b/src/libsyntax/ext/build.rs @@ -578,7 +578,7 @@ impl AstBuilder for ExtCtxt { fn expr_cast(&self, sp: Span, expr: @ast::Expr, ty: P) -> @ast::Expr { - self.expr(sp, ast::ExprCast(expr, ty)) + self.expr(sp, ast::ExprCast(expr, ty, false)) } diff --git a/src/libsyntax/ext/expand.rs b/src/libsyntax/ext/expand.rs index aa7c26805c367..b50361629f64c 100644 --- a/src/libsyntax/ext/expand.rs +++ b/src/libsyntax/ext/expand.rs @@ -24,6 +24,7 @@ use fold::*; use parse; use parse::{parse_item_from_source_str}; use parse::token; +//use parse::token::{fresh_mark, fresh_name, ident_to_str, intern, interner_get}; use parse::token::{fresh_mark, fresh_name, ident_to_str, intern}; use visit; use visit::Visitor; @@ -914,9 +915,41 @@ pub struct MacroExpander<'a> { cx: &'a mut ExtCtxt, } -impl<'a> ast_fold for MacroExpander<'a> { +static mut expansions: uint = 0; + + +impl ast_fold for MacroExpander { fn fold_expr(&mut self, expr: @ast::Expr) -> @ast::Expr { - expand_expr(expr, self) + + let start_macro = match expr.node { + ast::ExprMac(..) => true, + _ => false + }; + if start_macro { + unsafe { + expansions += 1; + } + } + let folded_expr = expand_expr(self.extsbox, + self.cx, + expr, + self); + unsafe { + if start_macro { + expansions -= 1; + } + + match folded_expr.node { + ast::ExprCast(a, b, _) if expansions > 0 => { + @ast::Expr { + id: folded_expr.id, + node: ast::ExprCast(a, b, true), + span: folded_expr.span + } + } + _ => folded_expr + } + } } fn fold_mod(&mut self, module: &ast::_mod) -> ast::_mod { @@ -924,11 +957,48 @@ impl<'a> ast_fold for MacroExpander<'a> { } fn fold_item(&mut self, item: @ast::item) -> SmallVector<@ast::item> { - expand_item(item, self) + let start_macro = match item.node { + ast::item_mac(..) => true, + _ => false + }; + if start_macro { + unsafe { + expansions += 1; + } + } + let expanded_item =expand_item(self.extsbox, + self.cx, + item, + self); + unsafe { + if start_macro { + expansions -= 1; + } + } + expanded_item } fn fold_stmt(&mut self, stmt: &ast::Stmt) -> SmallVector<@ast::Stmt> { - expand_stmt(stmt, self) + let start_macro = match stmt.node { + ast::StmtMac(..) => true, + _ => false + }; + if start_macro { + unsafe { + expansions += 1; + } + } + + let expanded_stmt = expand_stmt(self.extsbox, + self.cx, + stmt, + self); + unsafe { + if start_macro { + expansions -= 1; + } + } + expanded_stmt } fn fold_block(&mut self, block: P) -> P { diff --git a/src/libsyntax/fold.rs b/src/libsyntax/fold.rs index 47130a8e355e8..2caf048eb5bae 100644 --- a/src/libsyntax/fold.rs +++ b/src/libsyntax/fold.rs @@ -749,8 +749,8 @@ pub fn noop_fold_expr(e: @ast::Expr, folder: &mut T) -> @ast::Expr { } ExprDoBody(f) => ExprDoBody(folder.fold_expr(f)), ExprLit(_) => e.node.clone(), - ExprCast(expr, ty) => { - ExprCast(folder.fold_expr(expr), folder.fold_ty(ty)) + ExprCast(expr, ty, expanded) => { + ExprCast(folder.fold_expr(expr), folder.fold_ty(ty), expanded) } ExprAddrOf(m, ohs) => ExprAddrOf(m, folder.fold_expr(ohs)), ExprIf(cond, tr, fl) => { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 40a2ef86e4fb9..13f281813d6fb 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -2387,7 +2387,7 @@ impl Parser { let rhs = self.parse_ty(true); let _as = self.mk_expr(lhs.span.lo, rhs.span.hi, - ExprCast(lhs, rhs)); + ExprCast(lhs, rhs, false)); self.parse_more_binops(_as, min_prec) } else { lhs diff --git a/src/libsyntax/print/pprust.rs b/src/libsyntax/print/pprust.rs index 9725d6e38deee..a4d958146b0d9 100644 --- a/src/libsyntax/print/pprust.rs +++ b/src/libsyntax/print/pprust.rs @@ -1248,7 +1248,7 @@ pub fn print_expr(s: &mut ps, expr: &ast::Expr) { print_expr(s, expr); } ast::ExprLit(lit) => print_literal(s, lit), - ast::ExprCast(expr, ty) => { + ast::ExprCast(expr, ty, _) => { print_expr(s, expr); space(&mut s.s); word_space(s, "as"); diff --git a/src/libsyntax/visit.rs b/src/libsyntax/visit.rs index 29567ab944213..06abde411a5a9 100644 --- a/src/libsyntax/visit.rs +++ b/src/libsyntax/visit.rs @@ -660,7 +660,7 @@ pub fn walk_expr>(visitor: &mut V, expression: @Expr, env: visitor.visit_expr(subexpression, env.clone()) } ExprLit(_) => {} - ExprCast(subexpression, typ) => { + ExprCast(subexpression, typ, _) => { visitor.visit_expr(subexpression, env.clone()); visitor.visit_ty(typ, env.clone()) } diff --git a/src/test/compile-fail/lint-unnecessary-casts.rs b/src/test/compile-fail/lint-unnecessary-casts.rs new file mode 100644 index 0000000000000..ec9556ff3e9fe --- /dev/null +++ b/src/test/compile-fail/lint-unnecessary-casts.rs @@ -0,0 +1,5 @@ +fn main() { + let x: u64 = 1; + let y: u64 = x as u64; //~ WARN: unnecessary type cast + println!("{}", y); +} diff --git a/src/test/run-pass/lint-unnecessary-casts-ffi.rs b/src/test/run-pass/lint-unnecessary-casts-ffi.rs new file mode 100644 index 0000000000000..4bfe6aa0e0d69 --- /dev/null +++ b/src/test/run-pass/lint-unnecessary-casts-ffi.rs @@ -0,0 +1,14 @@ +use std::libc::size_t; + + +fn foo(x: size_t) { + println!("{}", x); +} + +fn main() { + let x: u64 = 1; + + // on 64 bit linux, size_t is u64, therefore the cast seems unnecessary, + // but on 32 bit linux is's u32, so the cast is needed + foo(x as size_t); +} diff --git a/src/test/run-pass/lint-unnecessary-casts-macros.rs b/src/test/run-pass/lint-unnecessary-casts-macros.rs new file mode 100644 index 0000000000000..086fc87e038bd --- /dev/null +++ b/src/test/run-pass/lint-unnecessary-casts-macros.rs @@ -0,0 +1,19 @@ + +#[feature(macro_rules)]; + +macro_rules! macro_with_cast( + ($x:ident) => ( // invoke it like `(input_5 special_e)` + { let y: u32 = 1; + foo(y); + $x as u64 + }); +) + +fn foo(z: u32) -> u32 { z+z } + +fn main() { + let x: u64 = 10; + macro_with_cast!(x); + macro_with_cast!(x); + //println!("{}", macro_with_cast!(x)); +} From 7fdaa56d6303ad8014b71c303873a9adc3e323f2 Mon Sep 17 00:00:00 2001 From: Florian Hahn Date: Wed, 25 Dec 2013 00:53:05 +0100 Subject: [PATCH 2/3] Remove some unnecessary type casts --- src/libextra/bitv.rs | 2 +- src/libextra/ebml.rs | 2 +- src/libextra/test.rs | 8 ++++---- src/libextra/time.rs | 4 ++-- src/libnative/io/file.rs | 22 +++++++++++----------- src/librustc/middle/lint.rs | 2 +- src/libstd/cleanup.rs | 2 +- src/libstd/io/mod.rs | 10 +++++----- src/libstd/io/net/ip.rs | 6 +++--- src/libstd/io/stdio.rs | 2 +- src/libstd/num/strconv.rs | 2 +- src/libstd/rand/distributions/normal.rs | 2 +- src/libstd/rt/global_heap.rs | 6 +++--- src/libstd/rt/local_heap.rs | 2 +- src/libstd/str.rs | 6 +++--- src/libstd/unstable/mutex.rs | 4 ++-- 16 files changed, 41 insertions(+), 41 deletions(-) diff --git a/src/libextra/bitv.rs b/src/libextra/bitv.rs index 3b44ad50ad79a..9f40507826fde 100644 --- a/src/libextra/bitv.rs +++ b/src/libextra/bitv.rs @@ -80,7 +80,7 @@ impl SmallBitv { self.bits |= 1< TestResult { impl ToJson for Metric { fn to_json(&self) -> json::Json { let mut map = ~TreeMap::new(); - map.insert(~"value", json::Number(self.value as f64)); - map.insert(~"noise", json::Number(self.noise as f64)); + map.insert(~"value", json::Number(self.value)); + map.insert(~"noise", json::Number(self.noise)); json::Object(map) } } @@ -1124,7 +1124,7 @@ impl BenchHarness { let loop_start = precise_time_ns(); for p in samples.mut_iter() { - self.bench_n(n as u64, |x| f(x)); + self.bench_n(n, |x| f(x)); *p = self.ns_per_iter() as f64; }; @@ -1132,7 +1132,7 @@ impl BenchHarness { let summ = stats::Summary::new(samples); for p in samples.mut_iter() { - self.bench_n(5 * n as u64, |x| f(x)); + self.bench_n(5 * n, |x| f(x)); *p = self.ns_per_iter() as f64; }; diff --git a/src/libextra/time.rs b/src/libextra/time.rs index 23c81c6fce529..c2948024e2801 100644 --- a/src/libextra/time.rs +++ b/src/libextra/time.rs @@ -767,13 +767,13 @@ pub fn strptime(s: &str, format: &str) -> Result { let mut buf = [0]; let c = match rdr.read(buf) { - Some(..) => buf[0] as u8 as char, + Some(..) => buf[0] as char, None => break }; match c { '%' => { let ch = match rdr.read(buf) { - Some(..) => buf[0] as u8 as char, + Some(..) => buf[0] as char, None => break }; match parse_type(s, pos, ch, &mut tm) { diff --git a/src/libnative/io/file.rs b/src/libnative/io/file.rs index 6197bd70c7610..ef73a0aabad4c 100644 --- a/src/libnative/io/file.rs +++ b/src/libnative/io/file.rs @@ -39,7 +39,7 @@ pub fn keep_going(data: &[u8], f: |*u8, uint| -> i64) -> i64 { ret = f(data, amt); if cfg!(windows) { break } // windows has no eintr // if we get an eintr, then try again - if ret != -1 || os::errno() as int != eintr { break } + if ret != -1 || os::errno() != eintr { break } } if ret == 0 { break @@ -81,7 +81,7 @@ impl FileDesc { #[cfg(not(windows))] type rlen = libc::size_t; let ret = keep_going(buf, |buf, len| { unsafe { - libc::read(self.fd, buf as *mut libc::c_void, len as rlen) as i64 + libc::read(self.fd, buf as *mut libc::c_void, len as rlen) } }); if ret == 0 { @@ -97,7 +97,7 @@ impl FileDesc { #[cfg(not(windows))] type wlen = libc::size_t; let ret = keep_going(buf, |buf, len| { unsafe { - libc::write(self.fd, buf as *libc::c_void, len as wlen) as i64 + libc::write(self.fd, buf as *libc::c_void, len as wlen) } }); if ret < 0 { @@ -213,7 +213,7 @@ impl rtio::RtioFileStream for FileDesc { io::SeekEnd => libc::SEEK_END, io::SeekCur => libc::SEEK_CUR, }; - let n = unsafe { libc::lseek(self.fd, pos as libc::off_t, whence) }; + let n = unsafe { libc::lseek(self.fd, pos, whence) }; if n < 0 { Err(super::last_error()) } else { @@ -279,7 +279,7 @@ impl rtio::RtioFileStream for FileDesc { #[cfg(unix)] fn truncate(&mut self, offset: i64) -> Result<(), IoError> { super::mkerr_libc(unsafe { - libc::ftruncate(self.fd, offset as libc::off_t) + libc::ftruncate(self.fd, offset) }) } } @@ -385,7 +385,7 @@ impl rtio::RtioFileStream for CFile { io::SeekEnd => libc::SEEK_END, io::SeekCur => libc::SEEK_CUR, }; - let n = unsafe { libc::fseek(self.file, pos as libc::c_long, whence) }; + let n = unsafe { libc::fseek(self.file, pos, whence) }; if n < 0 { Err(super::last_error()) } else { @@ -816,15 +816,15 @@ fn mkstat(stat: &libc::stat, path: &CString) -> io::FileStat { path: Path::new(path), size: stat.st_size as u64, kind: kind, - perm: (stat.st_mode) as io::FilePermission & io::AllPermissions, + perm: stat.st_mode & io::AllPermissions, created: mktime(stat.st_ctime as u64, stat.st_ctime_nsec as u64), modified: mktime(stat.st_mtime as u64, stat.st_mtime_nsec as u64), accessed: mktime(stat.st_atime as u64, stat.st_atime_nsec as u64), unstable: io::UnstableFileStat { - device: stat.st_dev as u64, - inode: stat.st_ino as u64, - rdev: stat.st_rdev as u64, - nlink: stat.st_nlink as u64, + device: stat.st_dev, + inode: stat.st_ino, + rdev: stat.st_rdev, + nlink: stat.st_nlink, uid: stat.st_uid as u64, gid: stat.st_gid as u64, blksize: stat.st_blksize as u64, diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index db43898a03bcb..3dc1a0d0908bb 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -276,7 +276,7 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[ LintSpec { lint: unnecessary_cast, desc: "detects unnecessary type casts, that can be removed", - default: allow, + default: warn, }), ("unused_mut", diff --git a/src/libstd/cleanup.rs b/src/libstd/cleanup.rs index fbcf7dd4e9026..fd9040423a3d9 100644 --- a/src/libstd/cleanup.rs +++ b/src/libstd/cleanup.rs @@ -42,7 +42,7 @@ unsafe fn each_live_alloc(read_next_before: bool, let next_before = (*alloc).next; let uniq = (*alloc).ref_count == managed::RC_MANAGED_UNIQUE; - if !f(alloc as *mut raw::Box<()>, uniq) { + if !f(alloc, uniq) { return false; } diff --git a/src/libstd/io/mod.rs b/src/libstd/io/mod.rs index 9c181aa56c223..90c30ece7895f 100644 --- a/src/libstd/io/mod.rs +++ b/src/libstd/io/mod.rs @@ -724,7 +724,7 @@ pub trait Reader { /// /// `u64`s are 8 bytes long. fn read_be_u64(&mut self) -> u64 { - self.read_be_uint_n(8) as u64 + self.read_be_uint_n(8) } /// Reads a big-endian `u32`. @@ -745,7 +745,7 @@ pub trait Reader { /// /// `i64`s are 8 bytes long. fn read_be_i64(&mut self) -> i64 { - self.read_be_int_n(8) as i64 + self.read_be_int_n(8) } /// Reads a big-endian `i32`. @@ -784,7 +784,7 @@ pub trait Reader { /// /// `u64`s are 8 bytes long. fn read_le_u64(&mut self) -> u64 { - self.read_le_uint_n(8) as u64 + self.read_le_uint_n(8) } /// Reads a little-endian `u32`. @@ -805,7 +805,7 @@ pub trait Reader { /// /// `i64`s are 8 bytes long. fn read_le_i64(&mut self) -> i64 { - self.read_le_int_n(8) as i64 + self.read_le_int_n(8) } /// Reads a little-endian `i32`. @@ -845,7 +845,7 @@ pub trait Reader { /// `u8`s are 1 byte. fn read_u8(&mut self) -> u8 { match self.read_byte() { - Some(b) => b as u8, + Some(b) => b, None => 0 } } diff --git a/src/libstd/io/net/ip.rs b/src/libstd/io/net/ip.rs index b4d14b57efca1..9fd183ca7704c 100644 --- a/src/libstd/io/net/ip.rs +++ b/src/libstd/io/net/ip.rs @@ -153,11 +153,11 @@ impl<'a> Parser<'a> { let c = c as u8; // assuming radix is either 10 or 16 if c >= '0' as u8 && c <= '9' as u8 { - Some((c - '0' as u8) as u8) + Some(c - '0' as u8) } else if radix > 10 && c >= 'a' as u8 && c < 'a' as u8 + (radix - 10) { - Some((c - 'a' as u8 + 10) as u8) + Some(c - 'a' as u8 + 10) } else if radix > 10 && c >= 'A' as u8 && c < 'A' as u8 + (radix - 10) { - Some((c - 'A' as u8 + 10) as u8) + Some(c - 'A' as u8 + 10) } else { None } diff --git a/src/libstd/io/stdio.rs b/src/libstd/io/stdio.rs index 1e4fa7968dc42..1fcafd7d12f78 100644 --- a/src/libstd/io/stdio.rs +++ b/src/libstd/io/stdio.rs @@ -209,7 +209,7 @@ impl Reader for StdReader { io_error::cond.raise(standard_error(EndOfFile)); None } - Ok(amt) => Some(amt as uint), + Ok(amt) => Some(amt), Err(e) => { io_error::cond.raise(e); None diff --git a/src/libstd/num/strconv.rs b/src/libstd/num/strconv.rs index 8e678ab66b25e..7dcae69f70d6d 100644 --- a/src/libstd/num/strconv.rs +++ b/src/libstd/num/strconv.rs @@ -344,7 +344,7 @@ pub fn float_to_str_bytes_common(rng: &mut R) -> StandardNormal { #[inline] fn pdf(x: f64) -> f64 { - ((-x*x/2.0) as f64).exp() + (-x*x/2.0).exp() } #[inline] fn zero_case(rng: &mut R, u: f64) -> f64 { diff --git a/src/libstd/rt/global_heap.rs b/src/libstd/rt/global_heap.rs index 385bb0b276c49..32e4486d7cca8 100644 --- a/src/libstd/rt/global_heap.rs +++ b/src/libstd/rt/global_heap.rs @@ -57,7 +57,7 @@ pub unsafe fn realloc_raw(ptr: *mut c_void, size: uint) -> *mut c_void { #[lang="exchange_malloc"] #[inline] pub unsafe fn exchange_malloc(size: uintptr_t) -> *c_char { - malloc_raw(size as uint) as *c_char + malloc_raw(size) as *c_char } // FIXME: #7496 @@ -71,12 +71,12 @@ pub unsafe fn closure_exchange_malloc_(td: *c_char, size: uintptr_t) -> *c_char #[inline] pub unsafe fn closure_exchange_malloc(td: *c_char, size: uintptr_t) -> *c_char { let td = td as *TyDesc; - let size = size as uint; + let size: uint = size; assert!(td.is_not_null()); let total_size = get_box_size(size, (*td).align); - let p = malloc_raw(total_size as uint); + let p = malloc_raw(total_size); let alloc = p as *mut raw::Box<()>; (*alloc).type_desc = td; diff --git a/src/libstd/rt/local_heap.rs b/src/libstd/rt/local_heap.rs index f2edc6e7ede60..43fbfbe352e6b 100644 --- a/src/libstd/rt/local_heap.rs +++ b/src/libstd/rt/local_heap.rs @@ -285,7 +285,7 @@ pub unsafe fn local_malloc(td: *libc::c_char, size: libc::uintptr_t) -> *libc::c let task: Option<*mut Task> = Local::try_unsafe_borrow(); match task { Some(task) => { - (*task).heap.alloc(td as *TyDesc, size as uint) as *libc::c_char + (*task).heap.alloc(td as *TyDesc, size) as *libc::c_char } None => rtabort!("local malloc outside of task") } diff --git a/src/libstd/str.rs b/src/libstd/str.rs index 4516fb85f9095..66c68d60b2216 100644 --- a/src/libstd/str.rs +++ b/src/libstd/str.rs @@ -901,7 +901,7 @@ pub fn utf16_chars(v: &[u16], f: |char|) { let mut c: u32 = (u - 0xD800_u16) as u32; c = c << 10; c |= (u2 - 0xDC00_u16) as u32; - c |= 0x1_0000_u32 as u32; + c |= 0x1_0000_u32; f(unsafe { cast::transmute(c) }); i += 2u; } @@ -964,7 +964,7 @@ pub struct CharRange { // The first byte is special, only want bottom 5 bits for width 2, 4 bits // for width 3, and 3 bits for width 4 macro_rules! utf8_first_byte( - ($byte:expr, $width:expr) => (($byte & (0x7F >> $width)) as uint) + ($byte:expr, $width:expr) => ($byte & (0x7F >> $width)) ) // return the value of $ch updated with continuation byte $byte @@ -987,7 +987,7 @@ pub mod raw { /// Create a Rust string from a *u8 buffer of the given length pub unsafe fn from_buf_len(buf: *u8, len: uint) -> ~str { let mut v: ~[u8] = vec::with_capacity(len); - ptr::copy_memory(v.as_mut_ptr(), buf as *u8, len); + ptr::copy_memory(v.as_mut_ptr(), buf, len); v.set_len(len); assert!(is_utf8(v)); diff --git a/src/libstd/unstable/mutex.rs b/src/libstd/unstable/mutex.rs index 36682b8541860..e11557ff337c2 100644 --- a/src/libstd/unstable/mutex.rs +++ b/src/libstd/unstable/mutex.rs @@ -66,8 +66,8 @@ impl Mutex { /// Creates a new mutex, with the lock/condition variable pre-initialized pub unsafe fn new() -> Mutex { Mutex { - lock: atomics::AtomicUint::new(imp::init_lock() as uint), - cond: atomics::AtomicUint::new(imp::init_cond() as uint), + lock: atomics::AtomicUint::new(imp::init_lock()), + cond: atomics::AtomicUint::new(imp::init_cond()), } } From ac69af5c6994483ac9b3a6d8dea912c228dfecd5 Mon Sep 17 00:00:00 2001 From: Florian Hahn Date: Sun, 22 Dec 2013 00:07:21 +0100 Subject: [PATCH 3/3] Add lint for unnecessary casts Conflicts: src/librustc/middle/lint.rs --- src/librustc/middle/lint.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/librustc/middle/lint.rs b/src/librustc/middle/lint.rs index 3dc1a0d0908bb..db43898a03bcb 100644 --- a/src/librustc/middle/lint.rs +++ b/src/librustc/middle/lint.rs @@ -276,7 +276,7 @@ static lint_table: &'static [(&'static str, LintSpec)] = &[ LintSpec { lint: unnecessary_cast, desc: "detects unnecessary type casts, that can be removed", - default: warn, + default: allow, }), ("unused_mut",