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