]> git.lizzy.rs Git - rust.git/blob - clippy_lints/src/nonstandard_macro_braces.rs
Rollup merge of #87069 - sexxi-goose:copy_ref_always, r=nikomatsakis
[rust.git] / clippy_lints / src / nonstandard_macro_braces.rs
1 use std::{
2     fmt,
3     hash::{Hash, Hasher},
4 };
5
6 use clippy_utils::{diagnostics::span_lint_and_help, in_macro, is_direct_expn_of, source::snippet_opt};
7 use if_chain::if_chain;
8 use rustc_ast::ast;
9 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
10 use rustc_lint::{EarlyContext, EarlyLintPass};
11 use rustc_session::{declare_tool_lint, impl_lint_pass};
12 use rustc_span::Span;
13 use serde::{de, Deserialize};
14
15 declare_clippy_lint! {
16     /// **What it does:** Checks that common macros are used with consistent bracing.
17     ///
18     /// **Why is this bad?** This is mostly a consistency lint although using () or []
19     /// doesn't give you a semicolon in item position, which can be unexpected.
20     ///
21     /// **Known problems:**
22     /// None
23     ///
24     /// **Example:**
25     ///
26     /// ```rust
27     /// vec!{1, 2, 3};
28     /// ```
29     /// Use instead:
30     /// ```rust
31     /// vec![1, 2, 3];
32     /// ```
33     pub NONSTANDARD_MACRO_BRACES,
34     nursery,
35     "check consistent use of braces in macro"
36 }
37
38 const BRACES: &[(&str, &str)] = &[("(", ")"), ("{", "}"), ("[", "]")];
39
40 /// The (name, (open brace, close brace), source snippet)
41 type MacroInfo<'a> = (&'a str, &'a (String, String), String);
42
43 #[derive(Clone, Debug, Default)]
44 pub struct MacroBraces {
45     macro_braces: FxHashMap<String, (String, String)>,
46     done: FxHashSet<Span>,
47 }
48
49 impl MacroBraces {
50     pub fn new(conf: &FxHashSet<MacroMatcher>) -> Self {
51         let macro_braces = macro_braces(conf.clone());
52         Self {
53             macro_braces,
54             done: FxHashSet::default(),
55         }
56     }
57 }
58
59 impl_lint_pass!(MacroBraces => [NONSTANDARD_MACRO_BRACES]);
60
61 impl EarlyLintPass for MacroBraces {
62     fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
63         if let Some((name, braces, snip)) = is_offending_macro(cx, item.span, self) {
64             let span = item.span.ctxt().outer_expn_data().call_site;
65             emit_help(cx, snip, braces, name, span);
66             self.done.insert(span);
67         }
68     }
69
70     fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
71         if let Some((name, braces, snip)) = is_offending_macro(cx, stmt.span, self) {
72             let span = stmt.span.ctxt().outer_expn_data().call_site;
73             emit_help(cx, snip, braces, name, span);
74             self.done.insert(span);
75         }
76     }
77
78     fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
79         if let Some((name, braces, snip)) = is_offending_macro(cx, expr.span, self) {
80             let span = expr.span.ctxt().outer_expn_data().call_site;
81             emit_help(cx, snip, braces, name, span);
82             self.done.insert(span);
83         }
84     }
85
86     fn check_ty(&mut self, cx: &EarlyContext<'_>, ty: &ast::Ty) {
87         if let Some((name, braces, snip)) = is_offending_macro(cx, ty.span, self) {
88             let span = ty.span.ctxt().outer_expn_data().call_site;
89             emit_help(cx, snip, braces, name, span);
90             self.done.insert(span);
91         }
92     }
93 }
94
95 fn is_offending_macro<'a>(cx: &EarlyContext<'_>, span: Span, mac_braces: &'a MacroBraces) -> Option<MacroInfo<'a>> {
96     if_chain! {
97         if in_macro(span);
98         if let Some((name, braces)) = find_matching_macro(span, &mac_braces.macro_braces);
99         if let Some(snip) = snippet_opt(cx, span.ctxt().outer_expn_data().call_site);
100         // we must check only invocation sites
101         // https://github.com/rust-lang/rust-clippy/issues/7422
102         if snip.starts_with(name);
103         // make formatting consistent
104         let c = snip.replace(" ", "");
105         if !c.starts_with(&format!("{}!{}", name, braces.0));
106         if !mac_braces.done.contains(&span.ctxt().outer_expn_data().call_site);
107         then {
108             Some((name, braces, snip))
109         } else {
110             None
111         }
112     }
113 }
114
115 fn emit_help(cx: &EarlyContext<'_>, snip: String, braces: &(String, String), name: &str, span: Span) {
116     let with_space = &format!("! {}", braces.0);
117     let without_space = &format!("!{}", braces.0);
118     let mut help = snip;
119     for b in BRACES.iter().filter(|b| b.0 != braces.0) {
120         help = help.replace(b.0, &braces.0).replace(b.1, &braces.1);
121         // Only `{` traditionally has space before the brace
122         if braces.0 != "{" && help.contains(with_space) {
123             help = help.replace(with_space, without_space);
124         } else if braces.0 == "{" && help.contains(without_space) {
125             help = help.replace(without_space, with_space);
126         }
127     }
128     span_lint_and_help(
129         cx,
130         NONSTANDARD_MACRO_BRACES,
131         span,
132         &format!("use of irregular braces for `{}!` macro", name),
133         Some(span),
134         &format!("consider writing `{}`", help),
135     );
136 }
137
138 fn find_matching_macro(
139     span: Span,
140     braces: &FxHashMap<String, (String, String)>,
141 ) -> Option<(&String, &(String, String))> {
142     braces
143         .iter()
144         .find(|(macro_name, _)| is_direct_expn_of(span, macro_name).is_some())
145 }
146
147 fn macro_braces(conf: FxHashSet<MacroMatcher>) -> FxHashMap<String, (String, String)> {
148     let mut braces = vec![
149         macro_matcher!(
150             name: "print",
151             braces: ("(", ")"),
152         ),
153         macro_matcher!(
154             name: "println",
155             braces: ("(", ")"),
156         ),
157         macro_matcher!(
158             name: "eprint",
159             braces: ("(", ")"),
160         ),
161         macro_matcher!(
162             name: "eprintln",
163             braces: ("(", ")"),
164         ),
165         macro_matcher!(
166             name: "write",
167             braces: ("(", ")"),
168         ),
169         macro_matcher!(
170             name: "writeln",
171             braces: ("(", ")"),
172         ),
173         macro_matcher!(
174             name: "format",
175             braces: ("(", ")"),
176         ),
177         macro_matcher!(
178             name: "format_args",
179             braces: ("(", ")"),
180         ),
181         macro_matcher!(
182             name: "vec",
183             braces: ("[", "]"),
184         ),
185     ]
186     .into_iter()
187     .collect::<FxHashMap<_, _>>();
188     // We want users items to override any existing items
189     for it in conf {
190         braces.insert(it.name, it.braces);
191     }
192     braces
193 }
194
195 macro_rules! macro_matcher {
196     (name: $name:expr, braces: ($open:expr, $close:expr) $(,)?) => {
197         ($name.to_owned(), ($open.to_owned(), $close.to_owned()))
198     };
199 }
200 pub(crate) use macro_matcher;
201
202 #[derive(Clone, Debug)]
203 pub struct MacroMatcher {
204     name: String,
205     braces: (String, String),
206 }
207
208 impl Hash for MacroMatcher {
209     fn hash<H: Hasher>(&self, state: &mut H) {
210         self.name.hash(state);
211     }
212 }
213
214 impl PartialEq for MacroMatcher {
215     fn eq(&self, other: &Self) -> bool {
216         self.name == other.name
217     }
218 }
219 impl Eq for MacroMatcher {}
220
221 impl<'de> Deserialize<'de> for MacroMatcher {
222     fn deserialize<D>(deser: D) -> Result<Self, D::Error>
223     where
224         D: de::Deserializer<'de>,
225     {
226         #[derive(Deserialize)]
227         #[serde(field_identifier, rename_all = "lowercase")]
228         enum Field {
229             Name,
230             Brace,
231         }
232         struct MacVisitor;
233         impl<'de> de::Visitor<'de> for MacVisitor {
234             type Value = MacroMatcher;
235
236             fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
237                 formatter.write_str("struct MacroMatcher")
238             }
239
240             fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
241             where
242                 V: de::MapAccess<'de>,
243             {
244                 let mut name = None;
245                 let mut brace: Option<&str> = None;
246                 while let Some(key) = map.next_key()? {
247                     match key {
248                         Field::Name => {
249                             if name.is_some() {
250                                 return Err(de::Error::duplicate_field("name"));
251                             }
252                             name = Some(map.next_value()?);
253                         },
254                         Field::Brace => {
255                             if brace.is_some() {
256                                 return Err(de::Error::duplicate_field("brace"));
257                             }
258                             brace = Some(map.next_value()?);
259                         },
260                     }
261                 }
262                 let name = name.ok_or_else(|| de::Error::missing_field("name"))?;
263                 let brace = brace.ok_or_else(|| de::Error::missing_field("brace"))?;
264                 Ok(MacroMatcher {
265                     name,
266                     braces: BRACES
267                         .iter()
268                         .find(|b| b.0 == brace)
269                         .map(|(o, c)| ((*o).to_owned(), (*c).to_owned()))
270                         .ok_or_else(|| {
271                             de::Error::custom(&format!("expected one of `(`, `{{`, `[` found `{}`", brace))
272                         })?,
273                 })
274             }
275         }
276
277         const FIELDS: &[&str] = &["name", "brace"];
278         deser.deserialize_struct("MacroMatcher", FIELDS, MacVisitor)
279     }
280 }