rustc_lint/builtin.rs
1//! Lints in the Rust compiler.
2//!
3//! This contains lints which can feasibly be implemented as their own
4//! AST visitor. Also see `rustc_session::lint::builtin`, which contains the
5//! definitions of lints that are emitted directly inside the main compiler.
6//!
7//! To add a new lint to rustc, declare it here using [`declare_lint!`].
8//! Then add code to emit the new lint in the appropriate circumstances.
9//!
10//! If you define a new [`EarlyLintPass`], you will also need to add it to the
11//! [`crate::early_lint_methods!`] invocation in `lib.rs`.
12//!
13//! If you define a new [`LateLintPass`], you will also need to add it to the
14//! [`crate::late_lint_methods!`] invocation in `lib.rs`.
15
16use std::fmt::Write;
17
18use ast::token::TokenKind;
19use rustc_abi::BackendRepr;
20use rustc_ast::tokenstream::{TokenStream, TokenTree};
21use rustc_ast::visit::{FnCtxt, FnKind};
22use rustc_ast::{self as ast, *};
23use rustc_ast_pretty::pprust::expr_to_string;
24use rustc_attr_parsing::AttributeParser;
25use rustc_errors::{Applicability, LintDiagnostic};
26use rustc_feature::GateIssue;
27use rustc_hir as hir;
28use rustc_hir::attrs::AttributeKind;
29use rustc_hir::def::{DefKind, Res};
30use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
31use rustc_hir::intravisit::FnKind as HirFnKind;
32use rustc_hir::{Body, FnDecl, ImplItemImplKind, PatKind, PredicateOrigin, find_attr};
33use rustc_middle::bug;
34use rustc_middle::lint::LevelAndSource;
35use rustc_middle::ty::layout::LayoutOf;
36use rustc_middle::ty::print::with_no_trimmed_paths;
37use rustc_middle::ty::{self, AssocContainer, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef};
38use rustc_session::lint::FutureIncompatibilityReason;
39// hardwired lints from rustc_lint_defs
40pub use rustc_session::lint::builtin::*;
41use rustc_session::{declare_lint, declare_lint_pass, impl_lint_pass};
42use rustc_span::edition::Edition;
43use rustc_span::source_map::Spanned;
44use rustc_span::{DUMMY_SP, Ident, InnerSpan, Span, Symbol, kw, sym};
45use rustc_target::asm::InlineAsmArch;
46use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
47use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy;
48use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
49use rustc_trait_selection::traits::{self};
50
51use crate::errors::BuiltinEllipsisInclusiveRangePatterns;
52use crate::lints::{
53 BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations,
54 BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatternsLint,
55 BuiltinExplicitOutlives, BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote,
56 BuiltinIncompleteFeatures, BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures,
57 BuiltinKeywordIdents, BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc,
58 BuiltinMutablesTransmutes, BuiltinNoMangleGeneric, BuiltinNonShorthandFieldPatterns,
59 BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds, BuiltinTypeAliasBounds,
60 BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit, BuiltinUnpermittedTypeInitSub,
61 BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures, BuiltinUnusedDocComment,
62 BuiltinUnusedDocCommentSub, BuiltinWhileTrue, InvalidAsmLabel,
63};
64use crate::{
65 EarlyContext, EarlyLintPass, LateContext, LateLintPass, Level, LintContext,
66 fluent_generated as fluent,
67};
68declare_lint! {
69 /// The `while_true` lint detects `while true { }`.
70 ///
71 /// ### Example
72 ///
73 /// ```rust,no_run
74 /// while true {
75 ///
76 /// }
77 /// ```
78 ///
79 /// {{produces}}
80 ///
81 /// ### Explanation
82 ///
83 /// `while true` should be replaced with `loop`. A `loop` expression is
84 /// the preferred way to write an infinite loop because it more directly
85 /// expresses the intent of the loop.
86 WHILE_TRUE,
87 Warn,
88 "suggest using `loop { }` instead of `while true { }`"
89}
90
91declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
92
93impl EarlyLintPass for WhileTrue {
94 #[inline]
95 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
96 if let ast::ExprKind::While(cond, _, label) = &e.kind
97 && let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
98 && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
99 && !cond.span.from_expansion()
100 {
101 let condition_span = e.span.with_hi(cond.span.hi());
102 let replace = format!(
103 "{}loop",
104 label.map_or_else(String::new, |label| format!("{}: ", label.ident,))
105 );
106 cx.emit_span_lint(
107 WHILE_TRUE,
108 condition_span,
109 BuiltinWhileTrue { suggestion: condition_span, replace },
110 );
111 }
112 }
113}
114
115declare_lint! {
116 /// The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`
117 /// instead of `Struct { x }` in a pattern.
118 ///
119 /// ### Example
120 ///
121 /// ```rust
122 /// struct Point {
123 /// x: i32,
124 /// y: i32,
125 /// }
126 ///
127 ///
128 /// fn main() {
129 /// let p = Point {
130 /// x: 5,
131 /// y: 5,
132 /// };
133 ///
134 /// match p {
135 /// Point { x: x, y: y } => (),
136 /// }
137 /// }
138 /// ```
139 ///
140 /// {{produces}}
141 ///
142 /// ### Explanation
143 ///
144 /// The preferred style is to avoid the repetition of specifying both the
145 /// field name and the binding name if both identifiers are the same.
146 NON_SHORTHAND_FIELD_PATTERNS,
147 Warn,
148 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
149}
150
151declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
152
153impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
154 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
155 // The result shouldn't be tainted, otherwise it will cause ICE.
156 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind
157 && cx.typeck_results().tainted_by_errors.is_none()
158 {
159 let variant = cx
160 .typeck_results()
161 .pat_ty(pat)
162 .ty_adt_def()
163 .expect("struct pattern type is not an ADT")
164 .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
165 for fieldpat in field_pats {
166 if fieldpat.is_shorthand {
167 continue;
168 }
169 if fieldpat.span.from_expansion() {
170 // Don't lint if this is a macro expansion: macro authors
171 // shouldn't have to worry about this kind of style issue
172 // (Issue #49588)
173 continue;
174 }
175 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
176 if cx.tcx.find_field_index(ident, variant)
177 == Some(cx.typeck_results().field_index(fieldpat.hir_id))
178 {
179 cx.emit_span_lint(
180 NON_SHORTHAND_FIELD_PATTERNS,
181 fieldpat.span,
182 BuiltinNonShorthandFieldPatterns {
183 ident,
184 suggestion: fieldpat.span,
185 prefix: binding_annot.prefix_str(),
186 },
187 );
188 }
189 }
190 }
191 }
192 }
193}
194
195declare_lint! {
196 /// The `unsafe_code` lint catches usage of `unsafe` code and other
197 /// potentially unsound constructs like `no_mangle`, `export_name`,
198 /// and `link_section`.
199 ///
200 /// ### Example
201 ///
202 /// ```rust,compile_fail
203 /// #![deny(unsafe_code)]
204 /// fn main() {
205 /// unsafe {
206 ///
207 /// }
208 /// }
209 ///
210 /// #[no_mangle]
211 /// fn func_0() { }
212 ///
213 /// #[export_name = "exported_symbol_name"]
214 /// pub fn name_in_rust() { }
215 ///
216 /// #[no_mangle]
217 /// #[link_section = ".example_section"]
218 /// pub static VAR1: u32 = 1;
219 /// ```
220 ///
221 /// {{produces}}
222 ///
223 /// ### Explanation
224 ///
225 /// This lint is intended to restrict the usage of `unsafe` blocks and other
226 /// constructs (including, but not limited to `no_mangle`, `link_section`
227 /// and `export_name` attributes) wrong usage of which causes undefined
228 /// behavior.
229 UNSAFE_CODE,
230 Allow,
231 "usage of `unsafe` code and other potentially unsound constructs",
232 @eval_always = true
233}
234
235declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
236
237impl UnsafeCode {
238 fn report_unsafe(
239 &self,
240 cx: &EarlyContext<'_>,
241 span: Span,
242 decorate: impl for<'a> LintDiagnostic<'a, ()>,
243 ) {
244 // This comes from a macro that has `#[allow_internal_unsafe]`.
245 if span.allows_unsafe() {
246 return;
247 }
248
249 cx.emit_span_lint(UNSAFE_CODE, span, decorate);
250 }
251}
252
253impl EarlyLintPass for UnsafeCode {
254 #[inline]
255 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
256 if let ast::ExprKind::Block(ref blk, _) = e.kind {
257 // Don't warn about generated blocks; that'll just pollute the output.
258 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
259 self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
260 }
261 }
262 }
263
264 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
265 match it.kind {
266 ast::ItemKind::Trait(box ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
267 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
268 }
269
270 ast::ItemKind::Impl(ast::Impl {
271 of_trait: Some(box ast::TraitImplHeader { safety: ast::Safety::Unsafe(_), .. }),
272 ..
273 }) => {
274 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
275 }
276
277 ast::ItemKind::Fn(..) => {
278 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
279 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleFn);
280 }
281
282 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
283 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameFn);
284 }
285
286 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
287 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionFn);
288 }
289 }
290
291 ast::ItemKind::Static(..) => {
292 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
293 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleStatic);
294 }
295
296 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
297 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameStatic);
298 }
299
300 if let Some(attr) = attr::find_by_name(&it.attrs, sym::link_section) {
301 self.report_unsafe(cx, attr.span, BuiltinUnsafe::LinkSectionStatic);
302 }
303 }
304
305 ast::ItemKind::GlobalAsm(..) => {
306 self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
307 }
308
309 ast::ItemKind::ForeignMod(ForeignMod { safety, .. }) => {
310 if let Safety::Unsafe(_) = safety {
311 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeExternBlock);
312 }
313 }
314
315 ast::ItemKind::MacroDef(..) => {
316 if let Some(hir::Attribute::Parsed(AttributeKind::AllowInternalUnsafe(span))) =
317 AttributeParser::parse_limited(
318 cx.builder.sess(),
319 &it.attrs,
320 sym::allow_internal_unsafe,
321 it.span,
322 DUMMY_NODE_ID,
323 Some(cx.builder.features()),
324 )
325 {
326 self.report_unsafe(cx, span, BuiltinUnsafe::AllowInternalUnsafe);
327 }
328 }
329
330 _ => {}
331 }
332 }
333
334 fn check_impl_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
335 if let ast::AssocItemKind::Fn(..) = it.kind {
336 if let Some(attr) = attr::find_by_name(&it.attrs, sym::no_mangle) {
337 self.report_unsafe(cx, attr.span, BuiltinUnsafe::NoMangleMethod);
338 }
339 if let Some(attr) = attr::find_by_name(&it.attrs, sym::export_name) {
340 self.report_unsafe(cx, attr.span, BuiltinUnsafe::ExportNameMethod);
341 }
342 }
343 }
344
345 fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
346 if let FnKind::Fn(
347 ctxt,
348 _,
349 ast::Fn {
350 sig: ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
351 body,
352 ..
353 },
354 ) = fk
355 {
356 let decorator = match ctxt {
357 FnCtxt::Foreign => return,
358 FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
359 FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
360 FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
361 };
362 self.report_unsafe(cx, span, decorator);
363 }
364 }
365}
366
367declare_lint! {
368 /// The `missing_docs` lint detects missing documentation for public items.
369 ///
370 /// ### Example
371 ///
372 /// ```rust,compile_fail
373 /// #![deny(missing_docs)]
374 /// pub fn foo() {}
375 /// ```
376 ///
377 /// {{produces}}
378 ///
379 /// ### Explanation
380 ///
381 /// This lint is intended to ensure that a library is well-documented.
382 /// Items without documentation can be difficult for users to understand
383 /// how to use properly.
384 ///
385 /// This lint is "allow" by default because it can be noisy, and not all
386 /// projects may want to enforce everything to be documented.
387 pub MISSING_DOCS,
388 Allow,
389 "detects missing documentation for public members",
390 report_in_external_macro
391}
392
393#[derive(Default)]
394pub struct MissingDoc;
395
396impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
397
398fn has_doc(attr: &hir::Attribute) -> bool {
399 if attr.is_doc_comment().is_some() {
400 return true;
401 }
402
403 if !attr.has_name(sym::doc) {
404 return false;
405 }
406
407 if attr.value_str().is_some() {
408 return true;
409 }
410
411 if let Some(list) = attr.meta_item_list() {
412 for meta in list {
413 if meta.has_name(sym::hidden) {
414 return true;
415 }
416 }
417 }
418
419 false
420}
421
422impl MissingDoc {
423 fn check_missing_docs_attrs(
424 &self,
425 cx: &LateContext<'_>,
426 def_id: LocalDefId,
427 article: &'static str,
428 desc: &'static str,
429 ) {
430 // Only check publicly-visible items, using the result from the privacy pass.
431 // It's an option so the crate root can also use this function (it doesn't
432 // have a `NodeId`).
433 if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
434 return;
435 }
436
437 let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
438 let has_doc = attrs.iter().any(has_doc);
439 if !has_doc {
440 cx.emit_span_lint(
441 MISSING_DOCS,
442 cx.tcx.def_span(def_id),
443 BuiltinMissingDoc { article, desc },
444 );
445 }
446 }
447}
448
449impl<'tcx> LateLintPass<'tcx> for MissingDoc {
450 fn check_crate(&mut self, cx: &LateContext<'_>) {
451 self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
452 }
453
454 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
455 // Previously the Impl and Use types have been excluded from missing docs,
456 // so we will continue to exclude them for compatibility.
457 //
458 // The documentation on `ExternCrate` is not used at the moment so no need to warn for it.
459 if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(..) =
460 it.kind
461 {
462 return;
463 }
464
465 let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
466 self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
467 }
468
469 fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
470 let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
471
472 self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
473 }
474
475 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
476 let container = cx.tcx.associated_item(impl_item.owner_id.def_id).container;
477
478 match container {
479 // If the method is an impl for a trait, don't doc.
480 AssocContainer::TraitImpl(_) => return,
481 AssocContainer::Trait => {}
482 // If the method is an impl for an item with docs_hidden, don't doc.
483 AssocContainer::InherentImpl => {
484 let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id());
485 let impl_ty = cx.tcx.type_of(parent).instantiate_identity();
486 let outerdef = match impl_ty.kind() {
487 ty::Adt(def, _) => Some(def.did()),
488 ty::Foreign(def_id) => Some(*def_id),
489 _ => None,
490 };
491 let is_hidden = match outerdef {
492 Some(id) => cx.tcx.is_doc_hidden(id),
493 None => false,
494 };
495 if is_hidden {
496 return;
497 }
498 }
499 }
500
501 let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
502 self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
503 }
504
505 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
506 let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
507 self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
508 }
509
510 fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
511 if !sf.is_positional() {
512 self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
513 }
514 }
515
516 fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
517 self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
518 }
519}
520
521declare_lint! {
522 /// The `missing_copy_implementations` lint detects potentially-forgotten
523 /// implementations of [`Copy`] for public types.
524 ///
525 /// [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html
526 ///
527 /// ### Example
528 ///
529 /// ```rust,compile_fail
530 /// #![deny(missing_copy_implementations)]
531 /// pub struct Foo {
532 /// pub field: i32
533 /// }
534 /// # fn main() {}
535 /// ```
536 ///
537 /// {{produces}}
538 ///
539 /// ### Explanation
540 ///
541 /// Historically (before 1.0), types were automatically marked as `Copy`
542 /// if possible. This was changed so that it required an explicit opt-in
543 /// by implementing the `Copy` trait. As part of this change, a lint was
544 /// added to alert if a copyable type was not marked `Copy`.
545 ///
546 /// This lint is "allow" by default because this code isn't bad; it is
547 /// common to write newtypes like this specifically so that a `Copy` type
548 /// is no longer `Copy`. `Copy` types can result in unintended copies of
549 /// large data which can impact performance.
550 pub MISSING_COPY_IMPLEMENTATIONS,
551 Allow,
552 "detects potentially-forgotten implementations of `Copy`"
553}
554
555declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
556
557impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
558 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
559 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
560 return;
561 }
562 let (def, ty) = match item.kind {
563 hir::ItemKind::Struct(_, generics, _) => {
564 if !generics.params.is_empty() {
565 return;
566 }
567 let def = cx.tcx.adt_def(item.owner_id);
568 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
569 }
570 hir::ItemKind::Union(_, generics, _) => {
571 if !generics.params.is_empty() {
572 return;
573 }
574 let def = cx.tcx.adt_def(item.owner_id);
575 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
576 }
577 hir::ItemKind::Enum(_, generics, _) => {
578 if !generics.params.is_empty() {
579 return;
580 }
581 let def = cx.tcx.adt_def(item.owner_id);
582 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
583 }
584 _ => return,
585 };
586 if def.has_dtor(cx.tcx) {
587 return;
588 }
589
590 // If the type contains a raw pointer, it may represent something like a handle,
591 // and recommending Copy might be a bad idea.
592 for field in def.all_fields() {
593 let did = field.did;
594 if cx.tcx.type_of(did).instantiate_identity().is_raw_ptr() {
595 return;
596 }
597 }
598 if cx.type_is_copy_modulo_regions(ty) {
599 return;
600 }
601 if type_implements_negative_copy_modulo_regions(cx.tcx, ty, cx.typing_env()) {
602 return;
603 }
604 if def.is_variant_list_non_exhaustive()
605 || def.variants().iter().any(|variant| variant.is_field_list_non_exhaustive())
606 {
607 return;
608 }
609
610 // We shouldn't recommend implementing `Copy` on stateful things,
611 // such as iterators.
612 if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
613 && cx
614 .tcx
615 .infer_ctxt()
616 .build(cx.typing_mode())
617 .type_implements_trait(iter_trait, [ty], cx.param_env)
618 .must_apply_modulo_regions()
619 {
620 return;
621 }
622
623 // Default value of clippy::trivially_copy_pass_by_ref
624 const MAX_SIZE: u64 = 256;
625
626 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
627 if size > MAX_SIZE {
628 return;
629 }
630 }
631
632 if type_allowed_to_implement_copy(
633 cx.tcx,
634 cx.param_env,
635 ty,
636 traits::ObligationCause::misc(item.span, item.owner_id.def_id),
637 hir::Safety::Safe,
638 )
639 .is_ok()
640 {
641 cx.emit_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
642 }
643 }
644}
645
646/// Check whether a `ty` has a negative `Copy` implementation, ignoring outlives constraints.
647fn type_implements_negative_copy_modulo_regions<'tcx>(
648 tcx: TyCtxt<'tcx>,
649 ty: Ty<'tcx>,
650 typing_env: ty::TypingEnv<'tcx>,
651) -> bool {
652 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
653 let trait_ref =
654 ty::TraitRef::new(tcx, tcx.require_lang_item(hir::LangItem::Copy, DUMMY_SP), [ty]);
655 let pred = ty::TraitPredicate { trait_ref, polarity: ty::PredicatePolarity::Negative };
656 let obligation = traits::Obligation {
657 cause: traits::ObligationCause::dummy(),
658 param_env,
659 recursion_depth: 0,
660 predicate: pred.upcast(tcx),
661 };
662 infcx.predicate_must_hold_modulo_regions(&obligation)
663}
664
665declare_lint! {
666 /// The `missing_debug_implementations` lint detects missing
667 /// implementations of [`fmt::Debug`] for public types.
668 ///
669 /// [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html
670 ///
671 /// ### Example
672 ///
673 /// ```rust,compile_fail
674 /// #![deny(missing_debug_implementations)]
675 /// pub struct Foo;
676 /// # fn main() {}
677 /// ```
678 ///
679 /// {{produces}}
680 ///
681 /// ### Explanation
682 ///
683 /// Having a `Debug` implementation on all types can assist with
684 /// debugging, as it provides a convenient way to format and display a
685 /// value. Using the `#[derive(Debug)]` attribute will automatically
686 /// generate a typical implementation, or a custom implementation can be
687 /// added by manually implementing the `Debug` trait.
688 ///
689 /// This lint is "allow" by default because adding `Debug` to all types can
690 /// have a negative impact on compile time and code size. It also requires
691 /// boilerplate to be added to every type, which can be an impediment.
692 MISSING_DEBUG_IMPLEMENTATIONS,
693 Allow,
694 "detects missing implementations of Debug"
695}
696
697#[derive(Default)]
698pub(crate) struct MissingDebugImplementations;
699
700impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
701
702impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
703 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
704 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
705 return;
706 }
707
708 match item.kind {
709 hir::ItemKind::Struct(..) | hir::ItemKind::Union(..) | hir::ItemKind::Enum(..) => {}
710 _ => return,
711 }
712
713 // Avoid listing trait impls if the trait is allowed.
714 let LevelAndSource { level, .. } =
715 cx.tcx.lint_level_at_node(MISSING_DEBUG_IMPLEMENTATIONS, item.hir_id());
716 if level == Level::Allow {
717 return;
718 }
719
720 let Some(debug) = cx.tcx.get_diagnostic_item(sym::Debug) else { return };
721
722 let has_impl = cx
723 .tcx
724 .non_blanket_impls_for_ty(debug, cx.tcx.type_of(item.owner_id).instantiate_identity())
725 .next()
726 .is_some();
727 if !has_impl {
728 cx.emit_span_lint(
729 MISSING_DEBUG_IMPLEMENTATIONS,
730 item.span,
731 BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
732 );
733 }
734 }
735}
736
737declare_lint! {
738 /// The `anonymous_parameters` lint detects anonymous parameters in trait
739 /// definitions.
740 ///
741 /// ### Example
742 ///
743 /// ```rust,edition2015,compile_fail
744 /// #![deny(anonymous_parameters)]
745 /// // edition 2015
746 /// pub trait Foo {
747 /// fn foo(usize);
748 /// }
749 /// fn main() {}
750 /// ```
751 ///
752 /// {{produces}}
753 ///
754 /// ### Explanation
755 ///
756 /// This syntax is mostly a historical accident, and can be worked around
757 /// quite easily by adding an `_` pattern or a descriptive identifier:
758 ///
759 /// ```rust
760 /// trait Foo {
761 /// fn foo(_: usize);
762 /// }
763 /// ```
764 ///
765 /// This syntax is now a hard error in the 2018 edition. In the 2015
766 /// edition, this lint is "warn" by default. This lint
767 /// enables the [`cargo fix`] tool with the `--edition` flag to
768 /// automatically transition old code from the 2015 edition to 2018. The
769 /// tool will run this lint and automatically apply the
770 /// suggested fix from the compiler (which is to add `_` to each
771 /// parameter). This provides a completely automated way to update old
772 /// code for a new edition. See [issue #41686] for more details.
773 ///
774 /// [issue #41686]: https://github.com/rust-lang/rust/issues/41686
775 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
776 pub ANONYMOUS_PARAMETERS,
777 Warn,
778 "detects anonymous parameters",
779 @future_incompatible = FutureIncompatibleInfo {
780 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
781 reference: "issue #41686 <https://github.com/rust-lang/rust/issues/41686>",
782 };
783}
784
785declare_lint_pass!(
786 /// Checks for use of anonymous parameters (RFC 1685).
787 AnonymousParameters => [ANONYMOUS_PARAMETERS]
788);
789
790impl EarlyLintPass for AnonymousParameters {
791 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
792 if cx.sess().edition() != Edition::Edition2015 {
793 // This is a hard error in future editions; avoid linting and erroring
794 return;
795 }
796 if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
797 for arg in sig.decl.inputs.iter() {
798 if let ast::PatKind::Missing = arg.pat.kind {
799 let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
800
801 let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
802 (snip.as_str(), Applicability::MachineApplicable)
803 } else {
804 ("<type>", Applicability::HasPlaceholders)
805 };
806 cx.emit_span_lint(
807 ANONYMOUS_PARAMETERS,
808 arg.pat.span,
809 BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
810 );
811 }
812 }
813 }
814 }
815}
816
817fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
818 use rustc_ast::token::CommentKind;
819
820 let mut attrs = attrs.iter().peekable();
821
822 // Accumulate a single span for sugared doc comments.
823 let mut sugared_span: Option<Span> = None;
824
825 while let Some(attr) = attrs.next() {
826 let is_doc_comment = attr.is_doc_comment();
827 if is_doc_comment {
828 sugared_span =
829 Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
830 }
831
832 if attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
833 continue;
834 }
835
836 let span = sugared_span.take().unwrap_or(attr.span);
837
838 if is_doc_comment || attr.has_name(sym::doc) {
839 let sub = match attr.kind {
840 AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
841 BuiltinUnusedDocCommentSub::PlainHelp
842 }
843 AttrKind::DocComment(CommentKind::Block, _) => {
844 BuiltinUnusedDocCommentSub::BlockHelp
845 }
846 };
847 cx.emit_span_lint(
848 UNUSED_DOC_COMMENTS,
849 span,
850 BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
851 );
852 }
853 }
854}
855
856impl EarlyLintPass for UnusedDocComment {
857 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
858 let kind = match stmt.kind {
859 ast::StmtKind::Let(..) => "statements",
860 // Disabled pending discussion in #78306
861 ast::StmtKind::Item(..) => return,
862 // expressions will be reported by `check_expr`.
863 ast::StmtKind::Empty
864 | ast::StmtKind::Semi(_)
865 | ast::StmtKind::Expr(_)
866 | ast::StmtKind::MacCall(_) => return,
867 };
868
869 warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
870 }
871
872 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
873 if let Some(body) = &arm.body {
874 let arm_span = arm.pat.span.with_hi(body.span.hi());
875 warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
876 }
877 }
878
879 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
880 if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind {
881 for field in fields {
882 warn_if_doc(cx, field.span, "pattern fields", &field.attrs);
883 }
884 }
885 }
886
887 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
888 warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
889
890 if let ExprKind::Struct(s) = &expr.kind {
891 for field in &s.fields {
892 warn_if_doc(cx, field.span, "expression fields", &field.attrs);
893 }
894 }
895 }
896
897 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
898 warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs);
899 }
900
901 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
902 warn_if_doc(cx, block.span, "blocks", block.attrs());
903 }
904
905 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
906 if let ast::ItemKind::ForeignMod(_) = item.kind {
907 warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
908 }
909 }
910}
911
912declare_lint! {
913 /// The `no_mangle_const_items` lint detects any `const` items with the
914 /// [`no_mangle` attribute].
915 ///
916 /// [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
917 ///
918 /// ### Example
919 ///
920 /// ```rust,compile_fail,edition2021
921 /// #[no_mangle]
922 /// const FOO: i32 = 5;
923 /// ```
924 ///
925 /// {{produces}}
926 ///
927 /// ### Explanation
928 ///
929 /// Constants do not have their symbols exported, and therefore, this
930 /// probably means you meant to use a [`static`], not a [`const`].
931 ///
932 /// [`static`]: https://doc.rust-lang.org/reference/items/static-items.html
933 /// [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html
934 NO_MANGLE_CONST_ITEMS,
935 Deny,
936 "const items will not have their symbols exported"
937}
938
939declare_lint! {
940 /// The `no_mangle_generic_items` lint detects generic items that must be
941 /// mangled.
942 ///
943 /// ### Example
944 ///
945 /// ```rust
946 /// #[unsafe(no_mangle)]
947 /// fn foo<T>(t: T) {}
948 ///
949 /// #[unsafe(export_name = "bar")]
950 /// fn bar<T>(t: T) {}
951 /// ```
952 ///
953 /// {{produces}}
954 ///
955 /// ### Explanation
956 ///
957 /// A function with generics must have its symbol mangled to accommodate
958 /// the generic parameter. The [`no_mangle`] and [`export_name`] attributes
959 /// have no effect in this situation, and should be removed.
960 ///
961 /// [`no_mangle`]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute
962 /// [`export_name`]: https://doc.rust-lang.org/reference/abi.html#the-export_name-attribute
963 NO_MANGLE_GENERIC_ITEMS,
964 Warn,
965 "generic items must be mangled"
966}
967
968declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS, NO_MANGLE_GENERIC_ITEMS]);
969
970impl InvalidNoMangleItems {
971 fn check_no_mangle_on_generic_fn(
972 &self,
973 cx: &LateContext<'_>,
974 attr_span: Span,
975 def_id: LocalDefId,
976 ) {
977 let generics = cx.tcx.generics_of(def_id);
978 if generics.requires_monomorphization(cx.tcx) {
979 cx.emit_span_lint(
980 NO_MANGLE_GENERIC_ITEMS,
981 cx.tcx.def_span(def_id),
982 BuiltinNoMangleGeneric { suggestion: attr_span },
983 );
984 }
985 }
986}
987
988impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
989 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
990 let attrs = cx.tcx.hir_attrs(it.hir_id());
991 match it.kind {
992 hir::ItemKind::Fn { .. } => {
993 if let Some(attr_span) =
994 find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
995 .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
996 {
997 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
998 }
999 }
1000 hir::ItemKind::Const(ident, generics, ..) => {
1001 if find_attr!(attrs, AttributeKind::NoMangle(..)) {
1002 let suggestion =
1003 if generics.params.is_empty() && generics.where_clause_span.is_empty() {
1004 // account for "pub const" (#45562)
1005 Some(it.span.until(ident.span))
1006 } else {
1007 None
1008 };
1009
1010 // Const items do not refer to a particular location in memory, and therefore
1011 // don't have anything to attach a symbol to
1012 cx.emit_span_lint(
1013 NO_MANGLE_CONST_ITEMS,
1014 it.span,
1015 BuiltinConstNoMangle { suggestion },
1016 );
1017 }
1018 }
1019 _ => {}
1020 }
1021 }
1022
1023 fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) {
1024 let attrs = cx.tcx.hir_attrs(it.hir_id());
1025 match it.kind {
1026 hir::ImplItemKind::Fn { .. } => {
1027 if let Some(attr_span) =
1028 find_attr!(attrs, AttributeKind::ExportName {span, ..} => *span)
1029 .or_else(|| find_attr!(attrs, AttributeKind::NoMangle(span) => *span))
1030 {
1031 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
1032 }
1033 }
1034 _ => {}
1035 }
1036 }
1037}
1038
1039declare_lint! {
1040 /// The `mutable_transmutes` lint catches transmuting from `&T` to `&mut
1041 /// T` because it is [undefined behavior].
1042 ///
1043 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
1044 ///
1045 /// ### Example
1046 ///
1047 /// ```rust,compile_fail
1048 /// unsafe {
1049 /// let y = std::mem::transmute::<&i32, &mut i32>(&5);
1050 /// }
1051 /// ```
1052 ///
1053 /// {{produces}}
1054 ///
1055 /// ### Explanation
1056 ///
1057 /// Certain assumptions are made about aliasing of data, and this transmute
1058 /// violates those assumptions. Consider using [`UnsafeCell`] instead.
1059 ///
1060 /// [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html
1061 MUTABLE_TRANSMUTES,
1062 Deny,
1063 "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
1064}
1065
1066declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
1067
1068impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
1069 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
1070 if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
1071 get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
1072 {
1073 if from_mutbl < to_mutbl {
1074 cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
1075 }
1076 }
1077
1078 fn get_transmute_from_to<'tcx>(
1079 cx: &LateContext<'tcx>,
1080 expr: &hir::Expr<'_>,
1081 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
1082 let def = if let hir::ExprKind::Path(ref qpath) = expr.kind {
1083 cx.qpath_res(qpath, expr.hir_id)
1084 } else {
1085 return None;
1086 };
1087 if let Res::Def(DefKind::Fn, did) = def {
1088 if !def_id_is_transmute(cx, did) {
1089 return None;
1090 }
1091 let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
1092 let from = sig.inputs().skip_binder()[0];
1093 let to = sig.output().skip_binder();
1094 return Some((from, to));
1095 }
1096 None
1097 }
1098
1099 fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
1100 cx.tcx.is_intrinsic(def_id, sym::transmute)
1101 }
1102 }
1103}
1104
1105declare_lint! {
1106 /// The `unstable_features` lint detects uses of `#![feature]`.
1107 ///
1108 /// ### Example
1109 ///
1110 /// ```rust,compile_fail
1111 /// #![deny(unstable_features)]
1112 /// #![feature(test)]
1113 /// ```
1114 ///
1115 /// {{produces}}
1116 ///
1117 /// ### Explanation
1118 ///
1119 /// In larger nightly-based projects which
1120 ///
1121 /// * consist of a multitude of crates where a subset of crates has to compile on
1122 /// stable either unconditionally or depending on a `cfg` flag to for example
1123 /// allow stable users to depend on them,
1124 /// * don't use nightly for experimental features but for, e.g., unstable options only,
1125 ///
1126 /// this lint may come in handy to enforce policies of these kinds.
1127 UNSTABLE_FEATURES,
1128 Allow,
1129 "enabling unstable features"
1130}
1131
1132declare_lint_pass!(
1133 /// Forbids using the `#[feature(...)]` attribute
1134 UnstableFeatures => [UNSTABLE_FEATURES]
1135);
1136
1137impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
1138 fn check_attribute(&mut self, cx: &LateContext<'_>, attr: &hir::Attribute) {
1139 if attr.has_name(sym::feature)
1140 && let Some(items) = attr.meta_item_list()
1141 {
1142 for item in items {
1143 cx.emit_span_lint(UNSTABLE_FEATURES, item.span(), BuiltinUnstableFeatures);
1144 }
1145 }
1146 }
1147}
1148
1149declare_lint! {
1150 /// The `ungated_async_fn_track_caller` lint warns when the
1151 /// `#[track_caller]` attribute is used on an async function
1152 /// without enabling the corresponding unstable feature flag.
1153 ///
1154 /// ### Example
1155 ///
1156 /// ```rust
1157 /// #[track_caller]
1158 /// async fn foo() {}
1159 /// ```
1160 ///
1161 /// {{produces}}
1162 ///
1163 /// ### Explanation
1164 ///
1165 /// The attribute must be used in conjunction with the
1166 /// [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`
1167 /// annotation will function as a no-op.
1168 ///
1169 /// [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html
1170 UNGATED_ASYNC_FN_TRACK_CALLER,
1171 Warn,
1172 "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled"
1173}
1174
1175declare_lint_pass!(
1176 /// Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to
1177 /// do anything
1178 UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1179);
1180
1181impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
1182 fn check_fn(
1183 &mut self,
1184 cx: &LateContext<'_>,
1185 fn_kind: HirFnKind<'_>,
1186 _: &'tcx FnDecl<'_>,
1187 _: &'tcx Body<'_>,
1188 span: Span,
1189 def_id: LocalDefId,
1190 ) {
1191 if fn_kind.asyncness().is_async()
1192 && !cx.tcx.features().async_fn_track_caller()
1193 // Now, check if the function has the `#[track_caller]` attribute
1194 && let Some(attr_span) = find_attr!(cx.tcx.get_all_attrs(def_id), AttributeKind::TrackCaller(span) => *span)
1195 {
1196 cx.emit_span_lint(
1197 UNGATED_ASYNC_FN_TRACK_CALLER,
1198 attr_span,
1199 BuiltinUngatedAsyncFnTrackCaller { label: span, session: &cx.tcx.sess },
1200 );
1201 }
1202 }
1203}
1204
1205declare_lint! {
1206 /// The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that
1207 /// means neither directly accessible, nor reexported (with `pub use`), nor leaked through
1208 /// things like return types (which the [`unnameable_types`] lint can detect if desired).
1209 ///
1210 /// ### Example
1211 ///
1212 /// ```rust,compile_fail
1213 /// #![deny(unreachable_pub)]
1214 /// mod foo {
1215 /// pub mod bar {
1216 ///
1217 /// }
1218 /// }
1219 /// ```
1220 ///
1221 /// {{produces}}
1222 ///
1223 /// ### Explanation
1224 ///
1225 /// The `pub` keyword both expresses an intent for an item to be publicly available, and also
1226 /// signals to the compiler to make the item publicly accessible. The intent can only be
1227 /// satisfied, however, if all items which contain this item are *also* publicly accessible.
1228 /// Thus, this lint serves to identify situations where the intent does not match the reality.
1229 ///
1230 /// If you wish the item to be accessible elsewhere within the crate, but not outside it, the
1231 /// `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the
1232 /// intent that the item is only visible within its own crate.
1233 ///
1234 /// This lint is "allow" by default because it will trigger for a large amount of existing Rust code.
1235 /// Eventually it is desired for this to become warn-by-default.
1236 ///
1237 /// [`unnameable_types`]: #unnameable-types
1238 pub UNREACHABLE_PUB,
1239 Allow,
1240 "`pub` items not reachable from crate root"
1241}
1242
1243declare_lint_pass!(
1244 /// Lint for items marked `pub` that aren't reachable from other crates.
1245 UnreachablePub => [UNREACHABLE_PUB]
1246);
1247
1248impl UnreachablePub {
1249 fn perform_lint(
1250 &self,
1251 cx: &LateContext<'_>,
1252 what: &str,
1253 def_id: LocalDefId,
1254 vis_span: Span,
1255 exportable: bool,
1256 ) {
1257 let mut applicability = Applicability::MachineApplicable;
1258 if cx.tcx.visibility(def_id).is_public() && !cx.effective_visibilities.is_reachable(def_id)
1259 {
1260 // prefer suggesting `pub(super)` instead of `pub(crate)` when possible,
1261 // except when `pub(super) == pub(crate)`
1262 let new_vis = if let Some(ty::Visibility::Restricted(restricted_did)) =
1263 cx.effective_visibilities.effective_vis(def_id).map(|effective_vis| {
1264 effective_vis.at_level(rustc_middle::middle::privacy::Level::Reachable)
1265 })
1266 && let parent_parent = cx
1267 .tcx
1268 .parent_module_from_def_id(cx.tcx.parent_module_from_def_id(def_id).into())
1269 && *restricted_did == parent_parent.to_local_def_id()
1270 && !restricted_did.to_def_id().is_crate_root()
1271 {
1272 "pub(super)"
1273 } else {
1274 "pub(crate)"
1275 };
1276
1277 if vis_span.from_expansion() {
1278 applicability = Applicability::MaybeIncorrect;
1279 }
1280 let def_span = cx.tcx.def_span(def_id);
1281 cx.emit_span_lint(
1282 UNREACHABLE_PUB,
1283 def_span,
1284 BuiltinUnreachablePub {
1285 what,
1286 new_vis,
1287 suggestion: (vis_span, applicability),
1288 help: exportable,
1289 },
1290 );
1291 }
1292 }
1293}
1294
1295impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
1296 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1297 // Do not warn for fake `use` statements.
1298 if let hir::ItemKind::Use(_, hir::UseKind::ListStem) = &item.kind {
1299 return;
1300 }
1301 self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1302 }
1303
1304 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1305 self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1306 }
1307
1308 fn check_field_def(&mut self, _cx: &LateContext<'_>, _field: &hir::FieldDef<'_>) {
1309 // - If an ADT definition is reported then we don't need to check fields
1310 // (as it would add unnecessary complexity to the source code, the struct
1311 // definition is in the immediate proximity to give the "real" visibility).
1312 // - If an ADT is not reported because it's not `pub` - we don't need to
1313 // check fields.
1314 // - If an ADT is not reported because it's reachable - we also don't need
1315 // to check fields because then they are reachable by construction if they
1316 // are pub.
1317 //
1318 // Therefore in no case we check the fields.
1319 //
1320 // cf. https://github.com/rust-lang/rust/pull/126013#issuecomment-2152839205
1321 // cf. https://github.com/rust-lang/rust/pull/126040#issuecomment-2152944506
1322 }
1323
1324 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1325 if let ImplItemImplKind::Inherent { vis_span } = impl_item.impl_kind {
1326 self.perform_lint(cx, "item", impl_item.owner_id.def_id, vis_span, false);
1327 }
1328 }
1329}
1330
1331declare_lint! {
1332 /// The `type_alias_bounds` lint detects bounds in type aliases.
1333 ///
1334 /// ### Example
1335 ///
1336 /// ```rust
1337 /// type SendVec<T: Send> = Vec<T>;
1338 /// ```
1339 ///
1340 /// {{produces}}
1341 ///
1342 /// ### Explanation
1343 ///
1344 /// Trait and lifetime bounds on generic parameters and in where clauses of
1345 /// type aliases are not checked at usage sites of the type alias. Moreover,
1346 /// they are not thoroughly checked for correctness at their definition site
1347 /// either similar to the aliased type.
1348 ///
1349 /// This is a known limitation of the type checker that may be lifted in a
1350 /// future edition. Permitting such bounds in light of this was unintentional.
1351 ///
1352 /// While these bounds may have secondary effects such as enabling the use of
1353 /// "shorthand" associated type paths[^1] and affecting the default trait
1354 /// object lifetime[^2] of trait object types passed to the type alias, this
1355 /// should not have been allowed until the aforementioned restrictions of the
1356 /// type checker have been lifted.
1357 ///
1358 /// Using such bounds is highly discouraged as they are actively misleading.
1359 ///
1360 /// [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter
1361 /// bounded by trait `Trait` which defines an associated type called `Assoc`
1362 /// as opposed to a fully qualified path of the form `<T as Trait>::Assoc`.
1363 /// [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>
1364 TYPE_ALIAS_BOUNDS,
1365 Warn,
1366 "bounds in type aliases are not enforced"
1367}
1368
1369declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]);
1370
1371impl TypeAliasBounds {
1372 pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool {
1373 // Bounds of the form `T: 'a` with `T` type param affect object lifetime defaults.
1374 if let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind
1375 && pred.bounds.iter().any(|bound| matches!(bound, hir::GenericBound::Outlives(_)))
1376 && pred.bound_generic_params.is_empty() // indeed, even if absent from the RHS
1377 && pred.bounded_ty.as_generic_param().is_some()
1378 {
1379 return true;
1380 }
1381 false
1382 }
1383}
1384
1385impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
1386 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1387 let hir::ItemKind::TyAlias(_, generics, hir_ty) = item.kind else { return };
1388
1389 // There must not be a where clause.
1390 if generics.predicates.is_empty() {
1391 return;
1392 }
1393
1394 // Bounds of lazy type aliases and TAITs are respected.
1395 if cx.tcx.type_alias_is_lazy(item.owner_id) {
1396 return;
1397 }
1398
1399 // FIXME(generic_const_exprs): Revisit this before stabilization.
1400 // See also `tests/ui/const-generics/generic_const_exprs/type-alias-bounds.rs`.
1401 let ty = cx.tcx.type_of(item.owner_id).instantiate_identity();
1402 if ty.has_type_flags(ty::TypeFlags::HAS_CT_PROJECTION)
1403 && cx.tcx.features().generic_const_exprs()
1404 {
1405 return;
1406 }
1407
1408 // NOTE(inherent_associated_types): While we currently do take some bounds in type
1409 // aliases into consideration during IAT *selection*, we don't perform full use+def
1410 // site wfchecking for such type aliases. Therefore TAB should still trigger.
1411 // See also `tests/ui/associated-inherent-types/type-alias-bounds.rs`.
1412
1413 let mut where_spans = Vec::new();
1414 let mut inline_spans = Vec::new();
1415 let mut inline_sugg = Vec::new();
1416
1417 for p in generics.predicates {
1418 let span = p.span;
1419 if p.kind.in_where_clause() {
1420 where_spans.push(span);
1421 } else {
1422 for b in p.kind.bounds() {
1423 inline_spans.push(b.span());
1424 }
1425 inline_sugg.push((span, String::new()));
1426 }
1427 }
1428
1429 let mut ty = Some(hir_ty);
1430 let enable_feat_help = cx.tcx.sess.is_nightly_build();
1431
1432 if let [.., label_sp] = *where_spans {
1433 cx.emit_span_lint(
1434 TYPE_ALIAS_BOUNDS,
1435 where_spans,
1436 BuiltinTypeAliasBounds {
1437 in_where_clause: true,
1438 label: label_sp,
1439 enable_feat_help,
1440 suggestions: vec![(generics.where_clause_span, String::new())],
1441 preds: generics.predicates,
1442 ty: ty.take(),
1443 },
1444 );
1445 }
1446 if let [.., label_sp] = *inline_spans {
1447 cx.emit_span_lint(
1448 TYPE_ALIAS_BOUNDS,
1449 inline_spans,
1450 BuiltinTypeAliasBounds {
1451 in_where_clause: false,
1452 label: label_sp,
1453 enable_feat_help,
1454 suggestions: inline_sugg,
1455 preds: generics.predicates,
1456 ty,
1457 },
1458 );
1459 }
1460 }
1461}
1462
1463pub(crate) struct ShorthandAssocTyCollector {
1464 pub(crate) qselves: Vec<Span>,
1465}
1466
1467impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector {
1468 fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) {
1469 // Look for "type-parameter shorthand-associated-types". I.e., paths of the
1470 // form `T::Assoc` with `T` type param. These are reliant on trait bounds.
1471 if let hir::QPath::TypeRelative(qself, _) = qpath
1472 && qself.as_generic_param().is_some()
1473 {
1474 self.qselves.push(qself.span);
1475 }
1476 hir::intravisit::walk_qpath(self, qpath, id)
1477 }
1478}
1479
1480declare_lint! {
1481 /// The `trivial_bounds` lint detects trait bounds that don't depend on
1482 /// any type parameters.
1483 ///
1484 /// ### Example
1485 ///
1486 /// ```rust
1487 /// #![feature(trivial_bounds)]
1488 /// pub struct A where i32: Copy;
1489 /// ```
1490 ///
1491 /// {{produces}}
1492 ///
1493 /// ### Explanation
1494 ///
1495 /// Usually you would not write a trait bound that you know is always
1496 /// true, or never true. However, when using macros, the macro may not
1497 /// know whether or not the constraint would hold or not at the time when
1498 /// generating the code. Currently, the compiler does not alert you if the
1499 /// constraint is always true, and generates an error if it is never true.
1500 /// The `trivial_bounds` feature changes this to be a warning in both
1501 /// cases, giving macros more freedom and flexibility to generate code,
1502 /// while still providing a signal when writing non-macro code that
1503 /// something is amiss.
1504 ///
1505 /// See [RFC 2056] for more details. This feature is currently only
1506 /// available on the nightly channel, see [tracking issue #48214].
1507 ///
1508 /// [RFC 2056]: https://github.com/rust-lang/rfcs/blob/master/text/2056-allow-trivial-where-clause-constraints.md
1509 /// [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214
1510 TRIVIAL_BOUNDS,
1511 Warn,
1512 "these bounds don't depend on an type parameters"
1513}
1514
1515declare_lint_pass!(
1516 /// Lint for trait and lifetime bounds that don't depend on type parameters
1517 /// which either do nothing, or stop the item from being used.
1518 TrivialConstraints => [TRIVIAL_BOUNDS]
1519);
1520
1521impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
1522 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1523 use rustc_middle::ty::ClauseKind;
1524
1525 if cx.tcx.features().trivial_bounds() {
1526 let predicates = cx.tcx.predicates_of(item.owner_id);
1527 for &(predicate, span) in predicates.predicates {
1528 let predicate_kind_name = match predicate.kind().skip_binder() {
1529 ClauseKind::Trait(..) => "trait",
1530 ClauseKind::TypeOutlives(..) |
1531 ClauseKind::RegionOutlives(..) => "lifetime",
1532
1533 ClauseKind::UnstableFeature(_)
1534 // `ConstArgHasType` is never global as `ct` is always a param
1535 | ClauseKind::ConstArgHasType(..)
1536 // Ignore projections, as they can only be global
1537 // if the trait bound is global
1538 | ClauseKind::Projection(..)
1539 // Ignore bounds that a user can't type
1540 | ClauseKind::WellFormed(..)
1541 // FIXME(generic_const_exprs): `ConstEvaluatable` can be written
1542 | ClauseKind::ConstEvaluatable(..)
1543 // Users don't write this directly, only via another trait ref.
1544 | ty::ClauseKind::HostEffect(..) => continue,
1545 };
1546 if predicate.is_global() {
1547 cx.emit_span_lint(
1548 TRIVIAL_BOUNDS,
1549 span,
1550 BuiltinTrivialBounds { predicate_kind_name, predicate },
1551 );
1552 }
1553 }
1554 }
1555 }
1556}
1557
1558declare_lint! {
1559 /// The `double_negations` lint detects expressions of the form `--x`.
1560 ///
1561 /// ### Example
1562 ///
1563 /// ```rust
1564 /// fn main() {
1565 /// let x = 1;
1566 /// let _b = --x;
1567 /// }
1568 /// ```
1569 ///
1570 /// {{produces}}
1571 ///
1572 /// ### Explanation
1573 ///
1574 /// Negating something twice is usually the same as not negating it at all.
1575 /// However, a double negation in Rust can easily be confused with the
1576 /// prefix decrement operator that exists in many languages derived from C.
1577 /// Use `-(-x)` if you really wanted to negate the value twice.
1578 ///
1579 /// To decrement a value, use `x -= 1` instead.
1580 pub DOUBLE_NEGATIONS,
1581 Warn,
1582 "detects expressions of the form `--x`"
1583}
1584
1585declare_lint_pass!(
1586 /// Lint for expressions of the form `--x` that can be confused with C's
1587 /// prefix decrement operator.
1588 DoubleNegations => [DOUBLE_NEGATIONS]
1589);
1590
1591impl EarlyLintPass for DoubleNegations {
1592 #[inline]
1593 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1594 // only lint on the innermost `--` in a chain of `-` operators,
1595 // even if there are 3 or more negations
1596 if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1597 && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1598 && !matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1599 // Don't lint if this jumps macro expansion boundary (Issue #143980)
1600 && expr.span.eq_ctxt(inner.span)
1601 {
1602 cx.emit_span_lint(
1603 DOUBLE_NEGATIONS,
1604 expr.span,
1605 BuiltinDoubleNegations {
1606 add_parens: BuiltinDoubleNegationsAddParens {
1607 start_span: inner.span.shrink_to_lo(),
1608 end_span: inner.span.shrink_to_hi(),
1609 },
1610 },
1611 );
1612 }
1613 }
1614}
1615
1616declare_lint_pass!(
1617 /// Does nothing as a lint pass, but registers some `Lint`s
1618 /// which are used by other parts of the compiler.
1619 SoftLints => [
1620 WHILE_TRUE,
1621 NON_SHORTHAND_FIELD_PATTERNS,
1622 UNSAFE_CODE,
1623 MISSING_DOCS,
1624 MISSING_COPY_IMPLEMENTATIONS,
1625 MISSING_DEBUG_IMPLEMENTATIONS,
1626 ANONYMOUS_PARAMETERS,
1627 UNUSED_DOC_COMMENTS,
1628 NO_MANGLE_CONST_ITEMS,
1629 NO_MANGLE_GENERIC_ITEMS,
1630 MUTABLE_TRANSMUTES,
1631 UNSTABLE_FEATURES,
1632 UNREACHABLE_PUB,
1633 TYPE_ALIAS_BOUNDS,
1634 TRIVIAL_BOUNDS,
1635 DOUBLE_NEGATIONS
1636 ]
1637);
1638
1639declare_lint! {
1640 /// The `ellipsis_inclusive_range_patterns` lint detects the [`...` range
1641 /// pattern], which is deprecated.
1642 ///
1643 /// [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns
1644 ///
1645 /// ### Example
1646 ///
1647 /// ```rust,edition2018
1648 /// let x = 123;
1649 /// match x {
1650 /// 0...100 => {}
1651 /// _ => {}
1652 /// }
1653 /// ```
1654 ///
1655 /// {{produces}}
1656 ///
1657 /// ### Explanation
1658 ///
1659 /// The `...` range pattern syntax was changed to `..=` to avoid potential
1660 /// confusion with the [`..` range expression]. Use the new form instead.
1661 ///
1662 /// [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html
1663 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1664 Warn,
1665 "`...` range patterns are deprecated",
1666 @future_incompatible = FutureIncompatibleInfo {
1667 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2021),
1668 reference: "<https://doc.rust-lang.org/edition-guide/rust-2021/warnings-promoted-to-error.html>",
1669 };
1670}
1671
1672#[derive(Default)]
1673pub struct EllipsisInclusiveRangePatterns {
1674 /// If `Some(_)`, suppress all subsequent pattern
1675 /// warnings for better diagnostics.
1676 node_id: Option<ast::NodeId>,
1677}
1678
1679impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1680
1681impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1682 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1683 if self.node_id.is_some() {
1684 // Don't recursively warn about patterns inside range endpoints.
1685 return;
1686 }
1687
1688 use self::ast::PatKind;
1689 use self::ast::RangeSyntax::DotDotDot;
1690
1691 /// If `pat` is a `...` pattern, return the start and end of the range, as well as the span
1692 /// corresponding to the ellipsis.
1693 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1694 match &pat.kind {
1695 PatKind::Range(
1696 a,
1697 Some(b),
1698 Spanned { span, node: RangeEnd::Included(DotDotDot) },
1699 ) => Some((a.as_deref(), b, *span)),
1700 _ => None,
1701 }
1702 }
1703
1704 let (parentheses, endpoints) = match &pat.kind {
1705 PatKind::Ref(subpat, _, _) => (true, matches_ellipsis_pat(subpat)),
1706 _ => (false, matches_ellipsis_pat(pat)),
1707 };
1708
1709 if let Some((start, end, join)) = endpoints {
1710 if parentheses {
1711 self.node_id = Some(pat.id);
1712 let end = expr_to_string(end);
1713 let replace = match start {
1714 Some(start) => format!("&({}..={})", expr_to_string(start), end),
1715 None => format!("&(..={end})"),
1716 };
1717 if join.edition() >= Edition::Edition2021 {
1718 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1719 span: pat.span,
1720 suggestion: pat.span,
1721 replace,
1722 });
1723 } else {
1724 cx.emit_span_lint(
1725 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1726 pat.span,
1727 BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1728 suggestion: pat.span,
1729 replace,
1730 },
1731 );
1732 }
1733 } else {
1734 let replace = "..=";
1735 if join.edition() >= Edition::Edition2021 {
1736 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1737 span: pat.span,
1738 suggestion: join,
1739 replace: replace.to_string(),
1740 });
1741 } else {
1742 cx.emit_span_lint(
1743 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1744 join,
1745 BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1746 suggestion: join,
1747 },
1748 );
1749 }
1750 };
1751 }
1752 }
1753
1754 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1755 if let Some(node_id) = self.node_id {
1756 if pat.id == node_id {
1757 self.node_id = None
1758 }
1759 }
1760 }
1761}
1762
1763declare_lint! {
1764 /// The `keyword_idents_2018` lint detects edition keywords being used as an
1765 /// identifier.
1766 ///
1767 /// ### Example
1768 ///
1769 /// ```rust,edition2015,compile_fail
1770 /// #![deny(keyword_idents_2018)]
1771 /// // edition 2015
1772 /// fn dyn() {}
1773 /// ```
1774 ///
1775 /// {{produces}}
1776 ///
1777 /// ### Explanation
1778 ///
1779 /// Rust [editions] allow the language to evolve without breaking
1780 /// backwards compatibility. This lint catches code that uses new keywords
1781 /// that are added to the language that are used as identifiers (such as a
1782 /// variable name, function name, etc.). If you switch the compiler to a
1783 /// new edition without updating the code, then it will fail to compile if
1784 /// you are using a new keyword as an identifier.
1785 ///
1786 /// You can manually change the identifiers to a non-keyword, or use a
1787 /// [raw identifier], for example `r#dyn`, to transition to a new edition.
1788 ///
1789 /// This lint solves the problem automatically. It is "allow" by default
1790 /// because the code is perfectly valid in older editions. The [`cargo
1791 /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1792 /// and automatically apply the suggested fix from the compiler (which is
1793 /// to use a raw identifier). This provides a completely automated way to
1794 /// update old code for a new edition.
1795 ///
1796 /// [editions]: https://doc.rust-lang.org/edition-guide/
1797 /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1798 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1799 pub KEYWORD_IDENTS_2018,
1800 Allow,
1801 "detects edition keywords being used as an identifier",
1802 @future_incompatible = FutureIncompatibleInfo {
1803 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2018),
1804 reference: "issue #49716 <https://github.com/rust-lang/rust/issues/49716>",
1805 };
1806}
1807
1808declare_lint! {
1809 /// The `keyword_idents_2024` lint detects edition keywords being used as an
1810 /// identifier.
1811 ///
1812 /// ### Example
1813 ///
1814 /// ```rust,edition2015,compile_fail
1815 /// #![deny(keyword_idents_2024)]
1816 /// // edition 2015
1817 /// fn gen() {}
1818 /// ```
1819 ///
1820 /// {{produces}}
1821 ///
1822 /// ### Explanation
1823 ///
1824 /// Rust [editions] allow the language to evolve without breaking
1825 /// backwards compatibility. This lint catches code that uses new keywords
1826 /// that are added to the language that are used as identifiers (such as a
1827 /// variable name, function name, etc.). If you switch the compiler to a
1828 /// new edition without updating the code, then it will fail to compile if
1829 /// you are using a new keyword as an identifier.
1830 ///
1831 /// You can manually change the identifiers to a non-keyword, or use a
1832 /// [raw identifier], for example `r#gen`, to transition to a new edition.
1833 ///
1834 /// This lint solves the problem automatically. It is "allow" by default
1835 /// because the code is perfectly valid in older editions. The [`cargo
1836 /// fix`] tool with the `--edition` flag will switch this lint to "warn"
1837 /// and automatically apply the suggested fix from the compiler (which is
1838 /// to use a raw identifier). This provides a completely automated way to
1839 /// update old code for a new edition.
1840 ///
1841 /// [editions]: https://doc.rust-lang.org/edition-guide/
1842 /// [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html
1843 /// [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html
1844 pub KEYWORD_IDENTS_2024,
1845 Allow,
1846 "detects edition keywords being used as an identifier",
1847 @future_incompatible = FutureIncompatibleInfo {
1848 reason: FutureIncompatibilityReason::EditionError(Edition::Edition2024),
1849 reference: "<https://doc.rust-lang.org/edition-guide/rust-2024/gen-keyword.html>",
1850 };
1851}
1852
1853declare_lint_pass!(
1854 /// Check for uses of edition keywords used as an identifier.
1855 KeywordIdents => [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]
1856);
1857
1858struct UnderMacro(bool);
1859
1860impl KeywordIdents {
1861 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1862 // Check if the preceding token is `$`, because we want to allow `$async`, etc.
1863 let mut prev_dollar = false;
1864 for tt in tokens.iter() {
1865 match tt {
1866 // Only report non-raw idents.
1867 TokenTree::Token(token, _) => {
1868 if let Some((ident, token::IdentIsRaw::No)) = token.ident() {
1869 if !prev_dollar {
1870 self.check_ident_token(cx, UnderMacro(true), ident, "");
1871 }
1872 } else if let Some((ident, token::IdentIsRaw::No)) = token.lifetime() {
1873 self.check_ident_token(
1874 cx,
1875 UnderMacro(true),
1876 ident.without_first_quote(),
1877 "'",
1878 );
1879 } else if token.kind == TokenKind::Dollar {
1880 prev_dollar = true;
1881 continue;
1882 }
1883 }
1884 TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts),
1885 }
1886 prev_dollar = false;
1887 }
1888 }
1889
1890 fn check_ident_token(
1891 &mut self,
1892 cx: &EarlyContext<'_>,
1893 UnderMacro(under_macro): UnderMacro,
1894 ident: Ident,
1895 prefix: &'static str,
1896 ) {
1897 let (lint, edition) = match ident.name {
1898 kw::Async | kw::Await | kw::Try => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1899
1900 // rust-lang/rust#56327: Conservatively do not
1901 // attempt to report occurrences of `dyn` within
1902 // macro definitions or invocations, because `dyn`
1903 // can legitimately occur as a contextual keyword
1904 // in 2015 code denoting its 2018 meaning, and we
1905 // do not want rustfix to inject bugs into working
1906 // code by rewriting such occurrences.
1907 //
1908 // But if we see `dyn` outside of a macro, we know
1909 // its precise role in the parsed AST and thus are
1910 // assured this is truly an attempt to use it as
1911 // an identifier.
1912 kw::Dyn if !under_macro => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1913
1914 kw::Gen => (KEYWORD_IDENTS_2024, Edition::Edition2024),
1915
1916 _ => return,
1917 };
1918
1919 // Don't lint `r#foo`.
1920 if ident.span.edition() >= edition
1921 || cx.sess().psess.raw_identifier_spans.contains(ident.span)
1922 {
1923 return;
1924 }
1925
1926 cx.emit_span_lint(
1927 lint,
1928 ident.span,
1929 BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix },
1930 );
1931 }
1932}
1933
1934impl EarlyLintPass for KeywordIdents {
1935 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1936 self.check_tokens(cx, &mac_def.body.tokens);
1937 }
1938 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1939 self.check_tokens(cx, &mac.args.tokens);
1940 }
1941 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) {
1942 if ident.name.as_str().starts_with('\'') {
1943 self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'");
1944 } else {
1945 self.check_ident_token(cx, UnderMacro(false), *ident, "");
1946 }
1947 }
1948}
1949
1950declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1951
1952impl ExplicitOutlivesRequirements {
1953 fn lifetimes_outliving_lifetime<'tcx>(
1954 tcx: TyCtxt<'tcx>,
1955 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1956 item: LocalDefId,
1957 lifetime: LocalDefId,
1958 ) -> Vec<ty::Region<'tcx>> {
1959 let item_generics = tcx.generics_of(item);
1960
1961 inferred_outlives
1962 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1963 ty::ClauseKind::RegionOutlives(ty::OutlivesPredicate(a, b)) => match a.kind() {
1964 ty::ReEarlyParam(ebr)
1965 if item_generics.region_param(ebr, tcx).def_id == lifetime.to_def_id() =>
1966 {
1967 Some(b)
1968 }
1969 _ => None,
1970 },
1971 _ => None,
1972 })
1973 .collect()
1974 }
1975
1976 fn lifetimes_outliving_type<'tcx>(
1977 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1978 index: u32,
1979 ) -> Vec<ty::Region<'tcx>> {
1980 inferred_outlives
1981 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1982 ty::ClauseKind::TypeOutlives(ty::OutlivesPredicate(a, b)) => {
1983 a.is_param(index).then_some(b)
1984 }
1985 _ => None,
1986 })
1987 .collect()
1988 }
1989
1990 fn collect_outlives_bound_spans<'tcx>(
1991 &self,
1992 tcx: TyCtxt<'tcx>,
1993 bounds: &hir::GenericBounds<'_>,
1994 inferred_outlives: &[ty::Region<'tcx>],
1995 predicate_span: Span,
1996 item: DefId,
1997 ) -> Vec<(usize, Span)> {
1998 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1999
2000 let item_generics = tcx.generics_of(item);
2001
2002 bounds
2003 .iter()
2004 .enumerate()
2005 .filter_map(|(i, bound)| {
2006 let hir::GenericBound::Outlives(lifetime) = bound else {
2007 return None;
2008 };
2009
2010 let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
2011 Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
2012 .iter()
2013 .any(|r| matches!(r.kind(), ty::ReEarlyParam(ebr) if { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() })),
2014 _ => false,
2015 };
2016
2017 if !is_inferred {
2018 return None;
2019 }
2020
2021 let span = bound.span().find_ancestor_inside(predicate_span)?;
2022 if span.in_external_macro(tcx.sess.source_map()) {
2023 return None;
2024 }
2025
2026 Some((i, span))
2027 })
2028 .collect()
2029 }
2030
2031 fn consolidate_outlives_bound_spans(
2032 &self,
2033 lo: Span,
2034 bounds: &hir::GenericBounds<'_>,
2035 bound_spans: Vec<(usize, Span)>,
2036 ) -> Vec<Span> {
2037 if bounds.is_empty() {
2038 return Vec::new();
2039 }
2040 if bound_spans.len() == bounds.len() {
2041 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
2042 // If all bounds are inferable, we want to delete the colon, so
2043 // start from just after the parameter (span passed as argument)
2044 vec![lo.to(last_bound_span)]
2045 } else {
2046 let mut merged = Vec::new();
2047 let mut last_merged_i = None;
2048
2049 let mut from_start = true;
2050 for (i, bound_span) in bound_spans {
2051 match last_merged_i {
2052 // If the first bound is inferable, our span should also eat the leading `+`.
2053 None if i == 0 => {
2054 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
2055 last_merged_i = Some(0);
2056 }
2057 // If consecutive bounds are inferable, merge their spans
2058 Some(h) if i == h + 1 => {
2059 if let Some(tail) = merged.last_mut() {
2060 // Also eat the trailing `+` if the first
2061 // more-than-one bound is inferable
2062 let to_span = if from_start && i < bounds.len() {
2063 bounds[i + 1].span().shrink_to_lo()
2064 } else {
2065 bound_span
2066 };
2067 *tail = tail.to(to_span);
2068 last_merged_i = Some(i);
2069 } else {
2070 bug!("another bound-span visited earlier");
2071 }
2072 }
2073 _ => {
2074 // When we find a non-inferable bound, subsequent inferable bounds
2075 // won't be consecutive from the start (and we'll eat the leading
2076 // `+` rather than the trailing one)
2077 from_start = false;
2078 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
2079 last_merged_i = Some(i);
2080 }
2081 }
2082 }
2083 merged
2084 }
2085 }
2086}
2087
2088impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
2089 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
2090 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
2091
2092 let def_id = item.owner_id.def_id;
2093 if let hir::ItemKind::Struct(_, generics, _)
2094 | hir::ItemKind::Enum(_, generics, _)
2095 | hir::ItemKind::Union(_, generics, _) = item.kind
2096 {
2097 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
2098 if inferred_outlives.is_empty() {
2099 return;
2100 }
2101
2102 let ty_generics = cx.tcx.generics_of(def_id);
2103 let num_where_predicates = generics
2104 .predicates
2105 .iter()
2106 .filter(|predicate| predicate.kind.in_where_clause())
2107 .count();
2108
2109 let mut bound_count = 0;
2110 let mut lint_spans = Vec::new();
2111 let mut where_lint_spans = Vec::new();
2112 let mut dropped_where_predicate_count = 0;
2113 for (i, where_predicate) in generics.predicates.iter().enumerate() {
2114 let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2115 match where_predicate.kind {
2116 hir::WherePredicateKind::RegionPredicate(predicate) => {
2117 if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2118 cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2119 {
2120 (
2121 Self::lifetimes_outliving_lifetime(
2122 cx.tcx,
2123 // don't warn if the inferred span actually came from the predicate we're looking at
2124 // this happens if the type is recursively defined
2125 inferred_outlives.iter().filter(|(_, span)| {
2126 !where_predicate.span.contains(*span)
2127 }),
2128 item.owner_id.def_id,
2129 region_def_id,
2130 ),
2131 &predicate.bounds,
2132 where_predicate.span,
2133 predicate.in_where_clause,
2134 )
2135 } else {
2136 continue;
2137 }
2138 }
2139 hir::WherePredicateKind::BoundPredicate(predicate) => {
2140 // FIXME we can also infer bounds on associated types,
2141 // and should check for them here.
2142 match predicate.bounded_ty.kind {
2143 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2144 let Res::Def(DefKind::TyParam, def_id) = path.res else {
2145 continue;
2146 };
2147 let index = ty_generics.param_def_id_to_index[&def_id];
2148 (
2149 Self::lifetimes_outliving_type(
2150 // don't warn if the inferred span actually came from the predicate we're looking at
2151 // this happens if the type is recursively defined
2152 inferred_outlives.iter().filter(|(_, span)| {
2153 !where_predicate.span.contains(*span)
2154 }),
2155 index,
2156 ),
2157 &predicate.bounds,
2158 where_predicate.span,
2159 predicate.origin == PredicateOrigin::WhereClause,
2160 )
2161 }
2162 _ => {
2163 continue;
2164 }
2165 }
2166 }
2167 _ => continue,
2168 };
2169 if relevant_lifetimes.is_empty() {
2170 continue;
2171 }
2172
2173 let bound_spans = self.collect_outlives_bound_spans(
2174 cx.tcx,
2175 bounds,
2176 &relevant_lifetimes,
2177 predicate_span,
2178 item.owner_id.to_def_id(),
2179 );
2180 bound_count += bound_spans.len();
2181
2182 let drop_predicate = bound_spans.len() == bounds.len();
2183 if drop_predicate && in_where_clause {
2184 dropped_where_predicate_count += 1;
2185 }
2186
2187 if drop_predicate {
2188 if !in_where_clause {
2189 lint_spans.push(predicate_span);
2190 } else if predicate_span.from_expansion() {
2191 // Don't try to extend the span if it comes from a macro expansion.
2192 where_lint_spans.push(predicate_span);
2193 } else if i + 1 < num_where_predicates {
2194 // If all the bounds on a predicate were inferable and there are
2195 // further predicates, we want to eat the trailing comma.
2196 let next_predicate_span = generics.predicates[i + 1].span;
2197 if next_predicate_span.from_expansion() {
2198 where_lint_spans.push(predicate_span);
2199 } else {
2200 where_lint_spans
2201 .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2202 }
2203 } else {
2204 // Eat the optional trailing comma after the last predicate.
2205 let where_span = generics.where_clause_span;
2206 if where_span.from_expansion() {
2207 where_lint_spans.push(predicate_span);
2208 } else {
2209 where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2210 }
2211 }
2212 } else {
2213 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2214 predicate_span.shrink_to_lo(),
2215 bounds,
2216 bound_spans,
2217 ));
2218 }
2219 }
2220
2221 // If all predicates in where clause are inferable, drop the entire clause
2222 // (including the `where`)
2223 if generics.has_where_clause_predicates
2224 && dropped_where_predicate_count == num_where_predicates
2225 {
2226 let where_span = generics.where_clause_span;
2227 // Extend the where clause back to the closing `>` of the
2228 // generics, except for tuple struct, which have the `where`
2229 // after the fields of the struct.
2230 let full_where_span =
2231 if let hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(..)) = item.kind {
2232 where_span
2233 } else {
2234 generics.span.shrink_to_hi().to(where_span)
2235 };
2236
2237 // Due to macro expansions, the `full_where_span` might not actually contain all
2238 // predicates.
2239 if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2240 lint_spans.push(full_where_span);
2241 } else {
2242 lint_spans.extend(where_lint_spans);
2243 }
2244 } else {
2245 lint_spans.extend(where_lint_spans);
2246 }
2247
2248 if !lint_spans.is_empty() {
2249 // Do not automatically delete outlives requirements from macros.
2250 let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2251 {
2252 Applicability::MachineApplicable
2253 } else {
2254 Applicability::MaybeIncorrect
2255 };
2256
2257 // Due to macros, there might be several predicates with the same span
2258 // and we only want to suggest removing them once.
2259 lint_spans.sort_unstable();
2260 lint_spans.dedup();
2261
2262 cx.emit_span_lint(
2263 EXPLICIT_OUTLIVES_REQUIREMENTS,
2264 lint_spans.clone(),
2265 BuiltinExplicitOutlives {
2266 count: bound_count,
2267 suggestion: BuiltinExplicitOutlivesSuggestion {
2268 spans: lint_spans,
2269 applicability,
2270 },
2271 },
2272 );
2273 }
2274 }
2275 }
2276}
2277
2278declare_lint! {
2279 /// The `incomplete_features` lint detects unstable features enabled with
2280 /// the [`feature` attribute] that may function improperly in some or all
2281 /// cases.
2282 ///
2283 /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2284 ///
2285 /// ### Example
2286 ///
2287 /// ```rust
2288 /// #![feature(generic_const_exprs)]
2289 /// ```
2290 ///
2291 /// {{produces}}
2292 ///
2293 /// ### Explanation
2294 ///
2295 /// Although it is encouraged for people to experiment with unstable
2296 /// features, some of them are known to be incomplete or faulty. This lint
2297 /// is a signal that the feature has not yet been finished, and you may
2298 /// experience problems with it.
2299 pub INCOMPLETE_FEATURES,
2300 Warn,
2301 "incomplete features that may function improperly in some or all cases"
2302}
2303
2304declare_lint! {
2305 /// The `internal_features` lint detects unstable features enabled with
2306 /// the [`feature` attribute] that are internal to the compiler or standard
2307 /// library.
2308 ///
2309 /// [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/
2310 ///
2311 /// ### Example
2312 ///
2313 /// ```rust
2314 /// #![feature(rustc_attrs)]
2315 /// ```
2316 ///
2317 /// {{produces}}
2318 ///
2319 /// ### Explanation
2320 ///
2321 /// These features are an implementation detail of the compiler and standard
2322 /// library and are not supposed to be used in user code.
2323 pub INTERNAL_FEATURES,
2324 Warn,
2325 "internal features are not supposed to be used"
2326}
2327
2328declare_lint_pass!(
2329 /// Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`.
2330 IncompleteInternalFeatures => [INCOMPLETE_FEATURES, INTERNAL_FEATURES]
2331);
2332
2333impl EarlyLintPass for IncompleteInternalFeatures {
2334 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2335 let features = cx.builder.features();
2336
2337 features
2338 .enabled_features_iter_stable_order()
2339 .filter(|(name, _)| features.incomplete(*name) || features.internal(*name))
2340 .for_each(|(name, span)| {
2341 if features.incomplete(name) {
2342 let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2343 .map(|n| BuiltinFeatureIssueNote { n });
2344 let help =
2345 HAS_MIN_FEATURES.contains(&name).then_some(BuiltinIncompleteFeaturesHelp);
2346
2347 cx.emit_span_lint(
2348 INCOMPLETE_FEATURES,
2349 span,
2350 BuiltinIncompleteFeatures { name, note, help },
2351 );
2352 } else {
2353 cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name });
2354 }
2355 });
2356 }
2357}
2358
2359const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2360
2361declare_lint! {
2362 /// The `invalid_value` lint detects creating a value that is not valid,
2363 /// such as a null reference.
2364 ///
2365 /// ### Example
2366 ///
2367 /// ```rust,no_run
2368 /// # #![allow(unused)]
2369 /// unsafe {
2370 /// let x: &'static i32 = std::mem::zeroed();
2371 /// }
2372 /// ```
2373 ///
2374 /// {{produces}}
2375 ///
2376 /// ### Explanation
2377 ///
2378 /// In some situations the compiler can detect that the code is creating
2379 /// an invalid value, which should be avoided.
2380 ///
2381 /// In particular, this lint will check for improper use of
2382 /// [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and
2383 /// [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The
2384 /// lint should provide extra information to indicate what the problem is
2385 /// and a possible solution.
2386 ///
2387 /// [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html
2388 /// [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html
2389 /// [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html
2390 /// [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init
2391 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2392 pub INVALID_VALUE,
2393 Warn,
2394 "an invalid value is being created (such as a null reference)"
2395}
2396
2397declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2398
2399/// Information about why a type cannot be initialized this way.
2400pub struct InitError {
2401 pub(crate) message: String,
2402 /// Spans from struct fields and similar that can be obtained from just the type.
2403 pub(crate) span: Option<Span>,
2404 /// Used to report a trace through adts.
2405 pub(crate) nested: Option<Box<InitError>>,
2406}
2407impl InitError {
2408 fn spanned(self, span: Span) -> InitError {
2409 Self { span: Some(span), ..self }
2410 }
2411
2412 fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2413 assert!(self.nested.is_none());
2414 Self { nested: nested.into().map(Box::new), ..self }
2415 }
2416}
2417
2418impl<'a> From<&'a str> for InitError {
2419 fn from(s: &'a str) -> Self {
2420 s.to_owned().into()
2421 }
2422}
2423impl From<String> for InitError {
2424 fn from(message: String) -> Self {
2425 Self { message, span: None, nested: None }
2426 }
2427}
2428
2429impl<'tcx> LateLintPass<'tcx> for InvalidValue {
2430 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2431 #[derive(Debug, Copy, Clone, PartialEq)]
2432 enum InitKind {
2433 Zeroed,
2434 Uninit,
2435 }
2436
2437 /// Test if this constant is all-0.
2438 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2439 use hir::ExprKind::*;
2440 use rustc_ast::LitKind::*;
2441 match &expr.kind {
2442 Lit(lit) => {
2443 if let Int(i, _) = lit.node {
2444 i == 0
2445 } else {
2446 false
2447 }
2448 }
2449 Tup(tup) => tup.iter().all(is_zero),
2450 _ => false,
2451 }
2452 }
2453
2454 /// Determine if this expression is a "dangerous initialization".
2455 fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2456 if let hir::ExprKind::Call(path_expr, args) = expr.kind
2457 // Find calls to `mem::{uninitialized,zeroed}` methods.
2458 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2459 {
2460 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2461 match cx.tcx.get_diagnostic_name(def_id) {
2462 Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2463 Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2464 Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2465 _ => {}
2466 }
2467 } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2468 // Find problematic calls to `MaybeUninit::assume_init`.
2469 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2470 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2471 // This is a call to *some* method named `assume_init`.
2472 // See if the `self` parameter is one of the dangerous constructors.
2473 if let hir::ExprKind::Call(path_expr, _) = receiver.kind
2474 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2475 {
2476 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2477 match cx.tcx.get_diagnostic_name(def_id) {
2478 Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2479 Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2480 _ => {}
2481 }
2482 }
2483 }
2484 }
2485
2486 None
2487 }
2488
2489 fn variant_find_init_error<'tcx>(
2490 cx: &LateContext<'tcx>,
2491 ty: Ty<'tcx>,
2492 variant: &VariantDef,
2493 args: ty::GenericArgsRef<'tcx>,
2494 descr: &str,
2495 init: InitKind,
2496 ) -> Option<InitError> {
2497 let mut field_err = variant.fields.iter().find_map(|field| {
2498 ty_find_init_error(cx, field.ty(cx.tcx, args), init).map(|mut err| {
2499 if !field.did.is_local() {
2500 err
2501 } else if err.span.is_none() {
2502 err.span = Some(cx.tcx.def_span(field.did));
2503 write!(&mut err.message, " (in this {descr})").unwrap();
2504 err
2505 } else {
2506 InitError::from(format!("in this {descr}"))
2507 .spanned(cx.tcx.def_span(field.did))
2508 .nested(err)
2509 }
2510 })
2511 });
2512
2513 // Check if this ADT has a constrained layout (like `NonNull` and friends).
2514 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(ty)) {
2515 if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair(scalar, _) =
2516 &layout.backend_repr
2517 {
2518 let range = scalar.valid_range(cx);
2519 let msg = if !range.contains(0) {
2520 "must be non-null"
2521 } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2522 // Prefer reporting on the fields over the entire struct for uninit,
2523 // as the information bubbles out and it may be unclear why the type can't
2524 // be null from just its outside signature.
2525
2526 "must be initialized inside its custom valid range"
2527 } else {
2528 return field_err;
2529 };
2530 if let Some(field_err) = &mut field_err {
2531 // Most of the time, if the field error is the same as the struct error,
2532 // the struct error only happens because of the field error.
2533 if field_err.message.contains(msg) {
2534 field_err.message = format!("because {}", field_err.message);
2535 }
2536 }
2537 return Some(InitError::from(format!("`{ty}` {msg}")).nested(field_err));
2538 }
2539 }
2540 field_err
2541 }
2542
2543 /// Return `Some` only if we are sure this type does *not*
2544 /// allow zero initialization.
2545 fn ty_find_init_error<'tcx>(
2546 cx: &LateContext<'tcx>,
2547 ty: Ty<'tcx>,
2548 init: InitKind,
2549 ) -> Option<InitError> {
2550 let ty = cx.tcx.try_normalize_erasing_regions(cx.typing_env(), ty).unwrap_or(ty);
2551
2552 match ty.kind() {
2553 // Primitive types that don't like 0 as a value.
2554 ty::Ref(..) => Some("references must be non-null".into()),
2555 ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2556 ty::FnPtr(..) => Some("function pointers must be non-null".into()),
2557 ty::Never => Some("the `!` type has no valid value".into()),
2558 ty::RawPtr(ty, _) if matches!(ty.kind(), ty::Dynamic(..)) =>
2559 // raw ptr to dyn Trait
2560 {
2561 Some("the vtable of a wide raw pointer must be non-null".into())
2562 }
2563 // Primitive types with other constraints.
2564 ty::Bool if init == InitKind::Uninit => {
2565 Some("booleans must be either `true` or `false`".into())
2566 }
2567 ty::Char if init == InitKind::Uninit => {
2568 Some("characters must be a valid Unicode codepoint".into())
2569 }
2570 ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => {
2571 Some("integers must be initialized".into())
2572 }
2573 ty::Float(_) if init == InitKind::Uninit => {
2574 Some("floats must be initialized".into())
2575 }
2576 ty::RawPtr(_, _) if init == InitKind::Uninit => {
2577 Some("raw pointers must be initialized".into())
2578 }
2579 // Recurse and checks for some compound types. (but not unions)
2580 ty::Adt(adt_def, args) if !adt_def.is_union() => {
2581 // Handle structs.
2582 if adt_def.is_struct() {
2583 return variant_find_init_error(
2584 cx,
2585 ty,
2586 adt_def.non_enum_variant(),
2587 args,
2588 "struct field",
2589 init,
2590 );
2591 }
2592 // And now, enums.
2593 let span = cx.tcx.def_span(adt_def.did());
2594 let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2595 let definitely_inhabited = match variant
2596 .inhabited_predicate(cx.tcx, *adt_def)
2597 .instantiate(cx.tcx, args)
2598 .apply_any_module(cx.tcx, cx.typing_env())
2599 {
2600 // Entirely skip uninhabited variants.
2601 Some(false) => return None,
2602 // Forward the others, but remember which ones are definitely inhabited.
2603 Some(true) => true,
2604 None => false,
2605 };
2606 Some((variant, definitely_inhabited))
2607 });
2608 let Some(first_variant) = potential_variants.next() else {
2609 return Some(
2610 InitError::from("enums with no inhabited variants have no valid value")
2611 .spanned(span),
2612 );
2613 };
2614 // So we have at least one potentially inhabited variant. Might we have two?
2615 let Some(second_variant) = potential_variants.next() else {
2616 // There is only one potentially inhabited variant. So we can recursively
2617 // check that variant!
2618 return variant_find_init_error(
2619 cx,
2620 ty,
2621 first_variant.0,
2622 args,
2623 "field of the only potentially inhabited enum variant",
2624 init,
2625 );
2626 };
2627 // So we have at least two potentially inhabited variants. If we can prove that
2628 // we have at least two *definitely* inhabited variants, then we have a tag and
2629 // hence leaving this uninit is definitely disallowed. (Leaving it zeroed could
2630 // be okay, depending on which variant is encoded as zero tag.)
2631 if init == InitKind::Uninit {
2632 let definitely_inhabited = (first_variant.1 as usize)
2633 + (second_variant.1 as usize)
2634 + potential_variants
2635 .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2636 .count();
2637 if definitely_inhabited > 1 {
2638 return Some(InitError::from(
2639 "enums with multiple inhabited variants have to be initialized to a variant",
2640 ).spanned(span));
2641 }
2642 }
2643 // We couldn't find anything wrong here.
2644 None
2645 }
2646 ty::Tuple(..) => {
2647 // Proceed recursively, check all fields.
2648 ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2649 }
2650 ty::Array(ty, len) => {
2651 if matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
2652 // Array length known at array non-empty -- recurse.
2653 ty_find_init_error(cx, *ty, init)
2654 } else {
2655 // Empty array or size unknown.
2656 None
2657 }
2658 }
2659 // Conservative fallback.
2660 _ => None,
2661 }
2662 }
2663
2664 if let Some(init) = is_dangerous_init(cx, expr) {
2665 // This conjures an instance of a type out of nothing,
2666 // using zeroed or uninitialized memory.
2667 // We are extremely conservative with what we warn about.
2668 let conjured_ty = cx.typeck_results().expr_ty(expr);
2669 if let Some(err) = with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2670 let msg = match init {
2671 InitKind::Zeroed => fluent::lint_builtin_unpermitted_type_init_zeroed,
2672 InitKind::Uninit => fluent::lint_builtin_unpermitted_type_init_uninit,
2673 };
2674 let sub = BuiltinUnpermittedTypeInitSub { err };
2675 cx.emit_span_lint(
2676 INVALID_VALUE,
2677 expr.span,
2678 BuiltinUnpermittedTypeInit {
2679 msg,
2680 ty: conjured_ty,
2681 label: expr.span,
2682 sub,
2683 tcx: cx.tcx,
2684 },
2685 );
2686 }
2687 }
2688 }
2689}
2690
2691declare_lint! {
2692 /// The `deref_nullptr` lint detects when a null pointer is dereferenced,
2693 /// which causes [undefined behavior].
2694 ///
2695 /// ### Example
2696 ///
2697 /// ```rust,compile_fail
2698 /// # #![allow(unused)]
2699 /// # #![cfg_attr(bootstrap, deny(deref_nullptr))]
2700 /// use std::ptr;
2701 /// unsafe {
2702 /// let x = &*ptr::null::<i32>();
2703 /// let x = ptr::addr_of!(*ptr::null::<i32>());
2704 /// let x = *(0 as *const i32);
2705 /// }
2706 /// ```
2707 ///
2708 /// {{produces}}
2709 ///
2710 /// ### Explanation
2711 ///
2712 /// Dereferencing a null pointer causes [undefined behavior] if it is accessed
2713 /// (loaded from or stored to).
2714 ///
2715 /// [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html
2716 pub DEREF_NULLPTR,
2717 Deny,
2718 "detects when an null pointer is dereferenced"
2719}
2720
2721declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
2722
2723impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
2724 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2725 /// test if expression is a null ptr
2726 fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
2727 let pointer_ty = cx.typeck_results().expr_ty(expr);
2728 let ty::RawPtr(pointee, _) = pointer_ty.kind() else {
2729 return false;
2730 };
2731 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(*pointee)) {
2732 if layout.layout.size() == rustc_abi::Size::ZERO {
2733 return false;
2734 }
2735 }
2736
2737 match &expr.kind {
2738 hir::ExprKind::Cast(expr, ty) => {
2739 if let hir::TyKind::Ptr(_) = ty.kind {
2740 return is_zero(expr) || is_null_ptr(cx, expr);
2741 }
2742 }
2743 // check for call to `core::ptr::null` or `core::ptr::null_mut`
2744 hir::ExprKind::Call(path, _) => {
2745 if let hir::ExprKind::Path(ref qpath) = path.kind
2746 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
2747 {
2748 return matches!(
2749 cx.tcx.get_diagnostic_name(def_id),
2750 Some(sym::ptr_null | sym::ptr_null_mut)
2751 );
2752 }
2753 }
2754 _ => {}
2755 }
2756 false
2757 }
2758
2759 /// test if expression is the literal `0`
2760 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2761 match &expr.kind {
2762 hir::ExprKind::Lit(lit) => {
2763 if let LitKind::Int(a, _) = lit.node {
2764 return a == 0;
2765 }
2766 }
2767 _ => {}
2768 }
2769 false
2770 }
2771
2772 if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind
2773 && is_null_ptr(cx, expr_deref)
2774 {
2775 if let hir::Node::Expr(hir::Expr {
2776 kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..),
2777 ..
2778 }) = cx.tcx.parent_hir_node(expr.hir_id)
2779 {
2780 // `&raw *NULL` is ok.
2781 } else {
2782 cx.emit_span_lint(
2783 DEREF_NULLPTR,
2784 expr.span,
2785 BuiltinDerefNullptr { label: expr.span },
2786 );
2787 }
2788 }
2789 }
2790}
2791
2792declare_lint! {
2793 /// The `named_asm_labels` lint detects the use of named labels in the
2794 /// inline `asm!` macro.
2795 ///
2796 /// ### Example
2797 ///
2798 /// ```rust,compile_fail
2799 /// # #![feature(asm_experimental_arch)]
2800 /// use std::arch::asm;
2801 ///
2802 /// fn main() {
2803 /// unsafe {
2804 /// asm!("foo: bar");
2805 /// }
2806 /// }
2807 /// ```
2808 ///
2809 /// {{produces}}
2810 ///
2811 /// ### Explanation
2812 ///
2813 /// LLVM is allowed to duplicate inline assembly blocks for any
2814 /// reason, for example when it is in a function that gets inlined. Because
2815 /// of this, GNU assembler [local labels] *must* be used instead of labels
2816 /// with a name. Using named labels might cause assembler or linker errors.
2817 ///
2818 /// See the explanation in [Rust By Example] for more details.
2819 ///
2820 /// [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels
2821 /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2822 pub NAMED_ASM_LABELS,
2823 Deny,
2824 "named labels in inline assembly",
2825}
2826
2827declare_lint! {
2828 /// The `binary_asm_labels` lint detects the use of numeric labels containing only binary
2829 /// digits in the inline `asm!` macro.
2830 ///
2831 /// ### Example
2832 ///
2833 /// ```rust,ignore (fails on non-x86_64)
2834 /// #![cfg(target_arch = "x86_64")]
2835 ///
2836 /// use std::arch::asm;
2837 ///
2838 /// fn main() {
2839 /// unsafe {
2840 /// asm!("0: jmp 0b");
2841 /// }
2842 /// }
2843 /// ```
2844 ///
2845 /// This will produce:
2846 ///
2847 /// ```text
2848 /// error: avoid using labels containing only the digits `0` and `1` in inline assembly
2849 /// --> <source>:7:15
2850 /// |
2851 /// 7 | asm!("0: jmp 0b");
2852 /// | ^ use a different label that doesn't start with `0` or `1`
2853 /// |
2854 /// = help: start numbering with `2` instead
2855 /// = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86
2856 /// = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information
2857 /// = note: `#[deny(binary_asm_labels)]` on by default
2858 /// ```
2859 ///
2860 /// ### Explanation
2861 ///
2862 /// An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary
2863 /// literal instead of a reference to the previous local label `0`. To work around this bug,
2864 /// don't use labels that could be confused with a binary literal.
2865 ///
2866 /// This behavior is platform-specific to x86 and x86-64.
2867 ///
2868 /// See the explanation in [Rust By Example] for more details.
2869 ///
2870 /// [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547
2871 /// [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels
2872 pub BINARY_ASM_LABELS,
2873 Deny,
2874 "labels in inline assembly containing only 0 or 1 digits",
2875}
2876
2877declare_lint_pass!(AsmLabels => [NAMED_ASM_LABELS, BINARY_ASM_LABELS]);
2878
2879#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2880enum AsmLabelKind {
2881 Named,
2882 FormatArg,
2883 Binary,
2884}
2885
2886/// Checks if a potential label is actually a Hexagon register span notation.
2887///
2888/// Hexagon assembly uses register span notation like `r1:0`, `V5:4.w`, `p1:0` etc.
2889/// These follow the pattern: `[letter][digit(s)]:[digit(s)][optional_suffix]`
2890///
2891/// Returns `true` if the string matches a valid Hexagon register span pattern.
2892pub fn is_hexagon_register_span(possible_label: &str) -> bool {
2893 // Extract the full register span from the context
2894 if let Some(colon_idx) = possible_label.find(':') {
2895 let after_colon = &possible_label[colon_idx + 1..];
2896 is_hexagon_register_span_impl(&possible_label[..colon_idx], after_colon)
2897 } else {
2898 false
2899 }
2900}
2901
2902/// Helper function for use within the lint when we have statement context.
2903fn is_hexagon_register_span_context(
2904 possible_label: &str,
2905 statement: &str,
2906 colon_idx: usize,
2907) -> bool {
2908 // Extract what comes after the colon in the statement
2909 let after_colon_start = colon_idx + 1;
2910 if after_colon_start >= statement.len() {
2911 return false;
2912 }
2913
2914 // Get the part after the colon, up to the next whitespace or special character
2915 let after_colon_full = &statement[after_colon_start..];
2916 let after_colon = after_colon_full
2917 .chars()
2918 .take_while(|&c| c.is_ascii_alphanumeric() || c == '.')
2919 .collect::<String>();
2920
2921 is_hexagon_register_span_impl(possible_label, &after_colon)
2922}
2923
2924/// Core implementation for checking hexagon register spans.
2925fn is_hexagon_register_span_impl(before_colon: &str, after_colon: &str) -> bool {
2926 if before_colon.len() < 1 || after_colon.is_empty() {
2927 return false;
2928 }
2929
2930 let mut chars = before_colon.chars();
2931 let start = chars.next().unwrap();
2932
2933 // Must start with a letter (r, V, p, etc.)
2934 if !start.is_ascii_alphabetic() {
2935 return false;
2936 }
2937
2938 let rest = &before_colon[1..];
2939
2940 // Check if the part after the first letter is all digits and non-empty
2941 if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit()) {
2942 return false;
2943 }
2944
2945 // Check if after colon starts with digits (may have suffix like .w, .h)
2946 let digits_after = after_colon.chars().take_while(|c| c.is_ascii_digit()).collect::<String>();
2947
2948 !digits_after.is_empty()
2949}
2950
2951impl<'tcx> LateLintPass<'tcx> for AsmLabels {
2952 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
2953 if let hir::Expr {
2954 kind:
2955 hir::ExprKind::InlineAsm(hir::InlineAsm {
2956 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
2957 template_strs,
2958 options,
2959 ..
2960 }),
2961 ..
2962 } = expr
2963 {
2964 // Non-generic naked functions are allowed to define arbitrary
2965 // labels.
2966 if *asm_macro == AsmMacro::NakedAsm {
2967 let def_id = expr.hir_id.owner.def_id;
2968 if !cx.tcx.generics_of(def_id).requires_monomorphization(cx.tcx) {
2969 return;
2970 }
2971 }
2972
2973 // asm with `options(raw)` does not do replacement with `{` and `}`.
2974 let raw = options.contains(InlineAsmOptions::RAW);
2975
2976 for (template_sym, template_snippet, template_span) in template_strs.iter() {
2977 let template_str = template_sym.as_str();
2978 let find_label_span = |needle: &str| -> Option<Span> {
2979 if let Some(template_snippet) = template_snippet {
2980 let snippet = template_snippet.as_str();
2981 if let Some(pos) = snippet.find(needle) {
2982 let end = pos
2983 + snippet[pos..]
2984 .find(|c| c == ':')
2985 .unwrap_or(snippet[pos..].len() - 1);
2986 let inner = InnerSpan::new(pos, end);
2987 return Some(template_span.from_inner(inner));
2988 }
2989 }
2990
2991 None
2992 };
2993
2994 // diagnostics are emitted per-template, so this is created here as opposed to the outer loop
2995 let mut spans = Vec::new();
2996
2997 // A semicolon might not actually be specified as a separator for all targets, but
2998 // it seems like LLVM accepts it always.
2999 let statements = template_str.split(|c| matches!(c, '\n' | ';'));
3000 for statement in statements {
3001 // If there's a comment, trim it from the statement
3002 let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
3003
3004 // In this loop, if there is ever a non-label, no labels can come after it.
3005 let mut start_idx = 0;
3006 'label_loop: for (idx, _) in statement.match_indices(':') {
3007 let possible_label = statement[start_idx..idx].trim();
3008 let mut chars = possible_label.chars();
3009
3010 let Some(start) = chars.next() else {
3011 // Empty string means a leading ':' in this section, which is not a
3012 // label.
3013 break 'label_loop;
3014 };
3015
3016 // Whether a { bracket has been seen and its } hasn't been found yet.
3017 let mut in_bracket = false;
3018 let mut label_kind = AsmLabelKind::Named;
3019
3020 // A label can also start with a format arg, if it's not a raw asm block.
3021 if !raw && start == '{' {
3022 in_bracket = true;
3023 label_kind = AsmLabelKind::FormatArg;
3024 } else if matches!(start, '0' | '1') {
3025 // Binary labels have only the characters `0` or `1`.
3026 label_kind = AsmLabelKind::Binary;
3027 } else if !(start.is_ascii_alphabetic() || matches!(start, '.' | '_')) {
3028 // Named labels start with ASCII letters, `.` or `_`.
3029 // anything else is not a label
3030 break 'label_loop;
3031 }
3032
3033 // Check for Hexagon register span notation (e.g., "r1:0", "V5:4", "V3:2.w")
3034 // This is valid Hexagon assembly syntax, not a label
3035 if matches!(cx.tcx.sess.asm_arch, Some(InlineAsmArch::Hexagon))
3036 && is_hexagon_register_span_context(possible_label, statement, idx)
3037 {
3038 break 'label_loop;
3039 }
3040
3041 for c in chars {
3042 // Inside a template format arg, any character is permitted for the
3043 // purposes of label detection because we assume that it can be
3044 // replaced with some other valid label string later. `options(raw)`
3045 // asm blocks cannot have format args, so they are excluded from this
3046 // special case.
3047 if !raw && in_bracket {
3048 if c == '{' {
3049 // Nested brackets are not allowed in format args, this cannot
3050 // be a label.
3051 break 'label_loop;
3052 }
3053
3054 if c == '}' {
3055 // The end of the format arg.
3056 in_bracket = false;
3057 }
3058 } else if !raw && c == '{' {
3059 // Start of a format arg.
3060 in_bracket = true;
3061 label_kind = AsmLabelKind::FormatArg;
3062 } else {
3063 let can_continue = match label_kind {
3064 // Format arg labels are considered to be named labels for the purposes
3065 // of continuing outside of their {} pair.
3066 AsmLabelKind::Named | AsmLabelKind::FormatArg => {
3067 c.is_ascii_alphanumeric() || matches!(c, '_' | '$')
3068 }
3069 AsmLabelKind::Binary => matches!(c, '0' | '1'),
3070 };
3071
3072 if !can_continue {
3073 // The potential label had an invalid character inside it, it
3074 // cannot be a label.
3075 break 'label_loop;
3076 }
3077 }
3078 }
3079
3080 // If all characters passed the label checks, this is a label.
3081 spans.push((find_label_span(possible_label), label_kind));
3082 start_idx = idx + 1;
3083 }
3084 }
3085
3086 for (span, label_kind) in spans {
3087 let missing_precise_span = span.is_none();
3088 let span = span.unwrap_or(*template_span);
3089 match label_kind {
3090 AsmLabelKind::Named => {
3091 cx.emit_span_lint(
3092 NAMED_ASM_LABELS,
3093 span,
3094 InvalidAsmLabel::Named { missing_precise_span },
3095 );
3096 }
3097 AsmLabelKind::FormatArg => {
3098 cx.emit_span_lint(
3099 NAMED_ASM_LABELS,
3100 span,
3101 InvalidAsmLabel::FormatArg { missing_precise_span },
3102 );
3103 }
3104 // the binary asm issue only occurs when using intel syntax on x86 targets
3105 AsmLabelKind::Binary
3106 if !options.contains(InlineAsmOptions::ATT_SYNTAX)
3107 && matches!(
3108 cx.tcx.sess.asm_arch,
3109 Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None
3110 ) =>
3111 {
3112 cx.emit_span_lint(
3113 BINARY_ASM_LABELS,
3114 span,
3115 InvalidAsmLabel::Binary { missing_precise_span, span },
3116 )
3117 }
3118 // No lint on anything other than x86
3119 AsmLabelKind::Binary => (),
3120 };
3121 }
3122 }
3123 }
3124 }
3125}
3126
3127declare_lint! {
3128 /// The `special_module_name` lint detects module
3129 /// declarations for files that have a special meaning.
3130 ///
3131 /// ### Example
3132 ///
3133 /// ```rust,compile_fail
3134 /// mod lib;
3135 ///
3136 /// fn main() {
3137 /// lib::run();
3138 /// }
3139 /// ```
3140 ///
3141 /// {{produces}}
3142 ///
3143 /// ### Explanation
3144 ///
3145 /// Cargo recognizes `lib.rs` and `main.rs` as the root of a
3146 /// library or binary crate, so declaring them as modules
3147 /// will lead to miscompilation of the crate unless configured
3148 /// explicitly.
3149 ///
3150 /// To access a library from a binary target within the same crate,
3151 /// use `your_crate_name::` as the path instead of `lib::`:
3152 ///
3153 /// ```rust,compile_fail
3154 /// // bar/src/lib.rs
3155 /// fn run() {
3156 /// // ...
3157 /// }
3158 ///
3159 /// // bar/src/main.rs
3160 /// fn main() {
3161 /// bar::run();
3162 /// }
3163 /// ```
3164 ///
3165 /// Binary targets cannot be used as libraries and so declaring
3166 /// one as a module is not allowed.
3167 pub SPECIAL_MODULE_NAME,
3168 Warn,
3169 "module declarations for files with a special meaning",
3170}
3171
3172declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3173
3174impl EarlyLintPass for SpecialModuleName {
3175 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3176 for item in &krate.items {
3177 if let ast::ItemKind::Mod(
3178 _,
3179 ident,
3180 ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No { .. }, _),
3181 ) = item.kind
3182 {
3183 if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3184 continue;
3185 }
3186
3187 match ident.name.as_str() {
3188 "lib" => cx.emit_span_lint(
3189 SPECIAL_MODULE_NAME,
3190 item.span,
3191 BuiltinSpecialModuleNameUsed::Lib,
3192 ),
3193 "main" => cx.emit_span_lint(
3194 SPECIAL_MODULE_NAME,
3195 item.span,
3196 BuiltinSpecialModuleNameUsed::Main,
3197 ),
3198 _ => continue,
3199 }
3200 }
3201 }
3202 }
3203}