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