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