1 use clippy_utils::diagnostics::span_lint_and_then;
2 use clippy_utils::higher::VecArgs;
3 use clippy_utils::last_path_segment;
4 use clippy_utils::macros::root_macro_call_first_node;
5 use clippy_utils::source::{indent_of, snippet};
6 use rustc_errors::Applicability;
7 use rustc_hir::{Expr, ExprKind, QPath, TyKind};
8 use rustc_lint::{LateContext, LateLintPass};
9 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 use rustc_span::{sym, Span, Symbol};
12 declare_clippy_lint! {
14 /// Checks for `Arc::new` or `Rc::new` in `vec![elem; len]`
16 /// ### Why is this bad?
17 /// This will create `elem` once and clone it `len` times - doing so with `Arc` or `Rc`
18 /// is a bit misleading, as it will create references to the same pointer, rather
19 /// than different instances.
23 /// let v = vec![std::sync::Arc::new("some data".to_string()); 100];
25 /// let v = vec![std::rc::Rc::new("some data".to_string()); 100];
30 /// // Initialize each value separately:
31 /// let mut data = Vec::with_capacity(100);
33 /// data.push(std::rc::Rc::new("some data".to_string()));
36 /// // Or if you want clones of the same reference,
37 /// // Create the reference beforehand to clarify that
38 /// // it should be cloned for each value
39 /// let data = std::rc::Rc::new("some data".to_string());
40 /// let v = vec![data; 100];
42 #[clippy::version = "1.62.0"]
43 pub RC_CLONE_IN_VEC_INIT,
45 "initializing `Arc` or `Rc` in `vec![elem; len]`"
47 declare_lint_pass!(RcCloneInVecInit => [RC_CLONE_IN_VEC_INIT]);
49 impl LateLintPass<'_> for RcCloneInVecInit {
50 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &Expr<'_>) {
51 let Some(macro_call) = root_macro_call_first_node(cx, expr) else { return; };
52 let Some(VecArgs::Repeat(elem, len)) = VecArgs::hir(cx, expr) else { return; };
53 let Some(symbol) = new_reference_call(cx, elem) else { return; };
55 emit_lint(cx, symbol, macro_call.span, elem, len);
59 fn elem_snippet(cx: &LateContext<'_>, elem: &Expr<'_>, symbol_name: &str) -> String {
60 let elem_snippet = snippet(cx, elem.span, "..").to_string();
61 if elem_snippet.contains('\n') {
62 // This string must be found in `elem_snippet`, otherwise we won't be constructing
63 // the snippet in the first place.
64 let reference_creation = format!("{symbol_name}::new");
65 let (code_until_reference_creation, _right) = elem_snippet.split_once(&reference_creation).unwrap();
67 return format!("{code_until_reference_creation}{reference_creation}(..)");
73 fn loop_init_suggestion(elem: &str, len: &str, indent: &str) -> String {
76 {indent} let mut v = Vec::with_capacity({len});
77 {indent} (0..{len}).for_each(|_| v.push({elem}));
83 fn extract_suggestion(elem: &str, len: &str, indent: &str) -> String {
86 {indent} let data = {elem};
87 {indent} vec![data; {len}]
92 fn emit_lint(cx: &LateContext<'_>, symbol: Symbol, lint_span: Span, elem: &Expr<'_>, len: &Expr<'_>) {
93 let symbol_name = symbol.as_str();
99 &format!("calling `{symbol_name}::new` in `vec![elem; len]`"),
101 let len_snippet = snippet(cx, len.span, "..");
102 let elem_snippet = elem_snippet(cx, elem, symbol_name);
103 let indentation = " ".repeat(indent_of(cx, lint_span).unwrap_or(0));
104 let loop_init_suggestion = loop_init_suggestion(&elem_snippet, len_snippet.as_ref(), &indentation);
105 let extract_suggestion = extract_suggestion(&elem_snippet, len_snippet.as_ref(), &indentation);
107 diag.note(format!("each element will point to the same `{symbol_name}` instance"));
108 diag.span_suggestion(
110 format!("consider initializing each `{symbol_name}` element individually"),
111 loop_init_suggestion,
112 Applicability::Unspecified,
114 diag.span_suggestion(
117 "or if this is intentional, consider extracting the `{symbol_name}` initialization to a variable"
120 Applicability::Unspecified,
126 /// Checks whether the given `expr` is a call to `Arc::new` or `Rc::new`
127 fn new_reference_call(cx: &LateContext<'_>, expr: &Expr<'_>) -> Option<Symbol> {
129 if let ExprKind::Call(func, _args) = expr.kind;
130 if let ExprKind::Path(ref func_path @ QPath::TypeRelative(ty, _)) = func.kind;
131 if let TyKind::Path(ref ty_path) = ty.kind;
132 if let Some(def_id) = cx.qpath_res(ty_path, ty.hir_id).opt_def_id();
133 if last_path_segment(func_path).ident.name == sym::new;
136 return cx.tcx.get_diagnostic_name(def_id).filter(|symbol| symbol == &sym::Arc || symbol == &sym::Rc);