Skip to content
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

Port clippy lint redundant_field_names to compiler #87512

Closed
wants to merge 10 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
2 changes: 1 addition & 1 deletion compiler/rustc_borrowck/src/region_infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1751,7 +1751,7 @@ impl<'tcx> RegionInferenceContext<'tcx> {
.map(|&(category, span)| BlameConstraint {
category,
from_closure: true,
span: span,
span,
variance_info: constraint.variance_info,
})
.unwrap_or(BlameConstraint {
Expand Down
7 changes: 3 additions & 4 deletions compiler/rustc_codegen_llvm/src/type_of.rs
Original file line number Diff line number Diff line change
Expand Up @@ -268,10 +268,9 @@ impl<'tcx> LayoutLlvmExt<'tcx> for TyAndLayout<'tcx> {
};
debug!("--> mapped {:#?} to llty={:?}", self, llty);

cx.type_lowering.borrow_mut().insert(
(self.ty, variant_index),
TypeLowering { lltype: llty, field_remapping: field_remapping },
);
cx.type_lowering
.borrow_mut()
.insert((self.ty, variant_index), TypeLowering { lltype: llty, field_remapping });

if let Some((llty, layout)) = defer {
let (llfields, packed, new_field_remapping) = struct_llfields(cx, layout);
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_const_eval/src/interpret/place.rs
Original file line number Diff line number Diff line change
Expand Up @@ -447,7 +447,7 @@ where
let actual_to = if from_end {
if from.checked_add(to).map_or(true, |to| to > len) {
// This can only be reached in ConstProp and non-rustc-MIR.
throw_ub!(BoundsCheckFailed { len: len, index: from.saturating_add(to) });
throw_ub!(BoundsCheckFailed { len, index: from.saturating_add(to) });
}
len.checked_sub(to).unwrap()
} else {
Expand Down
4 changes: 2 additions & 2 deletions compiler/rustc_graphviz/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@
//! pub fn render_to<W: Write>(output: &mut W) {
//! let nodes = vec!["{x,y}","{x}","{y}","{}"];
//! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
//! let graph = Graph { nodes: nodes, edges: edges };
//! let graph = Graph { nodes, edges };
//!
//! dot::render(&graph, output).unwrap()
//! }
Expand Down Expand Up @@ -216,7 +216,7 @@
//! pub fn render_to<W: Write>(output: &mut W) {
//! let nodes = vec!["{x,y}","{x}","{y}","{}"];
//! let edges = vec![(0,1), (0,2), (1,3), (2,3)];
//! let graph = Graph { nodes: nodes, edges: edges };
//! let graph = Graph { nodes, edges };
//!
//! dot::render(&graph, output).unwrap()
//! }
Expand Down
3 changes: 3 additions & 0 deletions compiler/rustc_lint/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ mod non_fmt_panic;
mod nonstandard_style;
mod noop_method_call;
mod passes;
mod redundant_field_initializers;
mod redundant_semicolon;
mod traits;
mod types;
Expand All @@ -83,6 +84,7 @@ use non_ascii_idents::*;
use non_fmt_panic::NonPanicFmt;
use nonstandard_style::*;
use noop_method_call::*;
use redundant_field_initializers::*;
use redundant_semicolon::*;
use traits::*;
use types::*;
Expand Down Expand Up @@ -129,6 +131,7 @@ macro_rules! early_lint_passes {
WhileTrue: WhileTrue,
NonAsciiIdents: NonAsciiIdents,
IncompleteFeatures: IncompleteFeatures,
RedundantFieldInitializers: RedundantFieldInitializers,
RedundantSemicolons: RedundantSemicolons,
UnusedDocComment: UnusedDocComment,
]
Expand Down
67 changes: 67 additions & 0 deletions compiler/rustc_lint/src/redundant_field_initializers.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
use crate::{EarlyContext, EarlyLintPass, LintContext};
use rustc_ast as ast;
use rustc_errors::Applicability;
use rustc_span::source_map::ExpnKind;

declare_lint! {
/// The `redundant_field_initializers` lint checks for fields in struct literals
/// where shorthands could be used.
///
/// ### Example
///
/// ```rust
/// let bar: u8 = 123;
///
/// struct Foo {
/// bar: u8,
/// }
///
/// let foo = Foo { bar: bar };
/// ```
///
/// {{produces}}
///
/// ### Explanation
///
/// If the field and variable names are the same,
/// the field name is redundant.
pub REDUNDANT_FIELD_INITIALIZERS,
Warn,
"checks for fields in struct literals where shorthands could be used"
}

declare_lint_pass!(RedundantFieldInitializers => [REDUNDANT_FIELD_INITIALIZERS]);

impl EarlyLintPass for RedundantFieldInitializers {
fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
if let ExpnKind::Macro(..) = expr.span.ctxt().outer_expn_data().kind {
// Do not lint on macro output.
return;
}

if let ast::ExprKind::Struct(ref se) = expr.kind {
for field in &se.fields {
if field.is_shorthand {
continue;
}
if let ast::ExprKind::Path(None, path) = &field.expr.kind {
if path.segments.len() == 1
&& path.segments[0].ident == field.ident
&& path.segments[0].args.is_none()
{
cx.struct_span_lint(REDUNDANT_FIELD_INITIALIZERS, field.span, |lint| {
lint.build("redundant field names in struct initialization")
.span_suggestion(
field.span,
"replace it with",
field.ident.to_string(),
Applicability::MachineApplicable,
)
.emit();
});
}
}
}
}
}
}
2 changes: 1 addition & 1 deletion compiler/rustc_middle/src/hir/map/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
insert_vec_map(
&mut nodes.nodes,
hir_id.local_id,
ParentedNode { parent: self.parent_node.local_id, node: node },
ParentedNode { parent: self.parent_node.local_id, node },
);
}

Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_mir_build/src/build/expr/as_constant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
Constant { span, user_ty: None, literal: literal.into() }
}
ExprKind::ConstBlock { value } => {
Constant { span: span, user_ty: None, literal: value.into() }
Constant { span, user_ty: None, literal: value.into() }
}
_ => span_bug!(span, "expression is not a valid constant {:?}", kind),
}
Expand Down
5 changes: 2 additions & 3 deletions compiler/rustc_mir_build/src/thir/cx/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -704,8 +704,7 @@ impl<'tcx> Cx<'tcx> {
ty: var_ty,
};
let lhs = self.thir.exprs.push(mk_const(self.tcx().mk_const(lhs)));
let bin =
ExprKind::Binary { op: BinOp::Add, lhs: lhs, rhs: offset };
let bin = ExprKind::Binary { op: BinOp::Add, lhs, rhs: offset };
self.thir.exprs.push(Expr {
temp_lifetime,
ty: var_ty,
Expand All @@ -719,7 +718,7 @@ impl<'tcx> Cx<'tcx> {
self.mirror_expr(source)
};

ExprKind::Cast { source: source }
ExprKind::Cast { source }
};

if let Some(user_ty) = user_ty {
Expand Down
2 changes: 1 addition & 1 deletion compiler/rustc_target/src/spec/aarch64_apple_ios_sim.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ pub fn target() -> Target {
let llvm_target = super::apple_base::ios_sim_llvm_target(arch);

Target {
llvm_target: llvm_target,
llvm_target,
pointer_width: 64,
data_layout: "e-m:o-i64:64-i128:128-n32:64-S128".to_string(),
arch: "aarch64".to_string(),
Expand Down
5 changes: 3 additions & 2 deletions compiler/rustc_typeck/src/check/upvar.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1548,8 +1548,9 @@ fn apply_capture_kind_on_capture_ty(
) -> Ty<'tcx> {
match capture_kind {
ty::UpvarCapture::ByValue(_) => ty,
ty::UpvarCapture::ByRef(borrow) => tcx
.mk_ref(borrow.region, ty::TypeAndMut { ty: ty, mutbl: borrow.kind.to_mutbl_lossy() }),
ty::UpvarCapture::ByRef(borrow) => {
tcx.mk_ref(borrow.region, ty::TypeAndMut { ty, mutbl: borrow.kind.to_mutbl_lossy() })
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion library/alloc/tests/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1802,7 +1802,7 @@ fn panic_safe() {
let mut input = (0..len)
.map(|id| DropCounter {
x: rng.next_u32() % modulus,
id: id,
id,
version: Cell::new(0),
})
.collect::<Vec<_>>();
Expand Down
2 changes: 1 addition & 1 deletion src/librustdoc/passes/collect_intra_doc_links.rs
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> {
) -> Result<(Res, Option<String>), ErrorKind<'path>> {
let tcx = self.cx.tcx;
let no_res = || ResolutionFailure::NotResolved {
module_id: module_id,
module_id,
partial_res: None,
unresolved: path_str.into(),
};
Expand Down
6 changes: 3 additions & 3 deletions src/test/ui-fulldeps/regions-mock-tcx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ struct TypeContext<'tcx, 'ast> {
impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
fn new(ty_arena: &'tcx TyArena<'tcx>, ast_arena: &'ast AstArena<'ast>)
-> TypeContext<'tcx, 'ast> {
TypeContext { ty_arena: ty_arena,
TypeContext { ty_arena,
types: Vec::new(),
type_table: HashMap::new(),

ast_arena: ast_arena,
ast_arena,
ast_counter: 0 }
}

Expand All @@ -83,7 +83,7 @@ impl<'tcx,'ast> TypeContext<'tcx, 'ast> {
fn ast(&mut self, a: AstKind<'ast>) -> Ast<'ast> {
let id = self.ast_counter;
self.ast_counter += 1;
self.ast_arena.alloc(AstStructure { id: NodeId {id:id}, kind: a })
self.ast_arena.alloc(AstStructure { id: NodeId {id}, kind: a })
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/alias-uninit-value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ enum sty { ty_nil, }
struct RawT {struct_: sty, cname: Option<String>, hash: usize}

fn mk_raw_ty(st: sty, cname: Option<String>) -> RawT {
return RawT {struct_: st, cname: cname, hash: 0};
return RawT {struct_: st, cname, hash: 0};
}

pub fn main() { mk_raw_ty(sty::ty_nil, None::<String>); }
4 changes: 2 additions & 2 deletions src/test/ui/alignment-gep-tup-like-1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ impl<A:Clone> Invokable<A> for Invoker<A> {

fn f<A:Clone + 'static>(a: A, b: u16) -> Box<dyn Invokable<A>+'static> {
box Invoker {
a: a,
b: b,
a,
b,
} as Box<dyn Invokable<A>+'static>
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/array-slice-vec/destructure-array-1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ struct D { x: u8 }
impl Drop for D { fn drop(&mut self) { } }

fn main() {
fn d(x: u8) -> D { D { x: x } }
fn d(x: u8) -> D { D { x } }

let d1 = foo([d(1), d(2), d(3), d(4)], 1);
let d3 = foo([d(5), d(6), d(7), d(8)], 3);
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/array-slice-vec/vec-res-add.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ struct R {
i:isize
}

fn r(i:isize) -> R { R { i: i } }
fn r(i:isize) -> R { R { i } }

impl Drop for R {
fn drop(&mut self) {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ impl OffsetState for Y {}
pub fn now() -> DateTime<X> { from_utc(Y) }

pub struct DateTime<Off: Offset> { pub offset: Off::State }
pub fn from_utc<Off: Offset>(offset: Off::State) -> DateTime<Off> { DateTime { offset: offset } }
pub fn from_utc<Off: Offset>(offset: Off::State) -> DateTime<Off> { DateTime { offset } }

pub fn main() {
let _x = now();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ struct TesterPair<T:Test> {

impl<T:Test> TesterPair<T> {
fn new(tester: T, value: T::V) -> TesterPair<T> {
TesterPair { tester: tester, value: value }
TesterPair { tester, value }
}

fn test(&self) -> bool {
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/attributes/class-attributes-1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@ impl Drop for Cat {


#[rustc_dummy]
fn cat(name: String) -> Cat { Cat{name: name,} }
fn cat(name: String) -> Cat { Cat{name,} }

fn main() { let _kitty = cat("Spotty".to_string()); }
2 changes: 1 addition & 1 deletion src/test/ui/attributes/class-attributes-2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ Maybe it should technically be a kitten_maker.
*/
fn cat(name: String) -> Cat {
Cat {
name: name
name
}
}

Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/binop/binops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ struct p {

fn p(x: isize, y: isize) -> p {
p {
x: x,
y: y
x,
y
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/borrowck/borrowck-borrowed-uniq-rvalue-2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ impl<'a> Drop for Defer<'a> {

fn defer<'r>(x: &'r [&'r str]) -> Defer<'r> {
Defer {
x: x
x
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/borrowck/fsu-moves-and-copies.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
#![feature(box_syntax, core)]

struct ncint { v: isize }
fn ncint(v: isize) -> ncint { ncint { v: v } }
fn ncint(v: isize) -> ncint { ncint { v } }

struct NoFoo { copied: isize, nocopy: ncint, }
impl NoFoo {
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/cfg/conditional-compile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,15 +46,15 @@ struct r {

#[cfg(bogus)]
fn r(i: isize) -> r {
r { i: i }
r { i }
}

struct r {
i: isize,
}

fn r(i: isize) -> r {
r { i: i }
r { i }
}

#[cfg(bogus)]
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/cleanup-rvalue-for-scope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ struct Box<T> { f: T }
struct AddFlags { bits: u64 }

fn AddFlags(bits: u64) -> AddFlags {
AddFlags { bits: bits }
AddFlags { bits }
}

fn arg(exp: u64, _x: &AddFlags) {
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/cleanup-rvalue-scopes-cf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ struct StackBox<T> { f: T }
struct AddFlags { bits: u64 }

fn AddFlags(bits: u64) -> AddFlags {
AddFlags { bits: bits }
AddFlags { bits }
}

fn arg(x: &AddFlags) -> &AddFlags {
Expand Down
2 changes: 1 addition & 1 deletion src/test/ui/cleanup-rvalue-scopes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ struct Box<T> { f: T }
struct AddFlags { bits: u64 }

fn AddFlags(bits: u64) -> AddFlags {
AddFlags { bits: bits }
AddFlags { bits }
}

fn arg(exp: u64, _x: &AddFlags) {
Expand Down
4 changes: 2 additions & 2 deletions src/test/ui/close-over-big-then-small-data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@ impl<A:Clone> Invokable<A> for Invoker<A> {

fn f<A:Clone + 'static>(a: A, b: u16) -> Box<dyn Invokable<A>+'static> {
box Invoker {
a: a,
b: b,
a,
b,
} as Box<dyn Invokable<A>+'static>
}

Expand Down
Loading