1use rustc_abi::ExternAbi;
16use rustc_ast as ast;
17use rustc_ast::AttrStyle;
18use rustc_ast::ast::{
19 AttrKind, Attribute, GenericArgs, IntTy, LitIntType, LitKind, StrStyle, TraitObjectSyntax, UintTy,
20};
21use rustc_ast::token::CommentKind;
22use rustc_hir::intravisit::FnKind;
23use rustc_hir::{
24 Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, HirId, Impl,
25 ImplItem, ImplItemImplKind, ImplItemKind, IsAuto, Item, ItemKind, Lit, LoopSource, MatchSource, MutTy, Node, Path,
26 QPath, Safety, TraitImplHeader, TraitItem, TraitItemKind, Ty, TyKind, UnOp, UnsafeSource, Variant, VariantData,
27 YieldSource,
28};
29use rustc_lint::{EarlyContext, LateContext, LintContext};
30use rustc_middle::ty::TyCtxt;
31use rustc_session::Session;
32use rustc_span::symbol::{Ident, kw};
33use rustc_span::{Span, Symbol, sym};
34
35#[derive(Clone)]
37pub enum Pat {
38 Str(&'static str),
40 MultiStr(&'static [&'static str]),
42 OwnedMultiStr(Vec<String>),
44 Sym(Symbol),
46 Num,
48}
49
50fn span_matches_pat(sess: &Session, span: Span, start_pat: Pat, end_pat: Pat) -> bool {
53 let pos = sess.source_map().lookup_byte_offset(span.lo());
54 let Some(ref src) = pos.sf.src else {
55 return false;
56 };
57 let end = span.hi() - pos.sf.start_pos;
58 src.get(pos.pos.0 as usize..end.0 as usize).is_some_and(|s| {
59 let start_str = s.trim_start_matches(|c: char| c.is_whitespace() || c == '(');
61 let end_str = s.trim_end_matches(|c: char| c.is_whitespace() || c == ')' || c == ',');
62 (match start_pat {
63 Pat::Str(text) => start_str.starts_with(text),
64 Pat::MultiStr(texts) => texts.iter().any(|s| start_str.starts_with(s)),
65 Pat::OwnedMultiStr(texts) => texts.iter().any(|s| start_str.starts_with(s)),
66 Pat::Sym(sym) => start_str.starts_with(sym.as_str()),
67 Pat::Num => start_str.as_bytes().first().is_some_and(u8::is_ascii_digit),
68 } && match end_pat {
69 Pat::Str(text) => end_str.ends_with(text),
70 Pat::MultiStr(texts) => texts.iter().any(|s| end_str.ends_with(s)),
71 Pat::OwnedMultiStr(texts) => texts.iter().any(|s| end_str.ends_with(s)),
72 Pat::Sym(sym) => end_str.ends_with(sym.as_str()),
73 Pat::Num => end_str.as_bytes().last().is_some_and(u8::is_ascii_hexdigit),
74 })
75 })
76}
77
78fn lit_search_pat(lit: &LitKind) -> (Pat, Pat) {
80 match lit {
81 LitKind::Str(_, StrStyle::Cooked) => (Pat::Str("\""), Pat::Str("\"")),
82 LitKind::Str(_, StrStyle::Raw(0)) => (Pat::Str("r"), Pat::Str("\"")),
83 LitKind::Str(_, StrStyle::Raw(_)) => (Pat::Str("r#"), Pat::Str("#")),
84 LitKind::ByteStr(_, StrStyle::Cooked) => (Pat::Str("b\""), Pat::Str("\"")),
85 LitKind::ByteStr(_, StrStyle::Raw(0)) => (Pat::Str("br\""), Pat::Str("\"")),
86 LitKind::ByteStr(_, StrStyle::Raw(_)) => (Pat::Str("br#\""), Pat::Str("#")),
87 LitKind::Byte(_) => (Pat::Str("b'"), Pat::Str("'")),
88 LitKind::Char(_) => (Pat::Str("'"), Pat::Str("'")),
89 LitKind::Int(_, LitIntType::Signed(IntTy::Isize)) => (Pat::Num, Pat::Str("isize")),
90 LitKind::Int(_, LitIntType::Unsigned(UintTy::Usize)) => (Pat::Num, Pat::Str("usize")),
91 LitKind::Int(..) => (Pat::Num, Pat::Num),
92 LitKind::Float(..) => (Pat::Num, Pat::Str("")),
93 LitKind::Bool(true) => (Pat::Str("true"), Pat::Str("true")),
94 LitKind::Bool(false) => (Pat::Str("false"), Pat::Str("false")),
95 _ => (Pat::Str(""), Pat::Str("")),
96 }
97}
98
99fn qpath_search_pat(path: &QPath<'_>) -> (Pat, Pat) {
101 match path {
102 QPath::Resolved(ty, path) => {
103 let start = if ty.is_some() {
104 Pat::Str("<")
105 } else {
106 path.segments.first().map_or(Pat::Str(""), |seg| {
107 if seg.ident.name == kw::PathRoot {
108 Pat::Str("::")
109 } else {
110 Pat::Sym(seg.ident.name)
111 }
112 })
113 };
114 let end = path.segments.last().map_or(Pat::Str(""), |seg| {
115 if seg.args.is_some() {
116 Pat::Str(">")
117 } else {
118 Pat::Sym(seg.ident.name)
119 }
120 });
121 (start, end)
122 },
123 QPath::TypeRelative(_, name) => (Pat::Str(""), Pat::Sym(name.ident.name)),
124 }
125}
126
127fn path_search_pat(path: &Path<'_>) -> (Pat, Pat) {
128 let (head, tail) = match path.segments {
129 [] => return (Pat::Str(""), Pat::Str("")),
130 [p] => (Pat::Sym(p.ident.name), p),
131 [.., tail] => (Pat::Str(""), tail),
134 };
135 (
136 head,
137 if tail.args.is_some() {
138 Pat::Str(">")
139 } else {
140 Pat::Sym(tail.ident.name)
141 },
142 )
143}
144
145fn expr_search_pat(tcx: TyCtxt<'_>, e: &Expr<'_>) -> (Pat, Pat) {
147 fn expr_search_pat_inner(tcx: TyCtxt<'_>, e: &Expr<'_>, outer_span: Span) -> (Pat, Pat) {
148 if !e.span.eq_ctxt(outer_span) {
154 return (Pat::Str(""), Pat::Str(""));
155 }
156
157 match e.kind {
158 ExprKind::ConstBlock(_) => (Pat::Str("const"), Pat::Str("}")),
159 ExprKind::Tup([]) => (Pat::Str(")"), Pat::Str("(")),
162 ExprKind::Unary(UnOp::Deref, e) => (Pat::Str("*"), expr_search_pat_inner(tcx, e, outer_span).1),
163 ExprKind::Unary(UnOp::Not, e) => (Pat::Str("!"), expr_search_pat_inner(tcx, e, outer_span).1),
164 ExprKind::Unary(UnOp::Neg, e) => (Pat::Str("-"), expr_search_pat_inner(tcx, e, outer_span).1),
165 ExprKind::Lit(lit) => lit_search_pat(&lit.node),
166 ExprKind::Array(_) | ExprKind::Repeat(..) => (Pat::Str("["), Pat::Str("]")),
167 ExprKind::Call(e, []) | ExprKind::MethodCall(_, e, [], _) => {
168 (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Str("("))
169 },
170 ExprKind::Call(first, [.., last])
171 | ExprKind::MethodCall(_, first, [.., last], _)
172 | ExprKind::Binary(_, first, last)
173 | ExprKind::Tup([first, .., last])
174 | ExprKind::Assign(first, last, _)
175 | ExprKind::AssignOp(_, first, last) => (
176 expr_search_pat_inner(tcx, first, outer_span).0,
177 expr_search_pat_inner(tcx, last, outer_span).1,
178 ),
179 ExprKind::Tup([e]) | ExprKind::DropTemps(e) => expr_search_pat_inner(tcx, e, outer_span),
180 ExprKind::Cast(e, _) | ExprKind::Type(e, _) => (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Str("")),
181 ExprKind::Let(let_expr) => (Pat::Str("let"), expr_search_pat_inner(tcx, let_expr.init, outer_span).1),
182 ExprKind::If(..) => (Pat::Str("if"), Pat::Str("}")),
183 ExprKind::Loop(_, Some(_), _, _) | ExprKind::Block(_, Some(_)) => (Pat::Str("'"), Pat::Str("}")),
184 ExprKind::Loop(_, None, LoopSource::Loop, _) => (Pat::Str("loop"), Pat::Str("}")),
185 ExprKind::Loop(_, None, LoopSource::While, _) => (Pat::Str("while"), Pat::Str("}")),
186 ExprKind::Loop(_, None, LoopSource::ForLoop, _) | ExprKind::Match(_, _, MatchSource::ForLoopDesugar) => {
187 (Pat::Str("for"), Pat::Str("}"))
188 },
189 ExprKind::Match(_, _, MatchSource::Normal) => (Pat::Str("match"), Pat::Str("}")),
190 ExprKind::Match(e, _, MatchSource::TryDesugar(_)) => {
191 (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Str("?"))
192 },
193 ExprKind::Match(e, _, MatchSource::AwaitDesugar) | ExprKind::Yield(e, YieldSource::Await { .. }) => {
194 (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Str("await"))
195 },
196 ExprKind::Closure(&Closure { body, .. }) => (
197 Pat::Str(""),
198 expr_search_pat_inner(tcx, tcx.hir_body(body).value, outer_span).1,
199 ),
200 ExprKind::Block(
201 Block {
202 rules: BlockCheckMode::UnsafeBlock(UnsafeSource::UserProvided),
203 ..
204 },
205 None,
206 ) => (Pat::Str("unsafe"), Pat::Str("}")),
207 ExprKind::Block(_, None) => (Pat::Str("{"), Pat::Str("}")),
208 ExprKind::Field(e, name) => (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Sym(name.name)),
209 ExprKind::Index(e, _, _) => (expr_search_pat_inner(tcx, e, outer_span).0, Pat::Str("]")),
210 ExprKind::Path(ref path) => qpath_search_pat(path),
211 ExprKind::AddrOf(_, _, e) => (Pat::Str("&"), expr_search_pat_inner(tcx, e, outer_span).1),
212 ExprKind::Break(Destination { label: None, .. }, None) => (Pat::Str("break"), Pat::Str("break")),
213 ExprKind::Break(Destination { label: Some(name), .. }, None) => {
214 (Pat::Str("break"), Pat::Sym(name.ident.name))
215 },
216 ExprKind::Break(_, Some(e)) => (Pat::Str("break"), expr_search_pat_inner(tcx, e, outer_span).1),
217 ExprKind::Continue(Destination { label: None, .. }) => (Pat::Str("continue"), Pat::Str("continue")),
218 ExprKind::Continue(Destination { label: Some(name), .. }) => {
219 (Pat::Str("continue"), Pat::Sym(name.ident.name))
220 },
221 ExprKind::Ret(None) => (Pat::Str("return"), Pat::Str("return")),
222 ExprKind::Ret(Some(e)) => (Pat::Str("return"), expr_search_pat_inner(tcx, e, outer_span).1),
223 ExprKind::Struct(path, _, _) => (qpath_search_pat(path).0, Pat::Str("}")),
224 ExprKind::Yield(e, YieldSource::Yield) => (Pat::Str("yield"), expr_search_pat_inner(tcx, e, outer_span).1),
225 _ => (Pat::Str(""), Pat::Str("")),
226 }
227 }
228
229 expr_search_pat_inner(tcx, e, e.span)
230}
231
232fn fn_header_search_pat(header: FnHeader) -> Pat {
233 if header.is_async() {
234 Pat::Str("async")
235 } else if header.is_const() {
236 Pat::Str("const")
237 } else if header.is_unsafe() {
238 Pat::Str("unsafe")
239 } else if header.abi != ExternAbi::Rust {
240 Pat::Str("extern")
241 } else {
242 Pat::MultiStr(&["fn", "extern"])
243 }
244}
245
246fn item_search_pat(item: &Item<'_>) -> (Pat, Pat) {
247 let (start_pat, end_pat) = match &item.kind {
248 ItemKind::ExternCrate(..) => (Pat::Str("extern"), Pat::Str(";")),
249 ItemKind::Static(..) => (Pat::Str("static"), Pat::Str(";")),
250 ItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
251 ItemKind::Fn { sig, .. } => (fn_header_search_pat(sig.header), Pat::Str("")),
252 ItemKind::ForeignMod { .. } => (Pat::Str("extern"), Pat::Str("}")),
253 ItemKind::TyAlias(..) => (Pat::Str("type"), Pat::Str(";")),
254 ItemKind::Enum(..) => (Pat::Str("enum"), Pat::Str("}")),
255 ItemKind::Struct(_, _, VariantData::Struct { .. }) => (Pat::Str("struct"), Pat::Str("}")),
256 ItemKind::Struct(..) => (Pat::Str("struct"), Pat::Str(";")),
257 ItemKind::Union(..) => (Pat::Str("union"), Pat::Str("}")),
258 ItemKind::Trait(_, _, Safety::Unsafe, ..)
259 | ItemKind::Impl(Impl {
260 of_trait: Some(TraitImplHeader {
261 safety: Safety::Unsafe, ..
262 }),
263 ..
264 }) => (Pat::Str("unsafe"), Pat::Str("}")),
265 ItemKind::Trait(_, IsAuto::Yes, ..) => (Pat::Str("auto"), Pat::Str("}")),
266 ItemKind::Trait(..) => (Pat::Str("trait"), Pat::Str("}")),
267 ItemKind::Impl(_) => (Pat::Str("impl"), Pat::Str("}")),
268 _ => return (Pat::Str(""), Pat::Str("")),
269 };
270 if item.vis_span.is_empty() {
271 (start_pat, end_pat)
272 } else {
273 (Pat::Str("pub"), end_pat)
274 }
275}
276
277fn trait_item_search_pat(item: &TraitItem<'_>) -> (Pat, Pat) {
278 match &item.kind {
279 TraitItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
280 TraitItemKind::Type(..) => (Pat::Str("type"), Pat::Str(";")),
281 TraitItemKind::Fn(sig, ..) => (fn_header_search_pat(sig.header), Pat::Str("")),
282 }
283}
284
285fn impl_item_search_pat(item: &ImplItem<'_>) -> (Pat, Pat) {
286 let (mut start_pat, end_pat) = match &item.kind {
287 ImplItemKind::Const(..) => (Pat::Str("const"), Pat::Str(";")),
288 ImplItemKind::Type(..) => (Pat::Str("type"), Pat::Str(";")),
289 ImplItemKind::Fn(sig, ..) => (fn_header_search_pat(sig.header), Pat::Str("")),
290 };
291 if let ImplItemImplKind::Inherent { vis_span, .. } = item.impl_kind
292 && !vis_span.is_empty()
293 {
294 start_pat = Pat::Str("pub");
295 }
296 (start_pat, end_pat)
297}
298
299fn field_def_search_pat(def: &FieldDef<'_>) -> (Pat, Pat) {
300 if def.vis_span.is_empty() {
301 if def.is_positional() {
302 (Pat::Str(""), Pat::Str(""))
303 } else {
304 (Pat::Sym(def.ident.name), Pat::Str(""))
305 }
306 } else {
307 (Pat::Str("pub"), Pat::Str(""))
308 }
309}
310
311fn variant_search_pat(v: &Variant<'_>) -> (Pat, Pat) {
312 match v.data {
313 VariantData::Struct { .. } => (Pat::Sym(v.ident.name), Pat::Str("}")),
314 VariantData::Tuple(..) => (Pat::Sym(v.ident.name), Pat::Str("")),
315 VariantData::Unit(..) => (Pat::Sym(v.ident.name), Pat::Sym(v.ident.name)),
316 }
317}
318
319fn fn_kind_pat(tcx: TyCtxt<'_>, kind: &FnKind<'_>, body: &Body<'_>, hir_id: HirId) -> (Pat, Pat) {
320 let (mut start_pat, end_pat) = match kind {
321 FnKind::ItemFn(.., header) => (fn_header_search_pat(*header), Pat::Str("")),
322 FnKind::Method(.., sig) => (fn_header_search_pat(sig.header), Pat::Str("")),
323 FnKind::Closure => return (Pat::Str(""), expr_search_pat(tcx, body.value).1),
324 };
325 match tcx.hir_node(hir_id) {
326 Node::Item(Item { vis_span, .. })
327 | Node::ImplItem(ImplItem {
328 impl_kind: ImplItemImplKind::Inherent { vis_span, .. },
329 ..
330 }) => {
331 if !vis_span.is_empty() {
332 start_pat = Pat::Str("pub");
333 }
334 },
335 Node::ImplItem(_) | Node::TraitItem(_) => {},
336 _ => start_pat = Pat::Str(""),
337 }
338 (start_pat, end_pat)
339}
340
341fn attr_search_pat(attr: &Attribute) -> (Pat, Pat) {
342 match attr.kind {
343 AttrKind::Normal(..) => {
344 if let Some(ident) = attr.ident() {
345 let ident_string = ident.to_string();
347 if attr.style == AttrStyle::Outer {
348 (
349 Pat::OwnedMultiStr(vec!["#[".to_owned() + &ident_string, ident_string]),
350 Pat::Str(""),
351 )
352 } else {
353 (
354 Pat::OwnedMultiStr(vec!["#![".to_owned() + &ident_string, ident_string]),
355 Pat::Str(""),
356 )
357 }
358 } else {
359 (Pat::Str("#"), Pat::Str("]"))
360 }
361 },
362 AttrKind::DocComment(_kind @ CommentKind::Line, ..) => {
363 if attr.style == AttrStyle::Outer {
364 (Pat::Str("///"), Pat::Str(""))
365 } else {
366 (Pat::Str("//!"), Pat::Str(""))
367 }
368 },
369 AttrKind::DocComment(_kind @ CommentKind::Block, ..) => {
370 if attr.style == AttrStyle::Outer {
371 (Pat::Str("/**"), Pat::Str("*/"))
372 } else {
373 (Pat::Str("/*!"), Pat::Str("*/"))
374 }
375 },
376 }
377}
378
379fn ty_search_pat(ty: &Ty<'_>) -> (Pat, Pat) {
380 match ty.kind {
381 TyKind::Slice(..) | TyKind::Array(..) => (Pat::Str("["), Pat::Str("]")),
382 TyKind::Ptr(MutTy { ty, .. }) => (Pat::Str("*"), ty_search_pat(ty).1),
383 TyKind::Ref(_, MutTy { ty, .. }) => (Pat::Str("&"), ty_search_pat(ty).1),
384 TyKind::FnPtr(fn_ptr) => (
385 if fn_ptr.safety.is_unsafe() {
386 Pat::Str("unsafe")
387 } else if fn_ptr.abi != ExternAbi::Rust {
388 Pat::Str("extern")
389 } else {
390 Pat::MultiStr(&["fn", "extern"])
391 },
392 match fn_ptr.decl.output {
393 FnRetTy::DefaultReturn(_) => {
394 if let [.., ty] = fn_ptr.decl.inputs {
395 ty_search_pat(ty).1
396 } else {
397 Pat::Str("(")
398 }
399 },
400 FnRetTy::Return(ty) => ty_search_pat(ty).1,
401 },
402 ),
403 TyKind::Never => (Pat::Str("!"), Pat::Str("!")),
404 TyKind::Tup([]) => (Pat::Str(")"), Pat::Str("(")),
407 TyKind::Tup([ty]) => ty_search_pat(ty),
408 TyKind::Tup([head, .., tail]) => (ty_search_pat(head).0, ty_search_pat(tail).1),
409 TyKind::OpaqueDef(..) => (Pat::Str("impl"), Pat::Str("")),
410 TyKind::Path(qpath) => qpath_search_pat(&qpath),
411 TyKind::Infer(()) => (Pat::Str("_"), Pat::Str("_")),
412 TyKind::UnsafeBinder(binder_ty) => (Pat::Str("unsafe"), ty_search_pat(binder_ty.inner_ty).1),
413 TyKind::TraitObject(_, tagged_ptr) if let TraitObjectSyntax::Dyn = tagged_ptr.tag() => {
414 (Pat::Str("dyn"), Pat::Str(""))
415 },
416 _ => (Pat::Str(""), Pat::Str("")),
418 }
419}
420
421fn ast_ty_search_pat(ty: &ast::Ty) -> (Pat, Pat) {
422 use ast::{Extern, FnRetTy, MutTy, Safety, TraitObjectSyntax, TyKind};
423
424 match &ty.kind {
425 TyKind::Slice(..) | TyKind::Array(..) => (Pat::Str("["), Pat::Str("]")),
426 TyKind::Ptr(MutTy { ty, .. }) => (Pat::Str("*"), ast_ty_search_pat(ty).1),
427 TyKind::Ref(_, MutTy { ty, .. }) | TyKind::PinnedRef(_, MutTy { ty, .. }) => {
428 (Pat::Str("&"), ast_ty_search_pat(ty).1)
429 },
430 TyKind::FnPtr(fn_ptr) => (
431 if let Safety::Unsafe(_) = fn_ptr.safety {
432 Pat::Str("unsafe")
433 } else if let Extern::Explicit(strlit, _) = fn_ptr.ext
434 && strlit.symbol == sym::rust
435 {
436 Pat::MultiStr(&["fn", "extern"])
437 } else {
438 Pat::Str("extern")
439 },
440 match &fn_ptr.decl.output {
441 FnRetTy::Default(_) => {
442 if let [.., param] = &*fn_ptr.decl.inputs {
443 ast_ty_search_pat(¶m.ty).1
444 } else {
445 Pat::Str("(")
446 }
447 },
448 FnRetTy::Ty(ty) => ast_ty_search_pat(ty).1,
449 },
450 ),
451 TyKind::Never => (Pat::Str("!"), Pat::Str("!")),
452 TyKind::Tup(tup) => match &**tup {
455 [] => (Pat::Str(")"), Pat::Str("(")),
456 [ty] => ast_ty_search_pat(ty),
457 [head, .., tail] => (ast_ty_search_pat(head).0, ast_ty_search_pat(tail).1),
458 },
459 TyKind::ImplTrait(..) => (Pat::Str("impl"), Pat::Str("")),
460 TyKind::Path(qself_path, path) => {
461 let start = if qself_path.is_some() {
462 Pat::Str("<")
463 } else if let Some(first) = path.segments.first() {
464 ident_search_pat(first.ident).0
465 } else {
466 Pat::Str("")
468 };
469 let end = if let Some(last) = path.segments.last() {
470 match last.args.as_deref() {
471 Some(GenericArgs::AngleBracketed(_)) => Pat::Str(">"),
473 Some(GenericArgs::Parenthesized(par_args)) => match &par_args.output {
474 FnRetTy::Default(_) => {
475 if let Some(last) = par_args.inputs.last() {
476 ast_ty_search_pat(last).1
478 } else {
479 Pat::Str("(")
481 }
482 },
483 FnRetTy::Ty(ty) => ast_ty_search_pat(ty).1,
485 },
486 Some(GenericArgs::ParenthesizedElided(_)) => Pat::Str(".."),
488 None => ident_search_pat(last.ident).1,
490 }
491 } else {
492 Pat::Str(
494 if qself_path.is_some() {
495 ">" } else {
497 ""
498 }
499 )
500 };
501 (start, end)
502 },
503 TyKind::Infer => (Pat::Str("_"), Pat::Str("_")),
504 TyKind::Paren(ty) => ast_ty_search_pat(ty),
505 TyKind::UnsafeBinder(binder_ty) => (Pat::Str("unsafe"), ast_ty_search_pat(&binder_ty.inner_ty).1),
506 TyKind::TraitObject(_, trait_obj_syntax) => {
507 if let TraitObjectSyntax::Dyn = trait_obj_syntax {
508 (Pat::Str("dyn"), Pat::Str(""))
509 } else {
510 (Pat::Str(""), Pat::Str(""))
512 }
513 },
514 TyKind::MacCall(mac_call) => {
515 let start = if let Some(first) = mac_call.path.segments.first() {
516 ident_search_pat(first.ident).0
517 } else {
518 Pat::Str("")
519 };
520 (start, Pat::Str(""))
521 },
522
523 TyKind::ImplicitSelf
525
526 |TyKind::Pat(..)
528
529 | TyKind::CVarArgs
531 | TyKind::Typeof(_)
532
533 | TyKind::Dummy
535 | TyKind::Err(_) => (Pat::Str(""), Pat::Str("")),
536 }
537}
538
539fn ident_search_pat(ident: Ident) -> (Pat, Pat) {
540 (Pat::Sym(ident.name), Pat::Sym(ident.name))
541}
542
543pub trait WithSearchPat<'cx> {
544 type Context: LintContext;
545 fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat);
546 fn span(&self) -> Span;
547}
548macro_rules! impl_with_search_pat {
549 (($cx_ident:ident: $cx_ty:ident<$cx_lt:lifetime>, $self:tt: $ty:ty) => $fn:ident($($args:tt)*)) => {
550 impl<$cx_lt> WithSearchPat<$cx_lt> for $ty {
551 type Context = $cx_ty<$cx_lt>;
552 fn search_pat(&$self, $cx_ident: &Self::Context) -> (Pat, Pat) {
553 $fn($($args)*)
554 }
555 fn span(&self) -> Span {
556 self.span
557 }
558 }
559 };
560}
561impl_with_search_pat!((cx: LateContext<'tcx>, self: Expr<'tcx>) => expr_search_pat(cx.tcx, self));
562impl_with_search_pat!((_cx: LateContext<'tcx>, self: Item<'_>) => item_search_pat(self));
563impl_with_search_pat!((_cx: LateContext<'tcx>, self: TraitItem<'_>) => trait_item_search_pat(self));
564impl_with_search_pat!((_cx: LateContext<'tcx>, self: ImplItem<'_>) => impl_item_search_pat(self));
565impl_with_search_pat!((_cx: LateContext<'tcx>, self: FieldDef<'_>) => field_def_search_pat(self));
566impl_with_search_pat!((_cx: LateContext<'tcx>, self: Variant<'_>) => variant_search_pat(self));
567impl_with_search_pat!((_cx: LateContext<'tcx>, self: Ty<'_>) => ty_search_pat(self));
568impl_with_search_pat!((_cx: LateContext<'tcx>, self: Ident) => ident_search_pat(*self));
569impl_with_search_pat!((_cx: LateContext<'tcx>, self: Lit) => lit_search_pat(&self.node));
570impl_with_search_pat!((_cx: LateContext<'tcx>, self: Path<'_>) => path_search_pat(self));
571
572impl_with_search_pat!((_cx: EarlyContext<'tcx>, self: Attribute) => attr_search_pat(self));
573impl_with_search_pat!((_cx: EarlyContext<'tcx>, self: ast::Ty) => ast_ty_search_pat(self));
574
575impl<'cx> WithSearchPat<'cx> for (&FnKind<'cx>, &Body<'cx>, HirId, Span) {
576 type Context = LateContext<'cx>;
577
578 fn search_pat(&self, cx: &Self::Context) -> (Pat, Pat) {
579 fn_kind_pat(cx.tcx, self.0, self.1, self.2)
580 }
581
582 fn span(&self) -> Span {
583 self.3
584 }
585}
586
587pub fn is_from_proc_macro<'cx, T: WithSearchPat<'cx>>(cx: &T::Context, item: &T) -> bool {
592 let (start_pat, end_pat) = item.search_pat(cx);
593 !span_matches_pat(cx.sess(), item.span(), start_pat, end_pat)
594}
595
596pub fn is_span_match(cx: &impl LintContext, span: Span) -> bool {
598 span_matches_pat(cx.sess(), span, Pat::Str("match"), Pat::Str("}"))
599}
600
601pub fn is_span_if(cx: &impl LintContext, span: Span) -> bool {
603 span_matches_pat(cx.sess(), span, Pat::Str("if"), Pat::Str("}"))
604}