]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_utils/src/check_proc_macro.rs
Auto merge of #102692 - nnethercote:TokenStreamBuilder, r=Aaron1011
[rust.git] / src / tools / clippy / clippy_utils / src / check_proc_macro.rs
1 //! This module handles checking if the span given is from a proc-macro or not.
2 //!
3 //! Proc-macros are capable of setting the span of every token they output to a few possible spans.
4 //! This includes spans we can detect easily as coming from a proc-macro (e.g. the call site
5 //! or the def site), and spans we can't easily detect as such (e.g. the span of any token
6 //! passed into the proc macro). This capability means proc-macros are capable of generating code
7 //! with a span that looks like it was written by the user, but which should not be linted by clippy
8 //! as it was generated by an external macro.
9 //!
10 //! That brings us to this module. The current approach is to determine a small bit of text which
11 //! must exist at both the start and the end of an item (e.g. an expression or a path) assuming the
12 //! code was written, and check if the span contains that text. Note this will only work correctly
13 //! if the span is not from a `macro_rules` based macro.
14
15 use rustc_ast::ast::{IntTy, LitIntType, LitKind, StrStyle, UintTy};
16 use rustc_hir::{
17     intravisit::FnKind, Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, HirId,
18     Impl, ImplItem, ImplItemKind, IsAuto, Item, ItemKind, LoopSource, MatchSource, Node, QPath, TraitItem,
19     TraitItemKind, UnOp, UnsafeSource, Unsafety, Variant, VariantData, YieldSource,
20 };
21 use rustc_lint::{LateContext, LintContext};
22 use rustc_middle::ty::TyCtxt;
23 use rustc_session::Session;
24 use rustc_span::{Span, Symbol};
25 use rustc_target::spec::abi::Abi;
26
27 /// The search pattern to look for. Used by `span_matches_pat`
28 #[derive(Clone, Copy)]
29 pub enum Pat {
30     /// A single string.
31     Str(&'static str),
32     /// Any of the given strings.
33     MultiStr(&'static [&'static str]),
34     /// The string representation of the symbol.
35     Sym(Symbol),
36     /// Any decimal or hexadecimal digit depending on the location.
37     Num,
38 }
39
40 /// Checks if the start and the end of the span's text matches the patterns. This will return false
41 /// if the span crosses multiple files or if source is not available.
42 fn span_matches_pat(sess: &Session, span: Span, start_pat: Pat, end_pat: Pat) -> bool {
43     let pos = sess.source_map().lookup_byte_offset(span.lo());
44     let Some(ref src) = pos.sf.src else {
45         return false;
46     };
47     let end = span.hi() - pos.sf.start_pos;
48     src.get(pos.pos.0 as usize..end.0 as usize).map_or(false, |s| {
49         // Spans can be wrapped in a mixture or parenthesis, whitespace, and trailing commas.
50         let start_str = s.trim_start_matches(|c: char| c.is_whitespace() || c == '(');
51         let end_str = s.trim_end_matches(|c: char| c.is_whitespace() || c == ')' || c == ',');
52         (match start_pat {
53             Pat::Str(text) => start_str.starts_with(text),
54             Pat::MultiStr(texts) => texts.iter().any(|s| start_str.starts_with(s)),
55             Pat::Sym(sym) => start_str.starts_with(sym.as_str()),
56             Pat::Num => start_str.as_bytes().first().map_or(false, u8::is_ascii_digit),
57         } && match end_pat {
58             Pat::Str(text) => end_str.ends_with(text),
59             Pat::MultiStr(texts) => texts.iter().any(|s| start_str.ends_with(s)),
60             Pat::Sym(sym) => end_str.ends_with(sym.as_str()),
61             Pat::Num => end_str.as_bytes().last().map_or(false, u8::is_ascii_hexdigit),
62         })
63     })
64 }
65
66 /// Get the search patterns to use for the given literal
67 fn lit_search_pat(lit: &LitKind) -> (Pat, Pat) {
68     match lit {
69         LitKind::Str(_, StrStyle::Cooked) => (Pat::Str("\""), Pat::Str("\"")),
70         LitKind::Str(_, StrStyle::Raw(0)) => (Pat::Str("r"), Pat::Str("\"")),
71         LitKind::Str(_, StrStyle::Raw(_)) => (Pat::Str("r#"), Pat::Str("#")),
72         LitKind::ByteStr(_) => (Pat::Str("b\""), Pat::Str("\"")),
73         LitKind::Byte(_) => (Pat::Str("b'"), Pat::Str("'")),
74         LitKind::Char(_) => (Pat::Str("'"), Pat::Str("'")),
75         LitKind::Int(_, LitIntType::Signed(IntTy::Isize)) => (Pat::Num, Pat::Str("isize")),
76         LitKind::Int(_, LitIntType::Unsigned(UintTy::Usize)) => (Pat::Num, Pat::Str("usize")),
77         LitKind::Int(..) => (Pat::Num, Pat::Num),
78         LitKind::Float(..) => (Pat::Num, Pat::Str("")),
79         LitKind::Bool(true) => (Pat::Str("true"), Pat::Str("true")),
80         LitKind::Bool(false) => (Pat::Str("false"), Pat::Str("false")),
81         _ => (Pat::Str(""), Pat::Str("")),
82     }
83 }
84
85 /// Get the search patterns to use for the given path
86 fn qpath_search_pat(path: &QPath<'_>) -> (Pat, Pat) {
87     match path {
88         QPath::Resolved(ty, path) => {
89             let start = if ty.is_some() {
90                 Pat::Str("<")
91             } else {
92                 path.segments
93                     .first()
94                     .map_or(Pat::Str(""), |seg| Pat::Sym(seg.ident.name))
95             };
96             let end = path.segments.last().map_or(Pat::Str(""), |seg| {
97                 if seg.args.is_some() {
98                     Pat::Str(">")
99                 } else {
100                     Pat::Sym(seg.ident.name)
101                 }
102             });
103             (start, end)
104         },
105         QPath::TypeRelative(_, name) => (Pat::Str(""), Pat::Sym(name.ident.name)),
106         QPath::LangItem(..) => (Pat::Str(""), Pat::Str("")),
107     }
108 }
109
110 /// Get the search patterns to use for the given expression
111 fn expr_search_pat(tcx: TyCtxt<'_>, e: &Expr<'_>) -> (Pat, Pat) {
112     match e.kind {
113         ExprKind::Box(e) => (Pat::Str("box"), expr_search_pat(tcx, e).1),
114         ExprKind::ConstBlock(_) => (Pat::Str("const"), Pat::Str("}")),
115         ExprKind::Tup([]) => (Pat::Str(")"), Pat::Str("(")),
116         ExprKind::Unary(UnOp::Deref, e) => (Pat::Str("*"), expr_search_pat(tcx, e).1),
117         ExprKind::Unary(UnOp::Not, e) => (Pat::Str("!"), expr_search_pat(tcx, e).1),
118         ExprKind::Unary(UnOp::Neg, e) => (Pat::Str("-"), expr_search_pat(tcx, e).1),
119         ExprKind::Lit(ref lit) => lit_search_pat(&lit.node),
120         ExprKind::Array(_) | ExprKind::Repeat(..) => (Pat::Str("["), Pat::Str("]")),
121         ExprKind::Call(e, []) | ExprKind::MethodCall(_, e, [], _) => (expr_search_pat(tcx, e).0, Pat::Str("(")),
122         ExprKind::Call(first, [.., last])
123         | ExprKind::MethodCall(_, first, [.., last], _)
124         | ExprKind::Binary(_, first, last)
125         | ExprKind::Tup([first, .., last])
126         | ExprKind::Assign(first, last, _)
127         | ExprKind::AssignOp(_, first, last) => (expr_search_pat(tcx, first).0, expr_search_pat(tcx, last).1),
128         ExprKind::Tup([e]) | ExprKind::DropTemps(e) => expr_search_pat(tcx, e),
129         ExprKind::Cast(e, _) | ExprKind::Type(e, _) => (expr_search_pat(tcx, e).0, Pat::Str("")),
130         ExprKind::Let(let_expr) => (Pat::Str("let"), expr_search_pat(tcx, let_expr.init).1),
131         ExprKind::If(..) => (Pat::Str("if"), Pat::Str("}")),
132         ExprKind::Loop(_, Some(_), _, _) | ExprKind::Block(_, Some(_)) => (Pat::Str("'"), Pat::Str("}")),
133         ExprKind::Loop(_, None, LoopSource::Loop, _) => (Pat::Str("loop"), Pat::Str("}")),
134         ExprKind::Loop(_, None, LoopSource::While, _) => (Pat::Str("while"), Pat::Str("}")),
135         ExprKind::Loop(_, None, LoopSource::ForLoop, _) | ExprKind::Match(_, _, MatchSource::ForLoopDesugar) => {
136             (Pat::Str("for"), Pat::Str("}"))
137         },
138         ExprKind::Match(_, _, MatchSource::Normal) => (Pat::Str("match"), Pat::Str("}")),
139         ExprKind::Match(e, _, MatchSource::TryDesugar) => (expr_search_pat(tcx, e).0, Pat::Str("?")),
140         ExprKind::Match(e, _, MatchSource::AwaitDesugar) | ExprKind::Yield(e, YieldSource::Await { .. }) => {
141             (expr_search_pat(tcx, e).0, Pat::Str("await"))
142         },
143         ExprKind::Closure(&Closure { body, .. }) => (Pat::Str(""), expr_search_pat(tcx, tcx.hir().body(body).value).1),
144         ExprKind::Block(
145             Block {
146                 rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided),
147                 ..
148             },
149             None,
150         ) => (Pat::Str("unsafe"), Pat::Str("}")),
151         ExprKind::Block(_, None) => (Pat::Str("{"), Pat::Str("}")),
152         ExprKind::Field(e, name) => (expr_search_pat(tcx, e).0, Pat::Sym(name.name)),
153         ExprKind::Index(e, _) => (expr_search_pat(tcx, e).0, Pat::Str("]")),
154         ExprKind::Path(ref path) => qpath_search_pat(path),
155         ExprKind::AddrOf(_, _, e) => (Pat::Str("&"), expr_search_pat(tcx, e).1),
156         ExprKind::Break(Destination { label: None, .. }, None) => (Pat::Str("break"), Pat::Str("break")),
157         ExprKind::Break(Destination { label: Some(name), .. }, None) => (Pat::Str("break"), Pat::Sym(name.ident.name)),
158         ExprKind::Break(_, Some(e)) => (Pat::Str("break"), expr_search_pat(tcx, e).1),
159         ExprKind::Continue(Destination { label: None, .. }) => (Pat::Str("continue"), Pat::Str("continue")),
160         ExprKind::Continue(Destination { label: Some(name), .. }) => (Pat::Str("continue"), Pat::Sym(name.ident.name)),
161         ExprKind::Ret(None) => (Pat::Str("return"), Pat::Str("return")),
162         ExprKind::Ret(Some(e)) => (Pat::Str("return"), expr_search_pat(tcx, e).1),
163         ExprKind::Struct(path, _, _) => (qpath_search_pat(path).0, Pat::Str("}")),
164         ExprKind::Yield(e, YieldSource::Yield) => (Pat::Str("yield"), expr_search_pat(tcx, e).1),
165         _ => (Pat::Str(""), Pat::Str("")),
166     }
167 }
168
169 fn fn_header_search_pat(header: FnHeader) -> Pat {
170     if header.is_async() {
171         Pat::Str("async")
172     } else if header.is_const() {
173         Pat::Str("const")
174     } else if header.is_unsafe() {
175         Pat::Str("unsafe")
176     } else if header.abi != Abi::Rust {
177         Pat::Str("extern")
178     } else {
179         Pat::MultiStr(&["fn", "extern"])
180     }
181 }
182
183 fn item_search_pat(item: &Item<'_>) -> (Pat, Pat) {
184     let (start_pat, end_pat) = match &item.kind {
185         ItemKind::ExternCrate(_) => (Pat::Str("extern"), Pat::Str(";")),
186         ItemKind::Static(..) => (Pat::Str("static"), Pat::Str(";")),
187         ItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
188         ItemKind::Fn(sig, ..) => (fn_header_search_pat(sig.header), Pat::Str("")),
189         ItemKind::ForeignMod { .. } => (Pat::Str("extern"), Pat::Str("}")),
190         ItemKind::TyAlias(..) | ItemKind::OpaqueTy(_) => (Pat::Str("type"), Pat::Str(";")),
191         ItemKind::Enum(..) => (Pat::Str("enum"), Pat::Str("}")),
192         ItemKind::Struct(VariantData::Struct(..), _) => (Pat::Str("struct"), Pat::Str("}")),
193         ItemKind::Struct(..) => (Pat::Str("struct"), Pat::Str(";")),
194         ItemKind::Union(..) => (Pat::Str("union"), Pat::Str("}")),
195         ItemKind::Trait(_, Unsafety::Unsafe, ..)
196         | ItemKind::Impl(Impl {
197             unsafety: Unsafety::Unsafe,
198             ..
199         }) => (Pat::Str("unsafe"), Pat::Str("}")),
200         ItemKind::Trait(IsAuto::Yes, ..) => (Pat::Str("auto"), Pat::Str("}")),
201         ItemKind::Trait(..) => (Pat::Str("trait"), Pat::Str("}")),
202         ItemKind::Impl(_) => (Pat::Str("impl"), Pat::Str("}")),
203         _ => return (Pat::Str(""), Pat::Str("")),
204     };
205     if item.vis_span.is_empty() {
206         (start_pat, end_pat)
207     } else {
208         (Pat::Str("pub"), end_pat)
209     }
210 }
211
212 fn trait_item_search_pat(item: &TraitItem<'_>) -> (Pat, Pat) {
213     match &item.kind {
214         TraitItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
215         TraitItemKind::Type(..) => (Pat::Str("type"), Pat::Str(";")),
216         TraitItemKind::Fn(sig, ..) => (fn_header_search_pat(sig.header), Pat::Str("")),
217     }
218 }
219
220 fn impl_item_search_pat(item: &ImplItem<'_>) -> (Pat, Pat) {
221     let (start_pat, end_pat) = match &item.kind {
222         ImplItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
223         ImplItemKind::Type(..) => (Pat::Str("type"), Pat::Str(";")),
224         ImplItemKind::Fn(sig, ..) => (fn_header_search_pat(sig.header), Pat::Str("")),
225     };
226     if item.vis_span.is_empty() {
227         (start_pat, end_pat)
228     } else {
229         (Pat::Str("pub"), end_pat)
230     }
231 }
232
233 fn field_def_search_pat(def: &FieldDef<'_>) -> (Pat, Pat) {
234     if def.vis_span.is_empty() {
235         if def.is_positional() {
236             (Pat::Str(""), Pat::Str(""))
237         } else {
238             (Pat::Sym(def.ident.name), Pat::Str(""))
239         }
240     } else {
241         (Pat::Str("pub"), Pat::Str(""))
242     }
243 }
244
245 fn variant_search_pat(v: &Variant<'_>) -> (Pat, Pat) {
246     match v.data {
247         VariantData::Struct(..) => (Pat::Sym(v.ident.name), Pat::Str("}")),
248         VariantData::Tuple(..) => (Pat::Sym(v.ident.name), Pat::Str("")),
249         VariantData::Unit(..) => (Pat::Sym(v.ident.name), Pat::Sym(v.ident.name)),
250     }
251 }
252
253 fn fn_kind_pat(tcx: TyCtxt<'_>, kind: &FnKind<'_>, body: &Body<'_>, hir_id: HirId) -> (Pat, Pat) {
254     let (start_pat, end_pat) = match kind {
255         FnKind::ItemFn(.., header) => (fn_header_search_pat(*header), Pat::Str("")),
256         FnKind::Method(.., sig) => (fn_header_search_pat(sig.header), Pat::Str("")),
257         FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, body.value).1),
258     };
259     let start_pat = match tcx.hir().get(hir_id) {
260         Node::Item(Item { vis_span, .. }) | Node::ImplItem(ImplItem { vis_span, .. }) => {
261             if vis_span.is_empty() {
262                 start_pat
263             } else {
264                 Pat::Str("pub")
265             }
266         },
267         Node::TraitItem(_) => start_pat,
268         _ => Pat::Str(""),
269     };
270     (start_pat, end_pat)
271 }
272
273 pub trait WithSearchPat {
274     type Context: LintContext;
275     fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat);
276     fn span(&self) -> Span;
277 }
278 macro_rules! impl_with_search_pat {
279     ($cx:ident: $ty:ident with $fn:ident $(($tcx:ident))?) => {
280         impl<'cx> WithSearchPat for $ty<'cx> {
281             type Context = $cx<'cx>;
282             #[allow(unused_variables)]
283             fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat) {
284                 $(let $tcx = cx.tcx;)?
285                 $fn($($tcx,)? self)
286             }
287             fn span(&self) -> Span {
288                 self.span
289             }
290         }
291     };
292 }
293 impl_with_search_pat!(LateContext: Expr with expr_search_pat(tcx));
294 impl_with_search_pat!(LateContext: Item with item_search_pat);
295 impl_with_search_pat!(LateContext: TraitItem with trait_item_search_pat);
296 impl_with_search_pat!(LateContext: ImplItem with impl_item_search_pat);
297 impl_with_search_pat!(LateContext: FieldDef with field_def_search_pat);
298 impl_with_search_pat!(LateContext: Variant with variant_search_pat);
299
300 impl<'cx> WithSearchPat for (&FnKind<'cx>, &Body<'cx>, HirId, Span) {
301     type Context = LateContext<'cx>;
302
303     fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat) {
304         fn_kind_pat(cx.tcx, self.0, self.1, self.2)
305     }
306
307     fn span(&self) -> Span {
308         self.3
309     }
310 }
311
312 /// Checks if the item likely came from a proc-macro.
313 ///
314 /// This should be called after `in_external_macro` and the initial pattern matching of the ast as
315 /// it is significantly slower than both of those.
316 pub fn is_from_proc_macro<T: WithSearchPat>(cx: &T::Context, item: &T) -> bool {
317     let (start_pat, end_pat) = item.search_pat(cx);
318     !span_matches_pat(cx.sess(), item.span(), start_pat, end_pat)
319 }
320
321 /// Checks if the span actually refers to a match expression
322 pub fn is_span_match(cx: &impl LintContext, span: Span) -> bool {
323     span_matches_pat(cx.sess(), span, Pat::Str("match"), Pat::Str("}"))
324 }
325
326 /// Checks if the span actually refers to an if expression
327 pub fn is_span_if(cx: &impl LintContext, span: Span) -> bool {
328     span_matches_pat(cx.sess(), span, Pat::Str("if"), Pat::Str("}"))
329 }