Skip to content

Implement VEC_NEW internal lint #62678

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 3 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
4 changes: 2 additions & 2 deletions src/librustc/cfg/construct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,8 @@ pub fn construct(tcx: TyCtxt<'_>, body: &hir::Body) -> CFG {
tables,
graph,
fn_exit,
loop_scopes: Vec::new(),
breakable_block_scopes: Vec::new(),
loop_scopes: vec![],
breakable_block_scopes: vec![],
};
body_exit = cfg_builder.expr(&body.value, entry);
cfg_builder.add_contained_edge(body_exit, fn_exit);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/dep_graph/graph.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ impl DepGraph {
pub fn query(&self) -> DepGraphQuery {
let current_dep_graph = self.data.as_ref().unwrap().current.borrow();
let nodes: Vec<_> = current_dep_graph.data.iter().map(|n| n.node).collect();
let mut edges = Vec::new();
let mut edges = vec![];
for (from, edge_targets) in current_dep_graph.data.iter()
.map(|d| (d.node, &d.edges)) {
for &edge_target in edge_targets.iter() {
Expand Down
24 changes: 12 additions & 12 deletions src/librustc/hir/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -251,10 +251,10 @@ pub fn lower_crate(
bodies: BTreeMap::new(),
trait_impls: BTreeMap::new(),
modules: BTreeMap::new(),
exported_macros: Vec::new(),
non_exported_macro_attrs: Vec::new(),
catch_scopes: Vec::new(),
loop_scopes: Vec::new(),
exported_macros: vec![],
non_exported_macro_attrs: vec![],
catch_scopes: vec![],
loop_scopes: vec![],
is_in_loop_condition: false,
is_in_trait_impl: false,
is_in_dyn_type: false,
Expand All @@ -266,9 +266,9 @@ pub fn lower_crate(
node_id_to_hir_id: IndexVec::new(),
generator_kind: None,
current_item: None,
lifetimes_to_define: Vec::new(),
lifetimes_to_define: vec![],
is_collecting_in_band_lifetimes: false,
in_scope_lifetimes: Vec::new(),
in_scope_lifetimes: vec![],
allow_try_trait: Some([sym::try_trait][..].into()),
allow_gen_future: Some([sym::gen_future][..].into()),
}.lower_crate(krate)
Expand Down Expand Up @@ -1093,7 +1093,7 @@ impl<'a> LoweringContext<'a> {
&generics.params,
|this| {
this.collect_in_band_defs(parent_id, anonymous_lifetime_mode, |this| {
let mut params = Vec::new();
let mut params = vec![];
// Note: it is necessary to lower generics *before* calling `f`.
// When lowering `async fn`, there's a final step when lowering
// the return type that assumes that all in-scope lifetimes have
Expand Down Expand Up @@ -1954,10 +1954,10 @@ impl<'a> LoweringContext<'a> {
parent: parent_index,
exist_ty_id,
collect_elided_lifetimes: true,
currently_bound_lifetimes: Vec::new(),
currently_bound_lifetimes: vec![],
already_defined_lifetimes: FxHashSet::default(),
output_lifetimes: Vec::new(),
output_lifetime_params: Vec::new(),
output_lifetimes: vec![],
output_lifetime_params: vec![],
};

for bound in bounds {
Expand Down Expand Up @@ -3225,8 +3225,8 @@ impl<'a> LoweringContext<'a> {
};

self.lower_body(|this| {
let mut arguments: Vec<hir::Arg> = Vec::new();
let mut statements: Vec<hir::Stmt> = Vec::new();
let mut arguments: Vec<hir::Arg> = vec![];
let mut statements: Vec<hir::Stmt> = vec![];

// Async function arguments are lowered into the closure body so that they are
// captured and so that the drop order matches the equivalent non-async functions.
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/map/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl<'a, 'hir> NodeCollector<'a, 'hir> {
-> NodeCollector<'a, 'hir> {
let root_mod_def_path_hash = definitions.def_path_hash(CRATE_DEF_INDEX);

let mut hir_body_nodes = Vec::new();
let mut hir_body_nodes = vec![];

// Allocate `DepNode`s for the root module.
let (root_mod_sig_dep_index, root_mod_full_dep_index) = {
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/hir/map/hir_id_validator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use rustc_data_structures::sync::{Lock, ParallelIterator, par_iter};
pub fn check_crate(hir_map: &hir::map::Map<'_>) {
hir_map.dep_graph.assert_ignored();

let errors = Lock::new(Vec::new());
let errors = Lock::new(vec![]);

par_iter(&hir_map.krate().modules).for_each(|(module_id, _)| {
let local_def_id = hir_map.local_def_id_from_node_id(*module_id);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/infer/lexical_region_resolve/graphviz.rs
Original file line number Diff line number Diff line change
Expand Up @@ -257,7 +257,7 @@ fn dump_region_data_to<'a, 'tcx>(
path);
let g = ConstraintGraph::new("region_data".to_string(), region_rels, map);
debug!("dump_region_data calling render");
let mut v = Vec::new();
let mut v = vec![];
dot::render(&g, &mut v).unwrap();
fs::write(path, &v)
}
2 changes: 1 addition & 1 deletion src/librustc/infer/lexical_region_resolve/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -792,7 +792,7 @@ impl<'cx, 'tcx> LexicalResolver<'cx, 'tcx> {
let mut state = WalkState {
set: Default::default(),
stack: vec![orig_node_idx],
result: Vec::new(),
result: vec![],
dup_found: false,
};
state.set.insert(orig_node_idx);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/infer/type_variable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ impl<'tcx> TypeVariableTable<'tcx> {
/// unified `V1` with `T1`, this function would return `{T0}`.
pub fn types_escaping_snapshot(&mut self, s: &Snapshot<'tcx>) -> Vec<Ty<'tcx>> {
let mut new_elem_threshold = u32::MAX;
let mut escaping_types = Vec::new();
let mut escaping_types = vec![];
let actions_since_snapshot = self.values.actions_since_snapshot(&s.snapshot);
debug!("actions_since_snapshot.len() = {}", actions_since_snapshot.len());
for action in actions_since_snapshot {
Expand Down
52 changes: 51 additions & 1 deletion src/librustc/lint/internal.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Some lints that are only useful in the compiler or crates that use compiler internals, such as
//! Clippy.

use crate::hir::{GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind};
use crate::hir::{
Expr, GenericArg, HirId, MutTy, Mutability, Path, PathSegment, QPath, Ty, TyKind,
};
use crate::lint::{
EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintArray, LintContext, LintPass,
};
Expand Down Expand Up @@ -255,3 +257,51 @@ fn is_lint_pass_expansion(expn_info: &ExpnInfo) -> bool {
false
}
}

declare_tool_lint! {
pub rustc::VEC_NEW,
Allow,
"Using Vec::new() instead of vec![]"
}

declare_lint_pass!(VecNew => [VEC_NEW]);

const VEC_PATH: &[Symbol; 3] = &[sym::alloc, sym::vec, sym::Vec];

impl LateLintPass<'_, '_> for VecNew {
fn check_expr(&mut self, cx: &LateContext<'_, '_>, expr: &Expr) {
use crate::hir::ExprKind;
if let ExprKind::Call(func, args) = &expr.node {
if !args.is_empty() {
return;
}

if let ExprKind::Path(qpath) = &func.node {
if let QPath::TypeRelative(ty, segment) = qpath {
if segment.ident.name.as_str() == "new" {
if let TyKind::Path(ty_path) = &ty.node {
if let QPath::Resolved(_, path) = ty_path {
if let Some(def_id) = path.res.opt_def_id() {
if cx.match_def_path(def_id, VEC_PATH) {
cx.struct_span_lint(
VEC_NEW,
expr.span,
"usage of `Vec::new()`",
)
.span_suggestion(
expr.span,
"use",
"vec![]".to_string(),
Applicability::MachineApplicable,
)
.emit();
}
}
}
}
}
}
}
}
}
}
2 changes: 1 addition & 1 deletion src/librustc/lint/levels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ enum LintSet {
impl LintLevelSets {
pub fn new(sess: &Session) -> LintLevelSets {
let mut me = LintLevelSets {
list: Vec::new(),
list: vec![],
lint_cap: Level::Forbid,
};
me.process_command_line(sess);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/cstore.rs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ pub struct EncodedMetadata {
impl EncodedMetadata {
pub fn new() -> EncodedMetadata {
EncodedMetadata {
raw_data: Vec::new(),
raw_data: vec![],
}
}
}
Expand Down
6 changes: 3 additions & 3 deletions src/librustc/middle/dependency_format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList {
let sess = &tcx.sess;

if !sess.opts.output_types.should_codegen() {
return Vec::new();
return vec![];
}

let preferred_linkage = match ty {
Expand Down Expand Up @@ -128,7 +128,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList {

if preferred_linkage == Linkage::NotLinked {
// If the crate is not linked, there are no link-time dependencies.
return Vec::new();
return vec![];
}

if preferred_linkage == Linkage::Static {
Expand All @@ -151,7 +151,7 @@ fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList {
but was not found in this form",
tcx.crate_name(cnum)));
}
return Vec::new();
return vec![];
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ fn entry_fn(tcx: TyCtxt<'_>, cnum: CrateNum) -> Option<(DefId, EntryFnType)> {
main_fn: None,
attr_main_fn: None,
start_fn: None,
non_main_fns: Vec::new(),
non_main_fns: vec![],
};

tcx.hir().krate().visit_all_item_likes(&mut ctxt);
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/lang_items.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl LanguageItems {

Self {
items: vec![$(init_none($variant)),*],
missing: Vec::new(),
missing: vec![],
}
}

Expand Down
8 changes: 4 additions & 4 deletions src/librustc/middle/liveness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -269,8 +269,8 @@ impl IrMaps<'tcx> {
live_node_map: HirIdMap::default(),
variable_map: HirIdMap::default(),
capture_info_map: Default::default(),
var_kinds: Vec::new(),
lnks: Vec::new(),
var_kinds: vec![],
lnks: vec![],
}
}

Expand Down Expand Up @@ -484,7 +484,7 @@ fn visit_expr<'tcx>(ir: &mut IrMaps<'tcx>, expr: &'tcx Expr) {
// being the location that the variable is used. This results
// in better error messages than just pointing at the closure
// construction site.
let mut call_caps = Vec::new();
let mut call_caps = vec![];
let closure_def_id = ir.tcx.hir().local_def_id(expr.hir_id);
if let Some(upvars) = ir.tcx.upvars(closure_def_id) {
let parent_upvars = ir.tcx.upvars(ir.body_owner);
Expand Down Expand Up @@ -833,7 +833,7 @@ impl<'a, 'tcx> Liveness<'a, 'tcx> {

#[allow(unused_must_use)]
fn ln_str(&self, ln: LiveNode) -> String {
let mut wr = Vec::new();
let mut wr = vec![];
{
let wr = &mut wr as &mut dyn Write;
write!(wr, "[ln({:?}) of kind {:?} reads", ln.get(), self.ir.lnk(ln));
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/reachable.rs
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ fn reachable_set(tcx: TyCtxt<'_>, crate_num: CrateNum) -> ReachableSet {
tcx,
tables: &ty::TypeckTables::empty(None),
reachable_symbols: Default::default(),
worklist: Vec::new(),
worklist: vec![],
any_library,
};

Expand Down
2 changes: 1 addition & 1 deletion src/librustc/mir/traversal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ impl<'a, 'tcx> Postorder<'a, 'tcx> {
let mut po = Postorder {
body,
visited: BitSet::new_empty(body.basic_blocks().len()),
visit_stack: Vec::new(),
visit_stack: vec![],
root_is_start_block: root == START_BLOCK,
};

Expand Down
26 changes: 13 additions & 13 deletions src/librustc/session/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -597,10 +597,10 @@ pub fn host_triple() -> &'static str {
impl Default for Options {
fn default() -> Options {
Options {
crate_types: Vec::new(),
crate_types: vec![],
optimize: OptLevel::No,
debuginfo: DebugInfo::None,
lint_opts: Vec::new(),
lint_opts: vec![],
lint_cap: None,
describe_lints: false,
output_types: OutputTypes(BTreeMap::new()),
Expand All @@ -610,20 +610,20 @@ impl Default for Options {
test: false,
incremental: None,
debugging_opts: basic_debugging_options(),
prints: Vec::new(),
prints: vec![],
borrowck_mode: BorrowckMode::Migrate,
cg: basic_codegen_options(),
error_format: ErrorOutputType::default(),
externs: Externs(BTreeMap::new()),
crate_name: None,
alt_std_name: None,
libs: Vec::new(),
libs: vec![],
unstable_features: UnstableFeatures::Disallow,
debug_assertions: true,
actually_rustdoc: false,
cli_forced_codegen_units: None,
cli_forced_thinlto_off: false,
remap_path_prefix: Vec::new(),
remap_path_prefix: vec![],
edition: DEFAULT_EDITION,
}
}
Expand Down Expand Up @@ -1147,9 +1147,9 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
"select target processor (rustc --print target-cpus for details)"),
target_feature: String = (String::new(), parse_string, [TRACKED],
"target specific attributes (rustc --print target-features for details)"),
passes: Vec<String> = (Vec::new(), parse_list, [TRACKED],
passes: Vec<String> = (vec![], parse_list, [TRACKED],
"a list of extra LLVM passes to run (space separated)"),
llvm_args: Vec<String> = (Vec::new(), parse_list, [TRACKED],
llvm_args: Vec<String> = (vec![], parse_list, [TRACKED],
"a list of arguments to pass to llvm (space separated)"),
save_temps: bool = (false, parse_bool, [UNTRACKED],
"save all temporary output files during compilation"),
Expand All @@ -1175,13 +1175,13 @@ options! {CodegenOptions, CodegenSetter, basic_codegen_options,
"choose the relocation model to use (rustc --print relocation-models for details)"),
code_model: Option<String> = (None, parse_opt_string, [TRACKED],
"choose the code model to use (rustc --print code-models for details)"),
metadata: Vec<String> = (Vec::new(), parse_list, [TRACKED],
metadata: Vec<String> = (vec![], parse_list, [TRACKED],
"metadata to mangle symbol names with"),
extra_filename: String = (String::new(), parse_string, [UNTRACKED],
"extra data to put in each output filename"),
codegen_units: Option<usize> = (None, parse_opt_uint, [UNTRACKED],
"divide crate into N units to optimize in parallel"),
remark: Passes = (Passes::Some(Vec::new()), parse_passes, [UNTRACKED],
remark: Passes = (Passes::Some(vec![]), parse_passes, [UNTRACKED],
"print remarks for these optimization passes (space separated, or \"all\")"),
no_stack_check: bool = (false, parse_bool, [UNTRACKED],
"the --no-stack-check flag is deprecated and does nothing"),
Expand Down Expand Up @@ -1315,7 +1315,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
"trace and profile the queries and keys of the incremental compilation framework"),
no_analysis: bool = (false, parse_bool, [UNTRACKED],
"parse and expand the source, but run no analysis"),
extra_plugins: Vec<String> = (Vec::new(), parse_list, [TRACKED],
extra_plugins: Vec<String> = (vec![], parse_list, [TRACKED],
"load extra plugins"),
unstable_options: bool = (false, parse_bool, [UNTRACKED],
"adds unstable command line options to rustc interface"),
Expand Down Expand Up @@ -1445,7 +1445,7 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
"disables the 'leak check' for subtyping; unsound, but useful for tests"),
no_interleave_lints: bool = (false, parse_bool, [UNTRACKED],
"don't interleave execution of lints; allows benchmarking individual lints"),
crate_attr: Vec<String> = (Vec::new(), parse_string_push, [TRACKED],
crate_attr: Vec<String> = (vec![], parse_string_push, [TRACKED],
"inject the given attribute in the crate"),
self_profile: SwitchWithOptPath = (SwitchWithOptPath::Disabled,
parse_switch_with_opt_path, [UNTRACKED],
Expand Down Expand Up @@ -2152,7 +2152,7 @@ pub fn build_session_options_and_crate_config(
);
}

let mut prints = Vec::<PrintRequest>::new();
let mut prints: Vec<PrintRequest> = vec![];
if cg.target_cpu.as_ref().map_or(false, |s| s == "help") {
prints.push(PrintRequest::TargetCPUs);
cg.target_cpu = None;
Expand Down Expand Up @@ -2449,7 +2449,7 @@ pub fn build_session_options_and_crate_config(
}

pub fn parse_crate_types_from_list(list_list: Vec<String>) -> Result<Vec<CrateType>, String> {
let mut crate_types: Vec<CrateType> = Vec::new();
let mut crate_types: Vec<CrateType> = vec![];
for unparsed_crate_type in &list_list {
for part in unparsed_crate_type.split(',') {
let new_part = match part {
Expand Down
Loading