1use 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_ir::lang_items::LangItem;
25use rustc_attr_ir::{AttributeKind, DocAttribute, find_attr};
26use rustc_attr_parsing::AttributeParser;
27use rustc_errors::{Applicability, Diagnostic, msg};
28use rustc_feature::GateIssue;
29use rustc_hir::def::{DefKind, Res};
30use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
31use rustc_hir::intravisit::FnKind as HirFnKind;
32use rustc_hir::{self as hir, Body, FnDecl, ImplItemImplKind, PatKind, PredicateOrigin};
33pub use rustc_lint_defs::builtin::*;
35use rustc_lint_defs::{declare_lint, declare_lint_pass, fcw, impl_lint_pass};
36use rustc_middle::ty::consts::ConstExt;
37use rustc_middle::ty::layout::LayoutOf;
38use rustc_middle::ty::print::with_no_trimmed_paths;
39use rustc_middle::ty::{
40 self, AssocContainer, Ty, TyCtxt, TypeVisitableExt, Unnormalized, Upcast, VariantDef,
41};
42use rustc_span::edition::Edition;
43use rustc_span::{DUMMY_SP, Ident, InnerSpan, Span, Spanned, Symbol, bug, kw, sym};
44use rustc_target::asm::InlineAsmArch;
45use rustc_trait_selection::infer::{InferCtxtExt, TyCtxtInferExt};
46use rustc_trait_selection::traits;
47use rustc_trait_selection::traits::misc::type_allowed_to_implement_copy;
48use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt as _;
49
50use crate::diagnostics::{
51 BuiltinAnonymousParams, BuiltinConstNoMangle, BuiltinDerefNullptr, BuiltinDoubleNegations,
52 BuiltinDoubleNegationsAddParens, BuiltinEllipsisInclusiveRangePatterns,
53 BuiltinEllipsisInclusiveRangePatternsLint, BuiltinExplicitOutlives,
54 BuiltinExplicitOutlivesSuggestion, BuiltinFeatureIssueNote, BuiltinIncompleteFeatures,
55 BuiltinIncompleteFeaturesHelp, BuiltinInternalFeatures, BuiltinKeywordIdents,
56 BuiltinMissingCopyImpl, BuiltinMissingDebugImpl, BuiltinMissingDoc, BuiltinMutablesTransmutes,
57 BuiltinNonShorthandFieldPatterns, BuiltinSpecialModuleNameUsed, BuiltinTrivialBounds,
58 BuiltinTypeAliasBounds, BuiltinUngatedAsyncFnTrackCaller, BuiltinUnpermittedTypeInit,
59 BuiltinUnpermittedTypeInitSub, BuiltinUnreachablePub, BuiltinUnsafe, BuiltinUnstableFeatures,
60 BuiltinUnusedDocComment, BuiltinUnusedDocCommentSub, BuiltinWhileTrue,
61 EqInternalMethodImplemented, InvalidAsmLabel,
62};
63use crate::{EarlyContext, EarlyLintPass, LateContext, LateLintPass, LintContext};
64
65#[doc = r" The `while_true` lint detects `while true { }`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" while true {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" `while true` should be replaced with `loop`. A `loop` expression is"]
#[doc =
r" the preferred way to write an infinite loop because it more directly"]
#[doc = r" expresses the intent of the loop."]
static WHILE_TRUE: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "WHILE_TRUE",
default_level: ::rustc_lint_defs::Warn,
desc: "suggest using `loop { }` instead of `while true { }`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
66 WHILE_TRUE,
84 Warn,
85 "suggest using `loop { }` instead of `while true { }`"
86}
87
88pub struct WhileTrue;
#[automatically_derived]
impl ::core::marker::Copy for WhileTrue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for WhileTrue { }
#[automatically_derived]
impl ::core::clone::Clone for WhileTrue {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for WhileTrue {
fn name(&self) -> &'static str { "WhileTrue" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[WHILE_TRUE]))
}
}
impl WhileTrue {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[WHILE_TRUE]))
}
}declare_lint_pass!(WhileTrue => [WHILE_TRUE]);
89
90impl EarlyLintPass for WhileTrue {
91 #[inline]
92 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
93 if let ast::ExprKind::While(cond, _, label) = &e.kind
94 && let ast::ExprKind::Lit(token_lit) = cond.peel_parens().kind
95 && let token::Lit { kind: token::Bool, symbol: kw::True, .. } = token_lit
96 && !cond.span.from_expansion()
97 {
98 let condition_span = e.span.with_hi(cond.span.hi());
99 let replace = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}loop",
label.map_or_else(String::new,
|label|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: ", label.ident))
}))))
})format!(
100 "{}loop",
101 label.map_or_else(String::new, |label| format!("{}: ", label.ident,))
102 );
103 cx.emit_span_lint(
104 WHILE_TRUE,
105 condition_span,
106 BuiltinWhileTrue { suggestion: condition_span, replace },
107 );
108 }
109 }
110}
111
112#[doc =
r" The `non_shorthand_field_patterns` lint detects using `Struct { x: x }`"]
#[doc = r" instead of `Struct { x }` in a pattern."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" struct Point {"]
#[doc = r" x: i32,"]
#[doc = r" y: i32,"]
#[doc = r" }"]
#[doc = r""]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" let p = Point {"]
#[doc = r" x: 5,"]
#[doc = r" y: 5,"]
#[doc = r" };"]
#[doc = r""]
#[doc = r" match p {"]
#[doc = r" Point { x: x, y: y } => (),"]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The preferred style is to avoid the repetition of specifying both the"]
#[doc = r" field name and the binding name if both identifiers are the same."]
static NON_SHORTHAND_FIELD_PATTERNS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NON_SHORTHAND_FIELD_PATTERNS",
default_level: ::rustc_lint_defs::Warn,
desc: "using `Struct { x: x }` instead of `Struct { x }` in a pattern",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
113 NON_SHORTHAND_FIELD_PATTERNS,
144 Warn,
145 "using `Struct { x: x }` instead of `Struct { x }` in a pattern"
146}
147
148pub struct NonShorthandFieldPatterns;
#[automatically_derived]
impl ::core::marker::Copy for NonShorthandFieldPatterns { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for NonShorthandFieldPatterns { }
#[automatically_derived]
impl ::core::clone::Clone for NonShorthandFieldPatterns {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for NonShorthandFieldPatterns {
fn name(&self) -> &'static str { "NonShorthandFieldPatterns" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NON_SHORTHAND_FIELD_PATTERNS]))
}
}
impl NonShorthandFieldPatterns {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NON_SHORTHAND_FIELD_PATTERNS]))
}
}declare_lint_pass!(NonShorthandFieldPatterns => [NON_SHORTHAND_FIELD_PATTERNS]);
149
150impl<'tcx> LateLintPass<'tcx> for NonShorthandFieldPatterns {
151 fn check_pat(&mut self, cx: &LateContext<'_>, pat: &hir::Pat<'_>) {
152 if let PatKind::Struct(ref qpath, field_pats, _) = pat.kind {
153 let variant = cx
154 .typeck_results()
155 .pat_ty(pat)
156 .ty_adt_def()
157 .expect("struct pattern type is not an ADT")
158 .variant_of_res(cx.qpath_res(qpath, pat.hir_id));
159 for fieldpat in field_pats {
160 if fieldpat.is_shorthand {
161 continue;
162 }
163 if fieldpat.span.from_expansion() {
164 continue;
168 }
169 if let PatKind::Binding(binding_annot, _, ident, None) = fieldpat.pat.kind {
170 if cx.tcx.find_field_index(ident, variant)
171 == Some(cx.typeck_results().field_index(fieldpat.hir_id))
172 {
173 cx.emit_span_lint(
174 NON_SHORTHAND_FIELD_PATTERNS,
175 fieldpat.span,
176 BuiltinNonShorthandFieldPatterns {
177 ident,
178 suggestion: fieldpat.span,
179 prefix: binding_annot.prefix_str(),
180 },
181 );
182 }
183 }
184 }
185 }
186 }
187}
188
189pub struct UnsafeCode;
#[automatically_derived]
impl ::core::marker::Copy for UnsafeCode { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnsafeCode { }
#[automatically_derived]
impl ::core::clone::Clone for UnsafeCode {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnsafeCode {
fn name(&self) -> &'static str { "UnsafeCode" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNSAFE_CODE]))
}
}
impl UnsafeCode {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNSAFE_CODE]))
}
}declare_lint_pass!(UnsafeCode => [UNSAFE_CODE]);
190
191impl UnsafeCode {
192 fn report_unsafe(
193 &self,
194 cx: &EarlyContext<'_>,
195 span: Span,
196 decorate: impl for<'a> Diagnostic<'a>,
197 ) {
198 if span.allows_unsafe() {
200 return;
201 }
202
203 cx.emit_span_lint(UNSAFE_CODE, span, decorate);
204 }
205}
206
207impl EarlyLintPass for UnsafeCode {
208 #[inline]
209 fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &ast::Expr) {
210 if let ast::ExprKind::Block(ref blk, _) = e.kind {
211 if blk.rules == ast::BlockCheckMode::Unsafe(ast::UserProvided) {
213 self.report_unsafe(cx, blk.span, BuiltinUnsafe::UnsafeBlock);
214 }
215 }
216 }
217
218 fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
219 match it.kind {
220 ast::ItemKind::Trait(ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
221 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
222 }
223
224 ast::ItemKind::Impl(ast::Impl {
225 of_trait: Some(ast::TraitImplHeader { safety: ast::Safety::Unsafe(_), .. }),
226 ..
227 }) => {
228 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
229 }
230
231 ast::ItemKind::GlobalAsm(..) => {
232 self.report_unsafe(cx, it.span, BuiltinUnsafe::GlobalAsm);
233 }
234
235 ast::ItemKind::ForeignMod(ForeignMod { safety, .. }) => {
236 if let Safety::Unsafe(_) = safety {
237 self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeExternBlock);
238 }
239 }
240
241 ast::ItemKind::MacroDef(..) => {
242 if let Some(rustc_attr_ir::Attribute::Parsed(AttributeKind::AllowInternalUnsafe(
243 span,
244 ))) = AttributeParser::parse_limited_sym(
245 cx.builder.sess(),
246 &it.attrs,
247 &[sym::allow_internal_unsafe],
248 ) {
249 self.report_unsafe(cx, span, BuiltinUnsafe::AllowInternalUnsafe);
250 }
251 }
252
253 _ => {}
254 }
255 }
256
257 fn check_fn(&mut self, cx: &EarlyContext<'_>, fk: FnKind<'_>, span: Span, _: ast::NodeId) {
258 if let FnKind::Fn(
259 ctxt,
260 _,
261 ast::Fn {
262 sig: ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
263 body,
264 ..
265 },
266 ) = fk
267 {
268 let decorator = match ctxt {
269 FnCtxt::Foreign => return,
270 FnCtxt::Free => BuiltinUnsafe::DeclUnsafeFn,
271 FnCtxt::Assoc(_) if body.is_none() => BuiltinUnsafe::DeclUnsafeMethod,
272 FnCtxt::Assoc(_) => BuiltinUnsafe::ImplUnsafeMethod,
273 };
274 self.report_unsafe(cx, span, decorator);
275 }
276 }
277}
278
279#[doc =
r" The `missing_docs` lint detects missing documentation for public items."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_docs)]"]
#[doc = r" pub fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This lint is intended to ensure that a library is well-documented."]
#[doc =
r" Items without documentation can be difficult for users to understand"]
#[doc = r" how to use properly."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it can be noisy, and not all"#]
#[doc = r" projects may want to enforce everything to be documented."]
pub static MISSING_DOCS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_DOCS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects missing documentation for public members",
is_externally_loaded: false,
report_in_external_macro: true,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
280 pub MISSING_DOCS,
300 Allow,
301 "detects missing documentation for public members",
302 report_in_external_macro
303}
304
305#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDoc {
#[inline]
fn default() -> Self { Self }
}Default)]
306pub struct MissingDoc;
307
308impl ::rustc_lint_defs::LintPass for MissingDoc {
fn name(&self) -> &'static str { "MissingDoc" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_DOCS]))
}
}
impl MissingDoc {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_DOCS]))
}
}impl_lint_pass!(MissingDoc => [MISSING_DOCS]);
309
310fn has_doc(attr: &rustc_attr_ir::Attribute) -> bool {
311 if #[allow(non_exhaustive_omitted_patterns)] match attr {
rustc_attr_ir::Attribute::Parsed(AttributeKind::DocComment { .. }) =>
true,
_ => false,
}matches!(attr, rustc_attr_ir::Attribute::Parsed(AttributeKind::DocComment { .. })) {
312 return true;
313 }
314
315 if let rustc_attr_ir::Attribute::Parsed(AttributeKind::Doc(d)) = attr
316 && #[allow(non_exhaustive_omitted_patterns)] match d.as_ref() {
DocAttribute { hidden: Some(..), .. } => true,
_ => false,
}matches!(d.as_ref(), DocAttribute { hidden: Some(..), .. })
317 {
318 return true;
319 }
320
321 false
322}
323
324impl MissingDoc {
325 fn check_missing_docs_attrs(
326 &self,
327 cx: &LateContext<'_>,
328 def_id: LocalDefId,
329 article: &'static str,
330 desc: &'static str,
331 ) {
332 if def_id != CRATE_DEF_ID && !cx.effective_visibilities.is_exported(def_id) {
336 return;
337 }
338
339 let attrs = cx.tcx.hir_attrs(cx.tcx.local_def_id_to_hir_id(def_id));
340 let has_doc = attrs.iter().any(has_doc);
341 if !has_doc {
342 cx.emit_span_lint(
343 MISSING_DOCS,
344 cx.tcx.def_span(def_id),
345 BuiltinMissingDoc { article, desc },
346 );
347 }
348 }
349}
350
351impl<'tcx> LateLintPass<'tcx> for MissingDoc {
352 fn check_crate(&mut self, cx: &LateContext<'_>) {
353 self.check_missing_docs_attrs(cx, CRATE_DEF_ID, "the", "crate");
354 }
355
356 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
357 if let hir::ItemKind::Impl(..) | hir::ItemKind::Use(..) | hir::ItemKind::ExternCrate(..) =
362 it.kind
363 {
364 return;
365 }
366
367 let (article, desc) = cx.tcx.article_and_description(it.owner_id.to_def_id());
368 self.check_missing_docs_attrs(cx, it.owner_id.def_id, article, desc);
369 }
370
371 fn check_trait_item(&mut self, cx: &LateContext<'_>, trait_item: &hir::TraitItem<'_>) {
372 let (article, desc) = cx.tcx.article_and_description(trait_item.owner_id.to_def_id());
373
374 self.check_missing_docs_attrs(cx, trait_item.owner_id.def_id, article, desc);
375 }
376
377 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
378 let container = cx.tcx.associated_item(impl_item.owner_id.def_id).container;
379
380 match container {
381 AssocContainer::TraitImpl(_) => return,
383 AssocContainer::Trait => {}
384 AssocContainer::InherentImpl => {
386 let parent = cx.tcx.hir_get_parent_item(impl_item.hir_id());
387 let impl_ty = cx.tcx.type_of(parent).instantiate_identity().skip_norm_wip();
388 let outerdef = match impl_ty.kind() {
389 ty::Adt(def, _) => Some(def.did()),
390 ty::Foreign(def_id) => Some(*def_id),
391 _ => None,
392 };
393 let is_hidden = match outerdef {
394 Some(id) => cx.tcx.is_doc_hidden(id),
395 None => false,
396 };
397 if is_hidden {
398 return;
399 }
400 }
401 }
402
403 let (article, desc) = cx.tcx.article_and_description(impl_item.owner_id.to_def_id());
404 self.check_missing_docs_attrs(cx, impl_item.owner_id.def_id, article, desc);
405 }
406
407 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'_>) {
408 let (article, desc) = cx.tcx.article_and_description(foreign_item.owner_id.to_def_id());
409 self.check_missing_docs_attrs(cx, foreign_item.owner_id.def_id, article, desc);
410 }
411
412 fn check_field_def(&mut self, cx: &LateContext<'_>, sf: &hir::FieldDef<'_>) {
413 if !sf.is_positional() {
414 self.check_missing_docs_attrs(cx, sf.def_id, "a", "struct field")
415 }
416 }
417
418 fn check_variant(&mut self, cx: &LateContext<'_>, v: &hir::Variant<'_>) {
419 self.check_missing_docs_attrs(cx, v.def_id, "a", "variant");
420 }
421}
422
423#[doc =
r" The `missing_copy_implementations` lint detects potentially-forgotten"]
#[doc = r" implementations of [`Copy`] for public types."]
#[doc = r""]
#[doc = r" [`Copy`]: https://doc.rust-lang.org/std/marker/trait.Copy.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_copy_implementations)]"]
#[doc = r" pub struct Foo {"]
#[doc = r" pub field: i32"]
#[doc = r" }"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Historically (before 1.0), types were automatically marked as `Copy`"]
#[doc =
r" if possible. This was changed so that it required an explicit opt-in"]
#[doc =
r" by implementing the `Copy` trait. As part of this change, a lint was"]
#[doc = r" added to alert if a copyable type was not marked `Copy`."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because this code isn't bad; it is"#]
#[doc =
r" common to write newtypes like this specifically so that a `Copy` type"]
#[doc =
r" is no longer `Copy`. `Copy` types can result in unintended copies of"]
#[doc = r" large data which can impact performance."]
pub static MISSING_COPY_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_COPY_IMPLEMENTATIONS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects potentially-forgotten implementations of `Copy`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
424 pub MISSING_COPY_IMPLEMENTATIONS,
453 Allow,
454 "detects potentially-forgotten implementations of `Copy`"
455}
456
457pub struct MissingCopyImplementations;
#[automatically_derived]
impl ::core::marker::Copy for MissingCopyImplementations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MissingCopyImplementations { }
#[automatically_derived]
impl ::core::clone::Clone for MissingCopyImplementations {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for MissingCopyImplementations {
fn name(&self) -> &'static str { "MissingCopyImplementations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_COPY_IMPLEMENTATIONS]))
}
}
impl MissingCopyImplementations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_COPY_IMPLEMENTATIONS]))
}
}declare_lint_pass!(MissingCopyImplementations => [MISSING_COPY_IMPLEMENTATIONS]);
458
459impl<'tcx> LateLintPass<'tcx> for MissingCopyImplementations {
460 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
461 if !cx.effective_visibilities.is_reachable(item.owner_id.def_id) {
462 return;
463 }
464 let (def, ty) = match item.kind {
465 hir::ItemKind::Struct(_, generics, _) => {
466 if !generics.params.is_empty() {
467 return;
468 }
469 let def = cx.tcx.adt_def(item.owner_id);
470 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
471 }
472 hir::ItemKind::Union(_, generics, _) => {
473 if !generics.params.is_empty() {
474 return;
475 }
476 let def = cx.tcx.adt_def(item.owner_id);
477 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
478 }
479 hir::ItemKind::Enum(_, generics, _) => {
480 if !generics.params.is_empty() {
481 return;
482 }
483 let def = cx.tcx.adt_def(item.owner_id);
484 (def, Ty::new_adt(cx.tcx, def, ty::List::empty()))
485 }
486 _ => return,
487 };
488 if def.has_dtor(cx.tcx) {
489 return;
490 }
491
492 for field in def.all_fields() {
495 let did = field.did;
496 if cx.tcx.type_of(did).instantiate_identity().skip_norm_wip().is_raw_ptr() {
497 return;
498 }
499 }
500 if cx.type_is_copy_modulo_regions(ty) {
501 return;
502 }
503 if type_implements_negative_copy_modulo_regions(cx.tcx, ty, cx.typing_env()) {
504 return;
505 }
506 if def.is_variant_list_non_exhaustive()
507 || def.variants().iter().any(|variant| variant.is_field_list_non_exhaustive())
508 {
509 return;
510 }
511
512 if let Some(iter_trait) = cx.tcx.get_diagnostic_item(sym::Iterator)
515 && cx
516 .tcx
517 .infer_ctxt()
518 .build(cx.typing_mode())
519 .type_implements_trait(iter_trait, [ty], cx.param_env)
520 .must_apply_modulo_regions()
521 {
522 return;
523 }
524
525 const MAX_SIZE: u64 = 256;
527
528 if let Some(size) = cx.layout_of(ty).ok().map(|l| l.size.bytes()) {
529 if size > MAX_SIZE {
530 return;
531 }
532 }
533
534 if type_allowed_to_implement_copy(
535 cx.tcx,
536 cx.param_env,
537 ty,
538 traits::ObligationCause::misc(item.span, item.owner_id.def_id),
539 hir::Safety::Safe,
540 )
541 .is_ok()
542 {
543 cx.emit_span_lint(MISSING_COPY_IMPLEMENTATIONS, item.span, BuiltinMissingCopyImpl);
544 }
545 }
546}
547
548fn type_implements_negative_copy_modulo_regions<'tcx>(
550 tcx: TyCtxt<'tcx>,
551 ty: Ty<'tcx>,
552 typing_env: ty::TypingEnv<'tcx>,
553) -> bool {
554 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
555 let trait_ref = ty::TraitRef::new(tcx, tcx.require_lang_item(LangItem::Copy, DUMMY_SP), [ty]);
556 let pred = ty::TraitClause { trait_ref, polarity: ty::ClausePolarity::Negative };
557 let obligation = traits::Obligation {
558 cause: traits::ObligationCause::dummy(),
559 param_env,
560 recursion_depth: 0,
561 predicate: pred.upcast(tcx),
562 };
563 infcx.predicate_must_hold_modulo_regions(&obligation)
564}
565
566#[doc = r" The `missing_debug_implementations` lint detects missing"]
#[doc = r" implementations of [`fmt::Debug`] for public types."]
#[doc = r""]
#[doc =
r" [`fmt::Debug`]: https://doc.rust-lang.org/std/fmt/trait.Debug.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(missing_debug_implementations)]"]
#[doc = r" pub struct Foo;"]
#[doc = r" # fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Having a `Debug` implementation on all types can assist with"]
#[doc =
r" debugging, as it provides a convenient way to format and display a"]
#[doc = r" value. Using the `#[derive(Debug)]` attribute will automatically"]
#[doc =
r" generate a typical implementation, or a custom implementation can be"]
#[doc = r" added by manually implementing the `Debug` trait."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because adding `Debug` to all types can"#]
#[doc =
r" have a negative impact on compile time and code size. It also requires"]
#[doc =
r" boilerplate to be added to every type, which can be an impediment."]
static MISSING_DEBUG_IMPLEMENTATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MISSING_DEBUG_IMPLEMENTATIONS",
default_level: ::rustc_lint_defs::Allow,
desc: "detects missing implementations of Debug",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
567 MISSING_DEBUG_IMPLEMENTATIONS,
594 Allow,
595 "detects missing implementations of Debug"
596}
597
598#[derive(#[automatically_derived]
impl ::core::default::Default for MissingDebugImplementations {
#[inline]
fn default() -> Self { Self }
}Default)]
599pub(crate) struct MissingDebugImplementations;
600
601impl ::rustc_lint_defs::LintPass for MissingDebugImplementations {
fn name(&self) -> &'static str { "MissingDebugImplementations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_DEBUG_IMPLEMENTATIONS]))
}
}
impl MissingDebugImplementations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MISSING_DEBUG_IMPLEMENTATIONS]))
}
}impl_lint_pass!(MissingDebugImplementations => [MISSING_DEBUG_IMPLEMENTATIONS]);
602
603impl<'tcx> LateLintPass<'tcx> for MissingDebugImplementations {
604 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
605 let def_id = item.owner_id.def_id;
606 if !cx.effective_visibilities.is_reachable(def_id) {
607 return;
608 }
609
610 let is_generic = match item.kind {
611 hir::ItemKind::Struct(_, generics, _)
612 | hir::ItemKind::Union(_, generics, _)
613 | hir::ItemKind::Enum(_, generics, _) => !generics.params.is_empty(),
614 _ => return,
615 };
616
617 let tcx = cx.tcx;
618
619 if tcx.lint_level_spec_at_node(MISSING_DEBUG_IMPLEMENTATIONS, item.hir_id()).is_allow() {
621 return;
622 }
623
624 let Some(debug) = tcx.get_diagnostic_item(sym::Debug) else { return };
625
626 let ty = tcx.type_of(item.owner_id);
627 if tcx
628 .non_blanket_impls_for_ty(debug, ty.instantiate_identity().skip_norm_wip())
629 .next()
630 .is_some()
631 {
632 return;
633 }
634
635 let infcx = tcx.infer_ctxt().build(cx.typing_mode());
636 if is_generic {
637 let args = infcx.fresh_args_for_item(item.span, def_id.to_def_id());
638 if infcx
639 .type_implements_trait_shallow(
640 debug,
641 ty.instantiate(tcx, args).skip_norm_wip(),
642 cx.param_env,
643 )
644 .is_some()
645 {
646 return;
647 }
648 } else if infcx
649 .type_implements_trait(debug, [ty.instantiate_identity().skip_norm_wip()], cx.param_env)
650 .must_apply_modulo_regions()
651 {
652 return;
653 }
654
655 cx.emit_span_lint(
656 MISSING_DEBUG_IMPLEMENTATIONS,
657 item.span,
658 BuiltinMissingDebugImpl { tcx: cx.tcx, def_id: debug },
659 );
660 }
661}
662
663#[doc =
r" The `anonymous_parameters` lint detects anonymous parameters in trait"]
#[doc = r" definitions."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(anonymous_parameters)]"]
#[doc = r" // edition 2015"]
#[doc = r" pub trait Foo {"]
#[doc = r" fn foo(usize);"]
#[doc = r" }"]
#[doc = r" fn main() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" This syntax is mostly a historical accident, and can be worked around"]
#[doc =
r" quite easily by adding an `_` pattern or a descriptive identifier:"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" trait Foo {"]
#[doc = r" fn foo(_: usize);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This syntax is now a hard error in the 2018 edition. In the 2015"]
#[doc = r#" edition, this lint is "warn" by default. This lint"#]
#[doc = r" enables the [`cargo fix`] tool with the `--edition` flag to"]
#[doc =
r" automatically transition old code from the 2015 edition to 2018. The"]
#[doc = r" tool will run this lint and automatically apply the"]
#[doc = r" suggested fix from the compiler (which is to add `_` to each"]
#[doc =
r" parameter). This provides a completely automated way to update old"]
#[doc = r" code for a new edition. See [issue #41686] for more details."]
#[doc = r""]
#[doc = r" [issue #41686]: https://github.com/rust-lang/rust/issues/41686"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static ANONYMOUS_PARAMETERS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "ANONYMOUS_PARAMETERS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects anonymous parameters",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2018,
page_slug: "trait-fn-parameters",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
664 pub ANONYMOUS_PARAMETERS,
703 Warn,
704 "detects anonymous parameters",
705 @future_incompatible = FutureIncompatibleInfo {
706 reason: fcw!(EditionError 2018 "trait-fn-parameters"),
707 };
708}
709
710#[doc = r" Checks for use of anonymous parameters (RFC 1685)."]
pub struct AnonymousParameters;
#[automatically_derived]
impl ::core::marker::Copy for AnonymousParameters { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AnonymousParameters { }
#[automatically_derived]
impl ::core::clone::Clone for AnonymousParameters {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for AnonymousParameters {
fn name(&self) -> &'static str { "AnonymousParameters" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ANONYMOUS_PARAMETERS]))
}
}
impl AnonymousParameters {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ANONYMOUS_PARAMETERS]))
}
}declare_lint_pass!(
711 AnonymousParameters => [ANONYMOUS_PARAMETERS]
713);
714
715impl EarlyLintPass for AnonymousParameters {
716 fn check_trait_item(&mut self, cx: &EarlyContext<'_>, it: &ast::AssocItem) {
717 if cx.sess().edition() != Edition::Edition2015 {
718 return;
720 }
721 if let ast::AssocItemKind::Fn(Fn { ref sig, .. }) = it.kind {
722 for arg in sig.decl.inputs.iter() {
723 if let ast::PatKind::Missing = arg.pat.kind {
724 let ty_snip = cx.sess().source_map().span_to_snippet(arg.ty.span);
725
726 let (ty_snip, appl) = if let Ok(ref snip) = ty_snip {
727 (snip.as_str(), Applicability::MachineApplicable)
728 } else {
729 ("<type>", Applicability::HasPlaceholders)
730 };
731 cx.emit_span_lint(
732 ANONYMOUS_PARAMETERS,
733 arg.pat.span,
734 BuiltinAnonymousParams { suggestion: (arg.pat.span, appl), ty_snip },
735 );
736 }
737 }
738 }
739 }
740}
741
742fn warn_if_doc(cx: &EarlyContext<'_>, node_span: Span, node_kind: &str, attrs: &[ast::Attribute]) {
743 use rustc_ast::token::CommentKind;
744
745 let mut attrs = attrs.iter().peekable();
746
747 let mut sugared_span: Option<Span> = None;
749
750 while let Some(attr) = attrs.next() {
751 let (is_doc_comment, is_doc_attribute) = match &attr.kind {
752 AttrKind::DocComment(..) => (true, false),
753 AttrKind::Normal(normal) if normal.item.path == sym::doc => (true, true),
754 _ => (false, false),
755 };
756 if is_doc_comment {
757 sugared_span =
758 Some(sugared_span.map_or(attr.span, |span| span.with_hi(attr.span.hi())));
759 }
760
761 if !is_doc_attribute && attrs.peek().is_some_and(|next_attr| next_attr.is_doc_comment()) {
762 continue;
763 }
764
765 let span = sugared_span.take().unwrap_or(attr.span);
766
767 if is_doc_comment || is_doc_attribute {
768 let sub = match attr.kind {
769 AttrKind::DocComment(CommentKind::Line, _) | AttrKind::Normal(..) => {
770 BuiltinUnusedDocCommentSub::PlainHelp
771 }
772 AttrKind::DocComment(CommentKind::Block, _) => {
773 BuiltinUnusedDocCommentSub::BlockHelp
774 }
775 AttrKind::Synthetic(..) => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
776 };
777 cx.emit_span_lint(
778 UNUSED_DOC_COMMENTS,
779 span,
780 BuiltinUnusedDocComment { kind: node_kind, label: node_span, sub },
781 );
782 }
783 }
784}
785
786impl EarlyLintPass for UnusedDocComment {
787 fn check_stmt(&mut self, cx: &EarlyContext<'_>, stmt: &ast::Stmt) {
788 let kind = match stmt.kind {
789 ast::StmtKind::Let(..) => "statements",
790 ast::StmtKind::Item(..) => return,
792 ast::StmtKind::Empty
794 | ast::StmtKind::Semi(_)
795 | ast::StmtKind::Expr(_)
796 | ast::StmtKind::MacCall(_) => return,
797 };
798
799 warn_if_doc(cx, stmt.span, kind, stmt.kind.attrs());
800 }
801
802 fn check_arm(&mut self, cx: &EarlyContext<'_>, arm: &ast::Arm) {
803 if let Some(body) = &arm.body {
804 let arm_span = arm.pat.span.with_hi(body.span.hi());
805 warn_if_doc(cx, arm_span, "match arms", &arm.attrs);
806 }
807 }
808
809 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
810 if let ast::PatKind::Struct(_, _, fields, _) = &pat.kind {
811 for field in fields {
812 warn_if_doc(cx, field.span, "pattern fields", &field.attrs);
813 }
814 }
815 }
816
817 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
818 warn_if_doc(cx, expr.span, "expressions", &expr.attrs);
819
820 if let ExprKind::Struct(s) = &expr.kind {
821 for field in &s.fields {
822 warn_if_doc(cx, field.span, "expression fields", &field.attrs);
823 }
824 }
825 }
826
827 fn check_generic_param(&mut self, cx: &EarlyContext<'_>, param: &ast::GenericParam) {
828 warn_if_doc(cx, param.ident.span, "generic parameters", ¶m.attrs);
829 }
830
831 fn check_block(&mut self, cx: &EarlyContext<'_>, block: &ast::Block) {
832 warn_if_doc(cx, block.span, "blocks", block.attrs());
833 }
834
835 fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
836 if let ast::ItemKind::ForeignMod(_) = item.kind {
837 warn_if_doc(cx, item.span, "extern blocks", &item.attrs);
838 }
839 }
840}
841
842#[doc =
r" The `no_mangle_const_items` lint detects any `const` items with the"]
#[doc = r" [`no_mangle` attribute]."]
#[doc = r""]
#[doc =
r" [`no_mangle` attribute]: https://doc.rust-lang.org/reference/abi.html#the-no_mangle-attribute"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail,edition2021"]
#[doc = r" #[no_mangle]"]
#[doc = r" const FOO: i32 = 5;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Constants do not have their symbols exported, and therefore, this"]
#[doc = r" probably means you meant to use a [`static`], not a [`const`]."]
#[doc = r""]
#[doc =
r" [`static`]: https://doc.rust-lang.org/reference/items/static-items.html"]
#[doc =
r" [`const`]: https://doc.rust-lang.org/reference/items/constant-items.html"]
static NO_MANGLE_CONST_ITEMS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NO_MANGLE_CONST_ITEMS",
default_level: ::rustc_lint_defs::Deny,
desc: "const items will not have their symbols exported",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
843 NO_MANGLE_CONST_ITEMS,
865 Deny,
866 "const items will not have their symbols exported"
867}
868
869pub struct InvalidNoMangleItems;
#[automatically_derived]
impl ::core::marker::Copy for InvalidNoMangleItems { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidNoMangleItems { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidNoMangleItems {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidNoMangleItems {
fn name(&self) -> &'static str { "InvalidNoMangleItems" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NO_MANGLE_CONST_ITEMS]))
}
}
impl InvalidNoMangleItems {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NO_MANGLE_CONST_ITEMS]))
}
}declare_lint_pass!(InvalidNoMangleItems => [NO_MANGLE_CONST_ITEMS]);
870
871impl InvalidNoMangleItems {
872 fn check_no_mangle_on_generic_fn(
873 &self,
874 cx: &LateContext<'_>,
875 attr_span: Span,
876 def_id: LocalDefId,
877 ) {
878 let generics = cx.tcx.generics_of(def_id);
879 if generics.requires_monomorphization(cx.tcx) {
880 cx.tcx.dcx().emit_err(crate::diagnostics::BuiltinNoMangleGeneric {
881 span: cx.tcx.def_span(def_id),
882 suggestion: attr_span,
883 });
884 }
885 }
886}
887
888impl<'tcx> LateLintPass<'tcx> for InvalidNoMangleItems {
889 fn check_item(&mut self, cx: &LateContext<'_>, it: &hir::Item<'_>) {
890 let attrs = cx.tcx.hir_attrs(it.hir_id());
891 match it.kind {
892 hir::ItemKind::Fn { .. } => {
893 if let Some(attr_span) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ExportName { span, .. }) =>
{
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, ExportName {span, ..} => *span)
894 .or_else(|| {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoMangle(span)) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, NoMangle(span) => *span))
895 {
896 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
897 }
898 }
899 hir::ItemKind::Const(ident, generics, ..) => {
900 if {
{
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoMangle(..)) => {
break 'done Some(());
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}.is_some()
}find_attr!(attrs, NoMangle(..)) {
901 let suggestion =
902 if generics.params.is_empty() && generics.where_clause_span.is_empty() {
903 Some(it.span.until(ident.span))
905 } else {
906 None
907 };
908
909 cx.emit_span_lint(
912 NO_MANGLE_CONST_ITEMS,
913 it.span,
914 BuiltinConstNoMangle { suggestion },
915 );
916 }
917 }
918 _ => {}
919 }
920 }
921
922 fn check_impl_item(&mut self, cx: &LateContext<'_>, it: &hir::ImplItem<'_>) {
923 let attrs = cx.tcx.hir_attrs(it.hir_id());
924 match it.kind {
925 hir::ImplItemKind::Fn { .. } => {
926 if let Some(attr_span) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(ExportName { span, .. }) =>
{
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, ExportName {span, ..} => *span)
927 .or_else(|| {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(NoMangle(span)) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, NoMangle(span) => *span))
928 {
929 self.check_no_mangle_on_generic_fn(cx, attr_span, it.owner_id.def_id);
930 }
931 }
932 _ => {}
933 }
934 }
935}
936
937#[doc =
r" The `mutable_transmutes` lint catches transmuting from `&T` to `&mut"]
#[doc = r" T` because it is [undefined behavior]."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" unsafe {"]
#[doc = r" let y = std::mem::transmute::<&i32, &mut i32>(&5);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Certain assumptions are made about aliasing of data, and this transmute"]
#[doc =
r" violates those assumptions. Consider using [`UnsafeCell`] instead."]
#[doc = r""]
#[doc =
r" [`UnsafeCell`]: https://doc.rust-lang.org/std/cell/struct.UnsafeCell.html"]
static MUTABLE_TRANSMUTES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "MUTABLE_TRANSMUTES",
default_level: ::rustc_lint_defs::Deny,
desc: "transmuting &T to &mut T is undefined behavior, even if the reference is unused",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
938 MUTABLE_TRANSMUTES,
960 Deny,
961 "transmuting &T to &mut T is undefined behavior, even if the reference is unused"
962}
963
964pub struct MutableTransmutes;
#[automatically_derived]
impl ::core::marker::Copy for MutableTransmutes { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for MutableTransmutes { }
#[automatically_derived]
impl ::core::clone::Clone for MutableTransmutes {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for MutableTransmutes {
fn name(&self) -> &'static str { "MutableTransmutes" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MUTABLE_TRANSMUTES]))
}
}
impl MutableTransmutes {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[MUTABLE_TRANSMUTES]))
}
}declare_lint_pass!(MutableTransmutes => [MUTABLE_TRANSMUTES]);
965
966impl<'tcx> LateLintPass<'tcx> for MutableTransmutes {
967 fn check_expr(&mut self, cx: &LateContext<'_>, expr: &hir::Expr<'_>) {
968 if let Some((&ty::Ref(_, _, from_mutbl), &ty::Ref(_, _, to_mutbl))) =
969 get_transmute_from_to(cx, expr).map(|(ty1, ty2)| (ty1.kind(), ty2.kind()))
970 {
971 if from_mutbl < to_mutbl {
972 cx.emit_span_lint(MUTABLE_TRANSMUTES, expr.span, BuiltinMutablesTransmutes);
973 }
974 }
975
976 fn get_transmute_from_to<'tcx>(
977 cx: &LateContext<'tcx>,
978 expr: &hir::Expr<'_>,
979 ) -> Option<(Ty<'tcx>, Ty<'tcx>)> {
980 let hir::ExprKind::Path(ref qpath) = expr.kind else { return None };
981 let def = cx.qpath_res(qpath, expr.hir_id);
982 if let Res::Def(DefKind::Fn, did) = def {
983 if !def_id_is_transmute(cx, did) {
984 return None;
985 }
986 let sig = cx.typeck_results().node_type(expr.hir_id).fn_sig(cx.tcx);
987 let from = sig.inputs().skip_binder()[0];
988 let to = sig.output().skip_binder();
989 return Some((from, to));
990 }
991 None
992 }
993
994 fn def_id_is_transmute(cx: &LateContext<'_>, def_id: DefId) -> bool {
995 cx.tcx.is_intrinsic(def_id, sym::transmute)
996 }
997 }
998}
999
1000#[doc = r" The `unstable_features` lint detects uses of `#![feature]`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unstable_features)]"]
#[doc = r" #![feature(test)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" In larger nightly-based projects which"]
#[doc = r""]
#[doc =
r" * consist of a multitude of crates where a subset of crates has to compile on"]
#[doc =
r" stable either unconditionally or depending on a `cfg` flag to for example"]
#[doc = r" allow stable users to depend on them,"]
#[doc =
r" * don't use nightly for experimental features but for, e.g., unstable options only,"]
#[doc = r""]
#[doc = r" this lint may come in handy to enforce policies of these kinds."]
static UNSTABLE_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNSTABLE_FEATURES",
default_level: ::rustc_lint_defs::Allow,
desc: "enabling unstable features",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1001 UNSTABLE_FEATURES,
1023 Allow,
1024 "enabling unstable features"
1025}
1026
1027#[doc = r" Forbids using the `#[feature(...)]` attribute"]
pub struct UnstableFeatures;
#[automatically_derived]
impl ::core::marker::Copy for UnstableFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnstableFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for UnstableFeatures {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnstableFeatures {
fn name(&self) -> &'static str { "UnstableFeatures" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNSTABLE_FEATURES]))
}
}
impl UnstableFeatures {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNSTABLE_FEATURES]))
}
}declare_lint_pass!(
1028 UnstableFeatures => [UNSTABLE_FEATURES]
1030);
1031
1032impl<'tcx> LateLintPass<'tcx> for UnstableFeatures {
1033 fn check_attributes(&mut self, cx: &LateContext<'_>, attrs: &[rustc_attr_ir::Attribute]) {
1034 if let Some(features) = {
'done:
{
for i in attrs {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(Feature(features, _)) => {
break 'done Some(features);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}find_attr!(attrs, Feature(features, _) => features) {
1035 for feature in features {
1036 cx.emit_span_lint(UNSTABLE_FEATURES, feature.span, BuiltinUnstableFeatures);
1037 }
1038 }
1039 }
1040}
1041
1042#[doc = r" The `ungated_async_fn_track_caller` lint warns when the"]
#[doc = r" `#[track_caller]` attribute is used on an async function"]
#[doc = r" without enabling the corresponding unstable feature flag."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[track_caller]"]
#[doc = r" async fn foo() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" The attribute must be used in conjunction with the"]
#[doc =
r" [`async_fn_track_caller` feature flag]. Otherwise, the `#[track_caller]`"]
#[doc = r" annotation will function as a no-op."]
#[doc = r""]
#[doc =
r" [`async_fn_track_caller` feature flag]: https://doc.rust-lang.org/beta/unstable-book/language-features/async-fn-track-caller.html"]
static UNGATED_ASYNC_FN_TRACK_CALLER: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNGATED_ASYNC_FN_TRACK_CALLER",
default_level: ::rustc_lint_defs::Warn,
desc: "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1043 UNGATED_ASYNC_FN_TRACK_CALLER,
1064 Warn,
1065 "enabling track_caller on an async fn is a no-op unless the async_fn_track_caller feature is enabled"
1066}
1067
1068#[doc =
r" Explains corresponding feature flag must be enabled for the `#[track_caller]` attribute to"]
#[doc = r" do anything"]
pub struct UngatedAsyncFnTrackCaller;
#[automatically_derived]
impl ::core::marker::Copy for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UngatedAsyncFnTrackCaller { }
#[automatically_derived]
impl ::core::clone::Clone for UngatedAsyncFnTrackCaller {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UngatedAsyncFnTrackCaller {
fn name(&self) -> &'static str { "UngatedAsyncFnTrackCaller" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNGATED_ASYNC_FN_TRACK_CALLER]))
}
}
impl UngatedAsyncFnTrackCaller {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNGATED_ASYNC_FN_TRACK_CALLER]))
}
}declare_lint_pass!(
1069 UngatedAsyncFnTrackCaller => [UNGATED_ASYNC_FN_TRACK_CALLER]
1072);
1073
1074impl<'tcx> LateLintPass<'tcx> for UngatedAsyncFnTrackCaller {
1075 fn check_fn(
1076 &mut self,
1077 cx: &LateContext<'_>,
1078 fn_kind: HirFnKind<'_>,
1079 _: &'tcx FnDecl<'_>,
1080 _: &'tcx Body<'_>,
1081 span: Span,
1082 def_id: LocalDefId,
1083 ) {
1084 if fn_kind.asyncness().is_async()
1085 && !cx.tcx.features().async_fn_track_caller()
1086 && let Some(attr_span) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(def_id, &cx.tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(TrackCaller(span)) => {
break 'done Some(*span);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(cx.tcx, def_id, TrackCaller(span) => *span)
1088 {
1089 cx.emit_span_lint(
1090 UNGATED_ASYNC_FN_TRACK_CALLER,
1091 attr_span,
1092 BuiltinUngatedAsyncFnTrackCaller { label: span, session: &cx.tcx.sess },
1093 );
1094 }
1095 }
1096}
1097
1098#[doc =
r" The `unreachable_pub` lint triggers for `pub` items not reachable from other crates - that"]
#[doc =
r" means neither directly accessible, nor reexported (with `pub use`), nor leaked through"]
#[doc =
r" things like return types (which the [`unnameable_types`] lint can detect if desired)."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" #![deny(unreachable_pub)]"]
#[doc = r" mod foo {"]
#[doc = r" pub mod bar {"]
#[doc = r""]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `pub` keyword both expresses an intent for an item to be publicly available, and also"]
#[doc =
r" signals to the compiler to make the item publicly accessible. The intent can only be"]
#[doc =
r" satisfied, however, if all items which contain this item are *also* publicly accessible."]
#[doc =
r" Thus, this lint serves to identify situations where the intent does not match the reality."]
#[doc = r""]
#[doc =
r" If you wish the item to be accessible elsewhere within the crate, but not outside it, the"]
#[doc =
r" `pub(crate)` visibility is recommended to be used instead. This more clearly expresses the"]
#[doc = r" intent that the item is only visible within its own crate."]
#[doc = r""]
#[doc =
r#" This lint is "allow" by default because it will trigger for a large amount of existing Rust code."#]
#[doc = r" Eventually it is desired for this to become warn-by-default."]
#[doc = r""]
#[doc = r" [`unnameable_types`]: #unnameable-types"]
pub static UNREACHABLE_PUB: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "UNREACHABLE_PUB",
default_level: ::rustc_lint_defs::Allow,
desc: "`pub` items not reachable from crate root",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1099 pub UNREACHABLE_PUB,
1132 Allow,
1133 "`pub` items not reachable from crate root"
1134}
1135
1136#[doc =
r" Lint for items marked `pub` that aren't reachable from other crates."]
pub struct UnreachablePub;
#[automatically_derived]
impl ::core::marker::Copy for UnreachablePub { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for UnreachablePub { }
#[automatically_derived]
impl ::core::clone::Clone for UnreachablePub {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for UnreachablePub {
fn name(&self) -> &'static str { "UnreachablePub" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNREACHABLE_PUB]))
}
}
impl UnreachablePub {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[UNREACHABLE_PUB]))
}
}declare_lint_pass!(
1137 UnreachablePub => [UNREACHABLE_PUB]
1139);
1140
1141impl UnreachablePub {
1142 fn perform_lint(
1143 &self,
1144 cx: &LateContext<'_>,
1145 what: &str,
1146 def_id: LocalDefId,
1147 vis_span: Span,
1148 exportable: bool,
1149 ) {
1150 let mut applicability = Applicability::MachineApplicable;
1151 if !cx.tcx.visibility(def_id).is_public() || cx.effective_visibilities.is_reachable(def_id)
1152 {
1153 return;
1154 }
1155
1156 let new_vis = if let Some(ty::Visibility::Restricted(restricted_did)) =
1159 cx.effective_visibilities.effective_vis(def_id).map(|effective_vis| {
1160 effective_vis.at_level(rustc_middle::middle::privacy::Level::Reachable)
1161 })
1162 && let parent_parent =
1163 cx.tcx.parent_module_from_def_id(cx.tcx.parent_module_from_def_id(def_id).into())
1164 && *restricted_did == parent_parent
1165 && !restricted_did.to_def_id().is_crate_root()
1166 {
1167 "pub(super)"
1168 } else {
1169 "pub(crate)"
1170 };
1171
1172 if vis_span.from_expansion() {
1173 applicability = Applicability::MaybeIncorrect;
1174 }
1175 let def_span = cx.tcx.def_span(def_id);
1176 cx.emit_span_lint(
1177 UNREACHABLE_PUB,
1178 def_span,
1179 BuiltinUnreachablePub {
1180 what,
1181 new_vis,
1182 suggestion: (vis_span, applicability),
1183 help: exportable,
1184 },
1185 );
1186 }
1187}
1188
1189impl<'tcx> LateLintPass<'tcx> for UnreachablePub {
1190 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1191 self.perform_lint(cx, "item", item.owner_id.def_id, item.vis_span, true);
1192 }
1193
1194 fn check_foreign_item(&mut self, cx: &LateContext<'_>, foreign_item: &hir::ForeignItem<'tcx>) {
1195 self.perform_lint(cx, "item", foreign_item.owner_id.def_id, foreign_item.vis_span, true);
1196 }
1197
1198 fn check_field_def(&mut self, _cx: &LateContext<'_>, _field: &hir::FieldDef<'_>) {
1199 }
1213
1214 fn check_impl_item(&mut self, cx: &LateContext<'_>, impl_item: &hir::ImplItem<'_>) {
1215 if let ImplItemImplKind::Inherent { vis_span } = impl_item.impl_kind {
1216 self.perform_lint(cx, "item", impl_item.owner_id.def_id, vis_span, false);
1217 }
1218 }
1219}
1220
1221#[doc = r" The `type_alias_bounds` lint detects bounds in type aliases."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" type SendVec<T: Send> = Vec<T>;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Trait and lifetime bounds on generic parameters and in where clauses of"]
#[doc =
r" type aliases are not checked at usage sites of the type alias. Moreover,"]
#[doc =
r" they are not thoroughly checked for correctness at their definition site"]
#[doc = r" either similar to the aliased type."]
#[doc = r""]
#[doc =
r" This is a known limitation of the type checker that may be lifted in a"]
#[doc =
r" future edition. Permitting such bounds in light of this was unintentional."]
#[doc = r""]
#[doc =
r" While these bounds may have secondary effects such as enabling the use of"]
#[doc =
r#" "shorthand" associated type paths[^1] and affecting the default trait"#]
#[doc =
r" object lifetime[^2] of trait object types passed to the type alias, this"]
#[doc =
r" should not have been allowed until the aforementioned restrictions of the"]
#[doc = r" type checker have been lifted."]
#[doc = r""]
#[doc =
r" Using such bounds is highly discouraged as they are actively misleading."]
#[doc = r""]
#[doc =
r" [^1]: I.e., paths of the form `T::Assoc` where `T` is a type parameter"]
#[doc =
r" bounded by trait `Trait` which defines an associated type called `Assoc`"]
#[doc =
r" as opposed to a fully qualified path of the form `<T as Trait>::Assoc`."]
#[doc =
r" [^2]: <https://doc.rust-lang.org/reference/lifetime-elision.html#default-trait-object-lifetimes>"]
static TYPE_ALIAS_BOUNDS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "TYPE_ALIAS_BOUNDS",
default_level: ::rustc_lint_defs::Warn,
desc: "bounds in type aliases are not enforced",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1222 TYPE_ALIAS_BOUNDS,
1255 Warn,
1256 "bounds in type aliases are not enforced"
1257}
1258
1259pub struct TypeAliasBounds;
#[automatically_derived]
impl ::core::marker::Copy for TypeAliasBounds { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TypeAliasBounds { }
#[automatically_derived]
impl ::core::clone::Clone for TypeAliasBounds {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for TypeAliasBounds {
fn name(&self) -> &'static str { "TypeAliasBounds" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TYPE_ALIAS_BOUNDS]))
}
}
impl TypeAliasBounds {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TYPE_ALIAS_BOUNDS]))
}
}declare_lint_pass!(TypeAliasBounds => [TYPE_ALIAS_BOUNDS]);
1260
1261impl TypeAliasBounds {
1262 pub(crate) fn affects_object_lifetime_defaults(pred: &hir::WherePredicate<'_>) -> bool {
1263 if let hir::WherePredicateKind::BoundPredicate(pred) = pred.kind
1265 && pred.bounds.iter().any(|bound| #[allow(non_exhaustive_omitted_patterns)] match bound {
hir::GenericBound::Outlives(_) => true,
_ => false,
}matches!(bound, hir::GenericBound::Outlives(_)))
1266 && pred.bound_generic_params.is_empty() && pred.bounded_ty.as_generic_param().is_some()
1268 {
1269 return true;
1270 }
1271 false
1272 }
1273}
1274
1275impl<'tcx> LateLintPass<'tcx> for TypeAliasBounds {
1276 fn check_item(&mut self, cx: &LateContext<'_>, item: &hir::Item<'_>) {
1277 let hir::ItemKind::TyAlias(_, generics, hir_ty) = item.kind else { return };
1278
1279 if generics.predicates.is_empty() {
1281 return;
1282 }
1283
1284 if cx.tcx.type_alias_is_checked(item.owner_id) {
1286 return;
1287 }
1288
1289 let ty = cx.tcx.type_of(item.owner_id).instantiate_identity().skip_norm_wip();
1292 if ty.has_type_flags(ty::TypeFlags::HAS_CONST_ALIAS)
1293 && cx.tcx.features().generic_const_exprs()
1294 {
1295 return;
1296 }
1297
1298 let mut where_spans = Vec::new();
1304 let mut inline_spans = Vec::new();
1305 let mut inline_sugg = Vec::new();
1306
1307 for p in generics.predicates {
1308 let span = p.span;
1309 if p.kind.in_where_clause() {
1310 where_spans.push(span);
1311 } else {
1312 for b in p.kind.bounds() {
1313 inline_spans.push(b.span());
1314 }
1315 inline_sugg.push((span, String::new()));
1316 }
1317 }
1318
1319 let mut ty = Some(hir_ty);
1320 let enable_feat_help = cx.tcx.sess.is_nightly_build();
1321
1322 if let [.., label_sp] = *where_spans {
1323 cx.emit_span_lint(
1324 TYPE_ALIAS_BOUNDS,
1325 where_spans,
1326 BuiltinTypeAliasBounds {
1327 in_where_clause: true,
1328 label: label_sp,
1329 enable_feat_help,
1330 suggestions: ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[(generics.where_clause_span, String::new())]))vec![(generics.where_clause_span, String::new())],
1331 preds: generics.predicates,
1332 ty: ty.take(),
1333 },
1334 );
1335 }
1336 if let [.., label_sp] = *inline_spans {
1337 cx.emit_span_lint(
1338 TYPE_ALIAS_BOUNDS,
1339 inline_spans,
1340 BuiltinTypeAliasBounds {
1341 in_where_clause: false,
1342 label: label_sp,
1343 enable_feat_help,
1344 suggestions: inline_sugg,
1345 preds: generics.predicates,
1346 ty,
1347 },
1348 );
1349 }
1350 }
1351}
1352
1353pub(crate) struct ShorthandAssocTyCollector {
1354 pub(crate) qselves: Vec<Span>,
1355}
1356
1357impl hir::intravisit::Visitor<'_> for ShorthandAssocTyCollector {
1358 fn visit_qpath(&mut self, qpath: &hir::QPath<'_>, id: hir::HirId, _: Span) {
1359 if let hir::QPath::TypeRelative(qself, _) = qpath
1362 && qself.as_generic_param().is_some()
1363 {
1364 self.qselves.push(qself.span);
1365 }
1366 hir::intravisit::walk_qpath(self, qpath, id)
1367 }
1368}
1369
1370#[doc =
r" The `trivial_bounds` lint detects trait bounds that don't depend on"]
#[doc = r" any type parameters."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(trivial_bounds)]"]
#[doc = r" pub struct A where i32: Copy;"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Usually you would not write a trait bound that you know is always"]
#[doc =
r" true, or never true. However, when using macros, the macro may not"]
#[doc =
r" know whether or not the constraint would hold or not at the time when"]
#[doc =
r" generating the code. Currently, the compiler does not alert you if the"]
#[doc =
r" constraint is always true, and generates an error if it is never true."]
#[doc = r" The `trivial_bounds` feature changes this to be a warning in both"]
#[doc =
r" cases, giving macros more freedom and flexibility to generate code,"]
#[doc = r" while still providing a signal when writing non-macro code that"]
#[doc = r" something is amiss."]
#[doc = r""]
#[doc = r" See [RFC 2056] for more details. This feature is currently only"]
#[doc = r" available on the nightly channel, see [tracking issue #48214]."]
#[doc = r""]
#[doc =
r" [RFC 2056]: https://rust-lang.github.io/rfcs/2056-allow-trivial-where-clause-constraints.html"]
#[doc =
r" [tracking issue #48214]: https://github.com/rust-lang/rust/issues/48214"]
static TRIVIAL_BOUNDS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "TRIVIAL_BOUNDS",
default_level: ::rustc_lint_defs::Warn,
desc: "these bounds don't depend on an type parameters",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1371 TRIVIAL_BOUNDS,
1401 Warn,
1402 "these bounds don't depend on an type parameters"
1403}
1404
1405#[doc =
r" Lint for trait and lifetime bounds that don't depend on type parameters"]
#[doc = r" which either do nothing, or stop the item from being used."]
pub struct TrivialConstraints;
#[automatically_derived]
impl ::core::marker::Copy for TrivialConstraints { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TrivialConstraints { }
#[automatically_derived]
impl ::core::clone::Clone for TrivialConstraints {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for TrivialConstraints {
fn name(&self) -> &'static str { "TrivialConstraints" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TRIVIAL_BOUNDS]))
}
}
impl TrivialConstraints {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[TRIVIAL_BOUNDS]))
}
}declare_lint_pass!(
1406 TrivialConstraints => [TRIVIAL_BOUNDS]
1409);
1410
1411impl<'tcx> LateLintPass<'tcx> for TrivialConstraints {
1412 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'tcx>) {
1413 use rustc_middle::ty::ClauseKind;
1414
1415 if cx.tcx.features().trivial_bounds() {
1416 let gen_clauses = cx.tcx.clauses_of(item.owner_id);
1417 for &(clause, span) in gen_clauses.clauses {
1418 let clause_kind_name = match clause.kind().skip_binder() {
1419 ClauseKind::Trait(..) => "trait",
1420 ClauseKind::TypeOutlives(..) | ClauseKind::RegionOutlives(..) => "lifetime",
1421
1422 ClauseKind::UnstableFeature(_)
1423 | ClauseKind::ConstArgHasType(..)
1425 | ClauseKind::Projection(..)
1428 | ClauseKind::WellFormed(..)
1430 | ClauseKind::ConstEvaluatable(..)
1432 | ty::ClauseKind::HostEffect(..) => continue,
1434 };
1435 if clause.is_global() {
1436 cx.emit_span_lint(
1437 TRIVIAL_BOUNDS,
1438 span,
1439 BuiltinTrivialBounds { clause_kind_name, clause },
1440 );
1441 }
1442 }
1443 }
1444 }
1445}
1446
1447#[doc =
r" The `double_negations` lint detects expressions of the form `--x`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" fn main() {"]
#[doc = r" let x = 1;"]
#[doc = r" let _b = --x;"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Negating something twice is usually the same as not negating it at all."]
#[doc =
r" However, a double negation in Rust can easily be confused with the"]
#[doc =
r" prefix decrement operator that exists in many languages derived from C."]
#[doc = r" Use `-(-x)` if you really wanted to negate the value twice."]
#[doc = r""]
#[doc = r" To decrement a value, use `x -= 1` instead."]
pub static DOUBLE_NEGATIONS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "DOUBLE_NEGATIONS",
default_level: ::rustc_lint_defs::Warn,
desc: "detects expressions of the form `--x`",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1448 pub DOUBLE_NEGATIONS,
1470 Warn,
1471 "detects expressions of the form `--x`"
1472}
1473
1474#[doc =
r" Lint for expressions of the form `--x` that can be confused with C's"]
#[doc = r" prefix decrement operator."]
pub struct DoubleNegations;
#[automatically_derived]
impl ::core::marker::Copy for DoubleNegations { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DoubleNegations { }
#[automatically_derived]
impl ::core::clone::Clone for DoubleNegations {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for DoubleNegations {
fn name(&self) -> &'static str { "DoubleNegations" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DOUBLE_NEGATIONS]))
}
}
impl DoubleNegations {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DOUBLE_NEGATIONS]))
}
}declare_lint_pass!(
1475 DoubleNegations => [DOUBLE_NEGATIONS]
1478);
1479
1480impl EarlyLintPass for DoubleNegations {
1481 #[inline]
1482 fn check_expr(&mut self, cx: &EarlyContext<'_>, expr: &ast::Expr) {
1483 if let ExprKind::Unary(UnOp::Neg, ref inner) = expr.kind
1486 && let ExprKind::Unary(UnOp::Neg, ref inner2) = inner.kind
1487 && !#[allow(non_exhaustive_omitted_patterns)] match inner2.kind {
ExprKind::Unary(UnOp::Neg, _) => true,
_ => false,
}matches!(inner2.kind, ExprKind::Unary(UnOp::Neg, _))
1488 && expr.span.eq_ctxt(inner.span)
1490 {
1491 cx.emit_span_lint(
1492 DOUBLE_NEGATIONS,
1493 expr.span,
1494 BuiltinDoubleNegations {
1495 add_parens: BuiltinDoubleNegationsAddParens {
1496 start_span: inner.span.shrink_to_lo(),
1497 end_span: inner.span.shrink_to_hi(),
1498 },
1499 },
1500 );
1501 }
1502 }
1503}
1504
1505pub mod soft {
1506 use super::*;
1507
1508 pub fn lint_vec() -> crate::LintVec {
1509 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[WHILE_TRUE, NON_SHORTHAND_FIELD_PATTERNS, UNSAFE_CODE, MISSING_DOCS,
MISSING_COPY_IMPLEMENTATIONS, MISSING_DEBUG_IMPLEMENTATIONS,
ANONYMOUS_PARAMETERS, UNUSED_DOC_COMMENTS,
NO_MANGLE_CONST_ITEMS, MUTABLE_TRANSMUTES, UNSTABLE_FEATURES,
UNREACHABLE_PUB, TYPE_ALIAS_BOUNDS, TRIVIAL_BOUNDS,
DOUBLE_NEGATIONS]))vec![
1510 WHILE_TRUE,
1511 NON_SHORTHAND_FIELD_PATTERNS,
1512 UNSAFE_CODE,
1513 MISSING_DOCS,
1514 MISSING_COPY_IMPLEMENTATIONS,
1515 MISSING_DEBUG_IMPLEMENTATIONS,
1516 ANONYMOUS_PARAMETERS,
1517 UNUSED_DOC_COMMENTS,
1518 NO_MANGLE_CONST_ITEMS,
1519 MUTABLE_TRANSMUTES,
1520 UNSTABLE_FEATURES,
1521 UNREACHABLE_PUB,
1522 TYPE_ALIAS_BOUNDS,
1523 TRIVIAL_BOUNDS,
1524 DOUBLE_NEGATIONS,
1525 ]
1526 }
1527}
1528
1529#[doc =
r" The `ellipsis_inclusive_range_patterns` lint detects the [`...` range"]
#[doc = r" pattern], which is deprecated."]
#[doc = r""]
#[doc =
r" [`...` range pattern]: https://doc.rust-lang.org/reference/patterns.html#range-patterns"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2018"]
#[doc = r" let x = 123;"]
#[doc = r" match x {"]
#[doc = r" 0...100 => {}"]
#[doc = r" _ => {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" The `...` range pattern syntax was changed to `..=` to avoid potential"]
#[doc =
r" confusion with the [`..` range expression]. Use the new form instead."]
#[doc = r""]
#[doc =
r" [`..` range expression]: https://doc.rust-lang.org/reference/expressions/range-expr.html"]
pub static ELLIPSIS_INCLUSIVE_RANGE_PATTERNS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "ELLIPSIS_INCLUSIVE_RANGE_PATTERNS",
default_level: ::rustc_lint_defs::Warn,
desc: "`...` range patterns are deprecated",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2021,
page_slug: "warnings-promoted-to-error",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1530 pub ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1554 Warn,
1555 "`...` range patterns are deprecated",
1556 @future_incompatible = FutureIncompatibleInfo {
1557 reason: fcw!(EditionError 2021 "warnings-promoted-to-error"),
1558 };
1559}
1560
1561#[derive(#[automatically_derived]
impl ::core::default::Default for EllipsisInclusiveRangePatterns {
#[inline]
fn default() -> Self {
Self { node_id: ::core::default::Default::default() }
}
}Default)]
1562pub struct EllipsisInclusiveRangePatterns {
1563 node_id: Option<ast::NodeId>,
1566}
1567
1568impl ::rustc_lint_defs::LintPass for EllipsisInclusiveRangePatterns {
fn name(&self) -> &'static str { "EllipsisInclusiveRangePatterns" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
}
}
impl EllipsisInclusiveRangePatterns {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]))
}
}impl_lint_pass!(EllipsisInclusiveRangePatterns => [ELLIPSIS_INCLUSIVE_RANGE_PATTERNS]);
1569
1570impl EarlyLintPass for EllipsisInclusiveRangePatterns {
1571 fn check_pat(&mut self, cx: &EarlyContext<'_>, pat: &ast::Pat) {
1572 if self.node_id.is_some() {
1573 return;
1575 }
1576
1577 use self::ast::PatKind;
1578 use self::ast::RangeSyntax::DotDotDot;
1579
1580 fn matches_ellipsis_pat(pat: &ast::Pat) -> Option<(Option<&Expr>, &Expr, Span)> {
1583 match &pat.kind {
1584 PatKind::Range(
1585 a,
1586 Some(b),
1587 Spanned { span, node: RangeEnd::Included(DotDotDot) },
1588 ) => Some((a.as_deref(), b, *span)),
1589 _ => None,
1590 }
1591 }
1592
1593 let (parentheses, endpoints) = match &pat.kind {
1594 PatKind::Ref(subpat, _, _) => (true, matches_ellipsis_pat(subpat)),
1595 _ => (false, matches_ellipsis_pat(pat)),
1596 };
1597
1598 if let Some((start, end, join)) = endpoints {
1599 if parentheses {
1600 self.node_id = Some(pat.id);
1601 let end = expr_to_string(end);
1602 let replace = match start {
1603 Some(start) => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&({0}..={1})",
expr_to_string(start), end))
})format!("&({}..={})", expr_to_string(start), end),
1604 None => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("&(..={0})", end))
})format!("&(..={end})"),
1605 };
1606 if join.edition() >= Edition::Edition2021 {
1607 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1608 span: pat.span,
1609 suggestion: pat.span,
1610 replace,
1611 });
1612 } else {
1613 cx.emit_span_lint(
1614 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1615 pat.span,
1616 BuiltinEllipsisInclusiveRangePatternsLint::Parenthesise {
1617 suggestion: pat.span,
1618 replace,
1619 },
1620 );
1621 }
1622 } else {
1623 let replace = "..=";
1624 if join.edition() >= Edition::Edition2021 {
1625 cx.sess().dcx().emit_err(BuiltinEllipsisInclusiveRangePatterns {
1626 span: pat.span,
1627 suggestion: join,
1628 replace: replace.to_string(),
1629 });
1630 } else {
1631 cx.emit_span_lint(
1632 ELLIPSIS_INCLUSIVE_RANGE_PATTERNS,
1633 join,
1634 BuiltinEllipsisInclusiveRangePatternsLint::NonParenthesise {
1635 suggestion: join,
1636 },
1637 );
1638 }
1639 };
1640 }
1641 }
1642
1643 fn check_pat_post(&mut self, _cx: &EarlyContext<'_>, pat: &ast::Pat) {
1644 if let Some(node_id) = self.node_id {
1645 if pat.id == node_id {
1646 self.node_id = None
1647 }
1648 }
1649 }
1650}
1651
1652#[doc =
r" The `keyword_idents_2018` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2018)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn dyn() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#dyn`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2018: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "KEYWORD_IDENTS_2018",
default_level: ::rustc_lint_defs::Allow,
desc: "detects edition keywords being used as an identifier",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2018,
page_slug: "new-keywords",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1653 pub KEYWORD_IDENTS_2018,
1689 Allow,
1690 "detects edition keywords being used as an identifier",
1691 @future_incompatible = FutureIncompatibleInfo {
1692 reason: fcw!(EditionError 2018 "new-keywords"),
1693 };
1694}
1695
1696#[doc =
r" The `keyword_idents_2024` lint detects edition keywords being used as an"]
#[doc = r" identifier."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,edition2015,compile_fail"]
#[doc = r" #![deny(keyword_idents_2024)]"]
#[doc = r" // edition 2015"]
#[doc = r" fn gen() {}"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Rust [editions] allow the language to evolve without breaking"]
#[doc =
r" backwards compatibility. This lint catches code that uses new keywords"]
#[doc =
r" that are added to the language that are used as identifiers (such as a"]
#[doc =
r" variable name, function name, etc.). If you switch the compiler to a"]
#[doc =
r" new edition without updating the code, then it will fail to compile if"]
#[doc = r" you are using a new keyword as an identifier."]
#[doc = r""]
#[doc =
r" You can manually change the identifiers to a non-keyword, or use a"]
#[doc =
r" [raw identifier], for example `r#gen`, to transition to a new edition."]
#[doc = r""]
#[doc =
r#" This lint solves the problem automatically. It is "allow" by default"#]
#[doc =
r" because the code is perfectly valid in older editions. The [`cargo"]
#[doc =
r#" fix`] tool with the `--edition` flag will switch this lint to "warn""#]
#[doc =
r" and automatically apply the suggested fix from the compiler (which is"]
#[doc =
r" to use a raw identifier). This provides a completely automated way to"]
#[doc = r" update old code for a new edition."]
#[doc = r""]
#[doc = r" [editions]: https://doc.rust-lang.org/edition-guide/"]
#[doc =
r" [raw identifier]: https://doc.rust-lang.org/reference/identifiers.html"]
#[doc =
r" [`cargo fix`]: https://doc.rust-lang.org/cargo/commands/cargo-fix.html"]
pub static KEYWORD_IDENTS_2024: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "KEYWORD_IDENTS_2024",
default_level: ::rustc_lint_defs::Allow,
desc: "detects edition keywords being used as an identifier",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::EditionError(::rustc_lint_defs::EditionFcw {
edition: rustc_span::edition::Edition::Edition2024,
page_slug: "gen-keyword",
}),
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
1697 pub KEYWORD_IDENTS_2024,
1733 Allow,
1734 "detects edition keywords being used as an identifier",
1735 @future_incompatible = FutureIncompatibleInfo {
1736 reason: fcw!(EditionError 2024 "gen-keyword"),
1737 };
1738}
1739
1740#[doc = r" Check for uses of edition keywords used as an identifier."]
pub struct KeywordIdents;
#[automatically_derived]
impl ::core::marker::Copy for KeywordIdents { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for KeywordIdents { }
#[automatically_derived]
impl ::core::clone::Clone for KeywordIdents {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for KeywordIdents {
fn name(&self) -> &'static str { "KeywordIdents" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]))
}
}
impl KeywordIdents {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]))
}
}declare_lint_pass!(
1741 KeywordIdents => [KEYWORD_IDENTS_2018, KEYWORD_IDENTS_2024]
1743);
1744
1745struct UnderMacro(bool);
1746
1747impl KeywordIdents {
1748 fn check_tokens(&mut self, cx: &EarlyContext<'_>, tokens: &TokenStream) {
1749 let mut prev_dollar = false;
1751 for tt in tokens.iter() {
1752 match tt {
1753 TokenTree::Token(token, _) => {
1755 if let Some((ident, token::IdentKind::Normal)) = token.ident() {
1756 if !prev_dollar {
1757 self.check_ident_token(cx, UnderMacro(true), ident, "");
1758 }
1759 } else if let Some((ident, token::IdentKind::Normal)) = token.lifetime() {
1760 self.check_ident_token(
1761 cx,
1762 UnderMacro(true),
1763 ident.without_first_quote(),
1764 "'",
1765 );
1766 } else if token.kind == TokenKind::Dollar {
1767 prev_dollar = true;
1768 continue;
1769 }
1770 }
1771 TokenTree::Delimited(.., tts) => self.check_tokens(cx, tts),
1772 }
1773 prev_dollar = false;
1774 }
1775 }
1776
1777 fn check_ident_token(
1778 &mut self,
1779 cx: &EarlyContext<'_>,
1780 UnderMacro(under_macro): UnderMacro,
1781 ident: Ident,
1782 prefix: &'static str,
1783 ) {
1784 let (lint, edition) = match ident.name {
1785 kw::Async | kw::Await | kw::Try => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1786
1787 kw::Dyn if !under_macro => (KEYWORD_IDENTS_2018, Edition::Edition2018),
1800
1801 kw::Gen => (KEYWORD_IDENTS_2024, Edition::Edition2024),
1802
1803 _ => return,
1804 };
1805
1806 if ident.span.edition() >= edition
1808 || cx.sess().psess.raw_identifier_spans.contains(ident.span)
1809 {
1810 return;
1811 }
1812
1813 cx.emit_span_lint(
1814 lint,
1815 ident.span,
1816 BuiltinKeywordIdents { kw: ident, next: edition, suggestion: ident.span, prefix },
1817 );
1818 }
1819}
1820
1821impl EarlyLintPass for KeywordIdents {
1822 fn check_mac_def(&mut self, cx: &EarlyContext<'_>, mac_def: &ast::MacroDef) {
1823 self.check_tokens(cx, &mac_def.body.tokens);
1824 }
1825 fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &ast::MacCall) {
1826 self.check_tokens(cx, &mac.args.tokens);
1827 }
1828 fn check_ident(&mut self, cx: &EarlyContext<'_>, ident: &Ident) {
1829 if ident.name.as_str().starts_with('\'') {
1830 self.check_ident_token(cx, UnderMacro(false), ident.without_first_quote(), "'");
1831 } else {
1832 self.check_ident_token(cx, UnderMacro(false), *ident, "");
1833 }
1834 }
1835}
1836
1837pub struct ExplicitOutlivesRequirements;
#[automatically_derived]
impl ::core::marker::Copy for ExplicitOutlivesRequirements { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for ExplicitOutlivesRequirements { }
#[automatically_derived]
impl ::core::clone::Clone for ExplicitOutlivesRequirements {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for ExplicitOutlivesRequirements {
fn name(&self) -> &'static str { "ExplicitOutlivesRequirements" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[EXPLICIT_OUTLIVES_REQUIREMENTS]))
}
}
impl ExplicitOutlivesRequirements {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[EXPLICIT_OUTLIVES_REQUIREMENTS]))
}
}declare_lint_pass!(ExplicitOutlivesRequirements => [EXPLICIT_OUTLIVES_REQUIREMENTS]);
1838
1839impl ExplicitOutlivesRequirements {
1840 fn lifetimes_outliving_lifetime<'tcx>(
1841 tcx: TyCtxt<'tcx>,
1842 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1843 item: LocalDefId,
1844 lifetime: LocalDefId,
1845 ) -> Vec<ty::Region<'tcx>> {
1846 let item_generics = tcx.generics_of(item);
1847
1848 inferred_outlives
1849 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1850 ty::ClauseKind::RegionOutlives(ty::OutlivesClause(a, b)) => match a.kind() {
1851 ty::ReEarlyParam(ebr)
1852 if item_generics.region_param(ebr, tcx).def_id == lifetime.to_def_id() =>
1853 {
1854 Some(b)
1855 }
1856 _ => None,
1857 },
1858 _ => None,
1859 })
1860 .collect()
1861 }
1862
1863 fn lifetimes_outliving_type<'tcx>(
1864 inferred_outlives: impl Iterator<Item = &'tcx (ty::Clause<'tcx>, Span)>,
1865 index: u32,
1866 ) -> Vec<ty::Region<'tcx>> {
1867 inferred_outlives
1868 .filter_map(|(clause, _)| match clause.kind().skip_binder() {
1869 ty::ClauseKind::TypeOutlives(ty::OutlivesClause(a, b)) => {
1870 a.is_param(index).then_some(b)
1871 }
1872 _ => None,
1873 })
1874 .collect()
1875 }
1876
1877 fn collect_outlives_bound_spans<'tcx>(
1878 &self,
1879 tcx: TyCtxt<'tcx>,
1880 bounds: &hir::GenericBounds<'_>,
1881 inferred_outlives: &[ty::Region<'tcx>],
1882 predicate_span: Span,
1883 item: DefId,
1884 ) -> Vec<(usize, Span)> {
1885 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1886
1887 let item_generics = tcx.generics_of(item);
1888
1889 bounds
1890 .iter()
1891 .enumerate()
1892 .filter_map(|(i, bound)| {
1893 let hir::GenericBound::Outlives(lifetime) = bound else {
1894 return None;
1895 };
1896
1897 let is_inferred = match tcx.named_bound_var(lifetime.hir_id) {
1898 Some(ResolvedArg::EarlyBound(def_id)) => inferred_outlives
1899 .iter()
1900 .any(|r| #[allow(non_exhaustive_omitted_patterns)] match r.kind() {
ty::ReEarlyParam(ebr) if
{ item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() }
=> true,
_ => false,
}matches!(r.kind(), ty::ReEarlyParam(ebr) if { item_generics.region_param(ebr, tcx).def_id == def_id.to_def_id() })),
1901 _ => false,
1902 };
1903
1904 if !is_inferred {
1905 return None;
1906 }
1907
1908 let span = bound.span().find_ancestor_inside(predicate_span)?;
1909 if span.in_external_macro(tcx.sess.source_map()) {
1910 return None;
1911 }
1912
1913 Some((i, span))
1914 })
1915 .collect()
1916 }
1917
1918 fn consolidate_outlives_bound_spans(
1919 &self,
1920 lo: Span,
1921 bounds: &hir::GenericBounds<'_>,
1922 bound_spans: Vec<(usize, Span)>,
1923 ) -> Vec<Span> {
1924 if bounds.is_empty() {
1925 return Vec::new();
1926 }
1927 if bound_spans.len() == bounds.len() {
1928 let (_, last_bound_span) = bound_spans[bound_spans.len() - 1];
1929 ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[lo.to(last_bound_span)]))vec![lo.to(last_bound_span)]
1932 } else {
1933 let mut merged = Vec::new();
1934 let mut last_merged_i = None;
1935
1936 let mut from_start = true;
1937 for (i, bound_span) in bound_spans {
1938 match last_merged_i {
1939 None if i == 0 => {
1941 merged.push(bound_span.to(bounds[1].span().shrink_to_lo()));
1942 last_merged_i = Some(0);
1943 }
1944 Some(h) if i == h + 1 => {
1946 if let Some(tail) = merged.last_mut() {
1947 let to_span = if from_start && i < bounds.len() {
1950 bounds[i + 1].span().shrink_to_lo()
1951 } else {
1952 bound_span
1953 };
1954 *tail = tail.to(to_span);
1955 last_merged_i = Some(i);
1956 } else {
1957 ::rustc_span::macros::bug_impl(None,
format_args!("another bound-span visited earlier"), Location::caller());bug!("another bound-span visited earlier");
1958 }
1959 }
1960 _ => {
1961 from_start = false;
1965 merged.push(bounds[i - 1].span().shrink_to_hi().to(bound_span));
1966 last_merged_i = Some(i);
1967 }
1968 }
1969 }
1970 merged
1971 }
1972 }
1973}
1974
1975impl<'tcx> LateLintPass<'tcx> for ExplicitOutlivesRequirements {
1976 fn check_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx hir::Item<'_>) {
1977 use rustc_middle::middle::resolve_bound_vars::ResolvedArg;
1978
1979 let def_id = item.owner_id.def_id;
1980 if let hir::ItemKind::Struct(_, generics, _)
1981 | hir::ItemKind::Enum(_, generics, _)
1982 | hir::ItemKind::Union(_, generics, _) = item.kind
1983 {
1984 let inferred_outlives = cx.tcx.inferred_outlives_of(def_id);
1985 if inferred_outlives.is_empty() {
1986 return;
1987 }
1988
1989 let ty_generics = cx.tcx.generics_of(def_id);
1990 let num_where_predicates = generics
1991 .predicates
1992 .iter()
1993 .filter(|predicate| predicate.kind.in_where_clause())
1994 .count();
1995
1996 let mut bound_count = 0;
1997 let mut lint_spans = Vec::new();
1998 let mut where_lint_spans = Vec::new();
1999 let mut dropped_where_predicate_count = 0;
2000 for (i, where_predicate) in generics.predicates.iter().enumerate() {
2001 let (relevant_lifetimes, bounds, predicate_span, in_where_clause) =
2002 match where_predicate.kind {
2003 hir::WherePredicateKind::RegionPredicate(predicate) => {
2004 if let Some(ResolvedArg::EarlyBound(region_def_id)) =
2005 cx.tcx.named_bound_var(predicate.lifetime.hir_id)
2006 {
2007 (
2008 Self::lifetimes_outliving_lifetime(
2009 cx.tcx,
2010 inferred_outlives.iter().filter(|(_, span)| {
2013 !where_predicate.span.contains(*span)
2014 }),
2015 item.owner_id.def_id,
2016 region_def_id,
2017 ),
2018 &predicate.bounds,
2019 where_predicate.span,
2020 predicate.in_where_clause,
2021 )
2022 } else {
2023 continue;
2024 }
2025 }
2026 hir::WherePredicateKind::BoundPredicate(predicate) => {
2027 match predicate.bounded_ty.kind {
2030 hir::TyKind::Path(hir::QPath::Resolved(None, path)) => {
2031 let Res::Def(DefKind::TyParam, def_id) = path.res else {
2032 continue;
2033 };
2034 let index = ty_generics.param_def_id_to_index[&def_id];
2035 if predicate.bound_generic_params.is_empty() {
2046 let ty_param = &ty_generics.own_params[index as usize];
2047 let param_ty =
2048 Ty::new_param(cx.tcx, ty_param.index, ty_param.name);
2049 if !param_ty.is_sized(cx.tcx, cx.typing_env()) {
2050 continue;
2051 }
2052 }
2053 (
2054 Self::lifetimes_outliving_type(
2055 inferred_outlives.iter().filter(|(_, span)| {
2058 !where_predicate.span.contains(*span)
2059 }),
2060 index,
2061 ),
2062 &predicate.bounds,
2063 where_predicate.span,
2064 predicate.origin == PredicateOrigin::WhereClause,
2065 )
2066 }
2067 _ => {
2068 continue;
2069 }
2070 }
2071 }
2072 };
2073 if relevant_lifetimes.is_empty() {
2074 continue;
2075 }
2076
2077 let bound_spans = self.collect_outlives_bound_spans(
2078 cx.tcx,
2079 bounds,
2080 &relevant_lifetimes,
2081 predicate_span,
2082 item.owner_id.to_def_id(),
2083 );
2084 bound_count += bound_spans.len();
2085
2086 let drop_predicate = bound_spans.len() == bounds.len();
2087 if drop_predicate && in_where_clause {
2088 dropped_where_predicate_count += 1;
2089 }
2090
2091 if drop_predicate {
2092 if !in_where_clause {
2093 lint_spans.push(predicate_span);
2094 } else if predicate_span.from_expansion() {
2095 where_lint_spans.push(predicate_span);
2097 } else if i + 1 < num_where_predicates {
2098 let next_predicate_span = generics.predicates[i + 1].span;
2101 if next_predicate_span.from_expansion() {
2102 where_lint_spans.push(predicate_span);
2103 } else {
2104 where_lint_spans
2105 .push(predicate_span.to(next_predicate_span.shrink_to_lo()));
2106 }
2107 } else {
2108 let where_span = generics.where_clause_span;
2110 if where_span.from_expansion() {
2111 where_lint_spans.push(predicate_span);
2112 } else {
2113 where_lint_spans.push(predicate_span.to(where_span.shrink_to_hi()));
2114 }
2115 }
2116 } else {
2117 where_lint_spans.extend(self.consolidate_outlives_bound_spans(
2118 predicate_span.shrink_to_lo(),
2119 bounds,
2120 bound_spans,
2121 ));
2122 }
2123 }
2124
2125 if generics.has_where_clause_predicates
2128 && dropped_where_predicate_count == num_where_predicates
2129 {
2130 let where_span = generics.where_clause_span;
2131 let full_where_span =
2135 if let hir::ItemKind::Struct(_, _, hir::VariantData::Tuple(..)) = item.kind {
2136 where_span
2137 } else {
2138 generics.span.shrink_to_hi().to(where_span)
2139 };
2140
2141 if where_lint_spans.iter().all(|&sp| full_where_span.contains(sp)) {
2144 lint_spans.push(full_where_span);
2145 } else {
2146 lint_spans.extend(where_lint_spans);
2147 }
2148 } else {
2149 lint_spans.extend(where_lint_spans);
2150 }
2151
2152 if !lint_spans.is_empty() {
2153 let applicability = if lint_spans.iter().all(|sp| sp.can_be_used_for_suggestions())
2155 {
2156 Applicability::MachineApplicable
2157 } else {
2158 Applicability::MaybeIncorrect
2159 };
2160
2161 lint_spans.sort_unstable();
2164 lint_spans.dedup();
2165
2166 cx.emit_span_lint(
2167 EXPLICIT_OUTLIVES_REQUIREMENTS,
2168 lint_spans.clone(),
2169 BuiltinExplicitOutlives {
2170 suggestion: BuiltinExplicitOutlivesSuggestion {
2171 spans: lint_spans,
2172 applicability,
2173 count: bound_count,
2174 },
2175 },
2176 );
2177 }
2178 }
2179 }
2180}
2181
2182#[doc =
r" The `incomplete_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that may function improperly in some or all"]
#[doc = r" cases."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(generic_const_exprs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Although it is encouraged for people to experiment with unstable"]
#[doc =
r" features, some of them are known to be incomplete or faulty. This lint"]
#[doc =
r" is a signal that the feature has not yet been finished, and you may"]
#[doc = r" experience problems with it."]
pub static INCOMPLETE_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INCOMPLETE_FEATURES",
default_level: ::rustc_lint_defs::Warn,
desc: "incomplete features that may function improperly in some or all cases",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2183 pub INCOMPLETE_FEATURES,
2204 Warn,
2205 "incomplete features that may function improperly in some or all cases"
2206}
2207
2208#[doc =
r" The `internal_features` lint detects unstable features enabled with"]
#[doc =
r" the [`feature` attribute] that are internal to the compiler or standard"]
#[doc = r" library."]
#[doc = r""]
#[doc =
r" [`feature` attribute]: https://doc.rust-lang.org/nightly/unstable-book/"]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #![feature(rustc_attrs)]"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" These features are an implementation detail of the compiler and standard"]
#[doc = r" library and are not supposed to be used in user code."]
pub static INTERNAL_FEATURES: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INTERNAL_FEATURES",
default_level: ::rustc_lint_defs::Warn,
desc: "internal features are not supposed to be used",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2209 pub INTERNAL_FEATURES,
2228 Warn,
2229 "internal features are not supposed to be used"
2230}
2231
2232#[doc =
r" Check for used feature gates in `INCOMPLETE_FEATURES` in `rustc_feature/src/unstable.rs`."]
pub struct IncompleteInternalFeatures;
#[automatically_derived]
impl ::core::marker::Copy for IncompleteInternalFeatures { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for IncompleteInternalFeatures { }
#[automatically_derived]
impl ::core::clone::Clone for IncompleteInternalFeatures {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for IncompleteInternalFeatures {
fn name(&self) -> &'static str { "IncompleteInternalFeatures" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INCOMPLETE_FEATURES, INTERNAL_FEATURES]))
}
}
impl IncompleteInternalFeatures {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INCOMPLETE_FEATURES, INTERNAL_FEATURES]))
}
}declare_lint_pass!(
2233 IncompleteInternalFeatures => [INCOMPLETE_FEATURES, INTERNAL_FEATURES]
2235);
2236
2237impl EarlyLintPass for IncompleteInternalFeatures {
2238 fn check_crate(&mut self, cx: &EarlyContext<'_>, _: &ast::Crate) {
2239 let features = cx.builder.features();
2240
2241 features
2242 .enabled_features_iter_stable_order()
2243 .filter(|(name, _)| features.incomplete(*name) || features.internal(*name))
2244 .for_each(|(name, span)| {
2245 if features.incomplete(name) {
2246 let note = rustc_feature::find_feature_issue(name, GateIssue::Language)
2247 .map(|n| BuiltinFeatureIssueNote { n });
2248 let help = HAS_MIN_FEATURES
2249 .contains(&name)
2250 .then_some(BuiltinIncompleteFeaturesHelp { name });
2251
2252 cx.emit_span_lint(
2253 INCOMPLETE_FEATURES,
2254 span,
2255 BuiltinIncompleteFeatures { name, note, help },
2256 );
2257 } else {
2258 cx.emit_span_lint(INTERNAL_FEATURES, span, BuiltinInternalFeatures { name });
2259 }
2260 });
2261 }
2262}
2263
2264const HAS_MIN_FEATURES: &[Symbol] = &[sym::specialization];
2265
2266#[doc =
r" The `invalid_value` lint detects creating a value that is not valid,"]
#[doc = r" such as a null reference."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,no_run"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" unsafe {"]
#[doc = r" let x: &'static i32 = std::mem::zeroed();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" In some situations the compiler can detect that the code is creating"]
#[doc = r" an invalid value, which should be avoided."]
#[doc = r""]
#[doc = r" In particular, this lint will check for improper use of"]
#[doc = r" [`mem::zeroed`], [`mem::uninitialized`], [`mem::transmute`], and"]
#[doc =
r" [`MaybeUninit::assume_init`] that can cause [undefined behavior]. The"]
#[doc =
r" lint should provide extra information to indicate what the problem is"]
#[doc = r" and a possible solution."]
#[doc = r""]
#[doc = r" [`mem::zeroed`]: https://doc.rust-lang.org/std/mem/fn.zeroed.html"]
#[doc =
r" [`mem::uninitialized`]: https://doc.rust-lang.org/std/mem/fn.uninitialized.html"]
#[doc =
r" [`mem::transmute`]: https://doc.rust-lang.org/std/mem/fn.transmute.html"]
#[doc =
r" [`MaybeUninit::assume_init`]: https://doc.rust-lang.org/std/mem/union.MaybeUninit.html#method.assume_init"]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static INVALID_VALUE: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INVALID_VALUE",
default_level: ::rustc_lint_defs::Warn,
desc: "an invalid value is being created (such as a null reference)",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2267 pub INVALID_VALUE,
2298 Warn,
2299 "an invalid value is being created (such as a null reference)"
2300}
2301
2302pub struct InvalidValue;
#[automatically_derived]
impl ::core::marker::Copy for InvalidValue { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InvalidValue { }
#[automatically_derived]
impl ::core::clone::Clone for InvalidValue {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for InvalidValue {
fn name(&self) -> &'static str { "InvalidValue" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INVALID_VALUE]))
}
}
impl InvalidValue {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INVALID_VALUE]))
}
}declare_lint_pass!(InvalidValue => [INVALID_VALUE]);
2303
2304pub struct InitError {
2306 pub(crate) message: String,
2307 pub(crate) span: Option<Span>,
2309 pub(crate) nested: Option<Box<InitError>>,
2311}
2312impl InitError {
2313 fn spanned(self, span: Span) -> InitError {
2314 Self { span: Some(span), ..self }
2315 }
2316
2317 fn nested(self, nested: impl Into<Option<InitError>>) -> InitError {
2318 if !self.nested.is_none() {
::core::panicking::panic("assertion failed: self.nested.is_none()")
};assert!(self.nested.is_none());
2319 Self { nested: nested.into().map(Box::new), ..self }
2320 }
2321}
2322
2323impl<'a> From<&'a str> for InitError {
2324 fn from(s: &'a str) -> Self {
2325 s.to_owned().into()
2326 }
2327}
2328impl From<String> for InitError {
2329 fn from(message: String) -> Self {
2330 Self { message, span: None, nested: None }
2331 }
2332}
2333
2334impl<'tcx> LateLintPass<'tcx> for InvalidValue {
2335 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2336 #[derive(#[automatically_derived]
impl ::core::fmt::Debug for InitKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
InitKind::Zeroed => "Zeroed",
InitKind::Uninit => "Uninit",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for InitKind { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InitKind { }
#[automatically_derived]
impl ::core::clone::Clone for InitKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for InitKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for InitKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq)]
2337 enum InitKind {
2338 Zeroed,
2339 Uninit,
2340 }
2341
2342 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2344 use hir::ExprKind::*;
2345 use rustc_ast::LitKind::*;
2346 match &expr.kind {
2347 Lit(lit) => {
2348 if let Int(i, _) = lit.node {
2349 i == 0
2350 } else {
2351 false
2352 }
2353 }
2354 Tup(tup) => tup.iter().all(is_zero),
2355 _ => false,
2356 }
2357 }
2358
2359 fn is_dangerous_init(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> Option<InitKind> {
2361 if let hir::ExprKind::Call(path_expr, args) = expr.kind
2362 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2364 {
2365 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2366 match cx.tcx.get_diagnostic_name(def_id) {
2367 Some(sym::mem_zeroed) => return Some(InitKind::Zeroed),
2368 Some(sym::mem_uninitialized) => return Some(InitKind::Uninit),
2369 Some(sym::transmute) if is_zero(&args[0]) => return Some(InitKind::Zeroed),
2370 _ => {}
2371 }
2372 } else if let hir::ExprKind::MethodCall(_, receiver, ..) = expr.kind {
2373 let def_id = cx.typeck_results().type_dependent_def_id(expr.hir_id)?;
2375 if cx.tcx.is_diagnostic_item(sym::assume_init, def_id) {
2376 if let hir::ExprKind::Call(path_expr, _) = receiver.kind
2379 && let hir::ExprKind::Path(ref qpath) = path_expr.kind
2380 {
2381 let def_id = cx.qpath_res(qpath, path_expr.hir_id).opt_def_id()?;
2382 match cx.tcx.get_diagnostic_name(def_id) {
2383 Some(sym::maybe_uninit_zeroed) => return Some(InitKind::Zeroed),
2384 Some(sym::maybe_uninit_uninit) => return Some(InitKind::Uninit),
2385 _ => {}
2386 }
2387 }
2388 }
2389 }
2390
2391 None
2392 }
2393
2394 fn variant_find_init_error<'tcx>(
2395 cx: &LateContext<'tcx>,
2396 ty: Ty<'tcx>,
2397 variant: &VariantDef,
2398 args: ty::GenericArgsRef<'tcx>,
2399 descr: &str,
2400 init: InitKind,
2401 ) -> Option<InitError> {
2402 let mut field_err = variant.fields.iter().find_map(|field| {
2403 ty_find_init_error(cx, field.ty(cx.tcx, args).skip_norm_wip(), init).map(
2404 |mut err| {
2405 if !field.did.is_local() {
2406 err
2407 } else if err.span.is_none() {
2408 err.span = Some(cx.tcx.def_span(field.did));
2409 (&mut err.message).write_fmt(format_args!(" (in this {0})", descr))write!(&mut err.message, " (in this {descr})").unwrap();
2410 err
2411 } else {
2412 InitError::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("in this {0}", descr))
})format!("in this {descr}"))
2413 .spanned(cx.tcx.def_span(field.did))
2414 .nested(err)
2415 }
2416 },
2417 )
2418 });
2419
2420 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(ty)) {
2422 if let BackendRepr::Scalar(scalar) | BackendRepr::ScalarPair { a: scalar, .. } =
2423 &layout.backend_repr
2424 {
2425 let range = scalar.valid_range(cx);
2426 let msg = if !range.contains(0) {
2427 "must be non-null"
2428 } else if init == InitKind::Uninit && !scalar.is_always_valid(cx) {
2429 "must be initialized inside its custom valid range"
2434 } else {
2435 return field_err;
2436 };
2437 if let Some(field_err) = &mut field_err {
2438 if field_err.message.contains(msg) {
2441 field_err.message = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("because {0}", field_err.message))
})format!("because {}", field_err.message);
2442 }
2443 }
2444 return Some(InitError::from(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("`{0}` {1}", ty, msg))
})format!("`{ty}` {msg}")).nested(field_err));
2445 }
2446 }
2447 field_err
2448 }
2449
2450 fn ty_find_init_error<'tcx>(
2453 cx: &LateContext<'tcx>,
2454 ty: Ty<'tcx>,
2455 init: InitKind,
2456 ) -> Option<InitError> {
2457 let ty = cx
2458 .tcx
2459 .try_normalize_erasing_regions(cx.typing_env(), Unnormalized::new_wip(ty))
2460 .unwrap_or(ty);
2461
2462 match ty.kind() {
2463 ty::Ref(..) => Some("references must be non-null".into()),
2465 ty::Adt(..) if ty.is_box() => Some("`Box` must be non-null".into()),
2466 ty::FnPtr(..) => Some("function pointers must be non-null".into()),
2467 ty::Never => Some("the `!` type has no valid value".into()),
2468 ty::RawPtr(ty, _) if #[allow(non_exhaustive_omitted_patterns)] match ty.kind() {
ty::Dynamic(..) => true,
_ => false,
}matches!(ty.kind(), ty::Dynamic(..)) =>
2469 {
2471 Some("the vtable of a wide raw pointer must be non-null".into())
2472 }
2473 ty::Bool if init == InitKind::Uninit => {
2475 Some("booleans must be either `true` or `false`".into())
2476 }
2477 ty::Char if init == InitKind::Uninit => {
2478 Some("characters must be a valid Unicode codepoint".into())
2479 }
2480 ty::Int(_) | ty::Uint(_) if init == InitKind::Uninit => {
2481 Some("integers must be initialized".into())
2482 }
2483 ty::Float(_) if init == InitKind::Uninit => {
2484 Some("floats must be initialized".into())
2485 }
2486 ty::RawPtr(_, _) if init == InitKind::Uninit => {
2487 Some("raw pointers must be initialized".into())
2488 }
2489 ty::Adt(adt_def, args) if !adt_def.is_union() => {
2491 if adt_def.is_struct() {
2493 return variant_find_init_error(
2494 cx,
2495 ty,
2496 adt_def.non_enum_variant(),
2497 args,
2498 "struct field",
2499 init,
2500 );
2501 }
2502 let span = cx.tcx.def_span(adt_def.did());
2504 let mut potential_variants = adt_def.variants().iter().filter_map(|variant| {
2505 let definitely_inhabited = match variant
2506 .inhabited_predicate(cx.tcx)
2507 .instantiate(cx.tcx, args)
2508 .apply_any_module(cx.tcx, cx.typing_env())
2509 {
2510 Some(false) => return None,
2512 Some(true) => true,
2514 None => false,
2515 };
2516 Some((variant, definitely_inhabited))
2517 });
2518 let Some(first_variant) = potential_variants.next() else {
2519 return Some(
2520 InitError::from("enums with no inhabited variants have no valid value")
2521 .spanned(span),
2522 );
2523 };
2524 let Some(second_variant) = potential_variants.next() else {
2526 return variant_find_init_error(
2529 cx,
2530 ty,
2531 first_variant.0,
2532 args,
2533 "field of the only potentially inhabited enum variant",
2534 init,
2535 );
2536 };
2537 if init == InitKind::Uninit {
2542 let definitely_inhabited = (first_variant.1 as usize)
2543 + (second_variant.1 as usize)
2544 + potential_variants
2545 .filter(|(_variant, definitely_inhabited)| *definitely_inhabited)
2546 .count();
2547 if definitely_inhabited > 1 {
2548 return Some(InitError::from(
2549 "enums with multiple inhabited variants have to be initialized to a variant",
2550 ).spanned(span));
2551 }
2552 }
2553 None
2555 }
2556 ty::Tuple(..) => {
2557 ty.tuple_fields().iter().find_map(|field| ty_find_init_error(cx, field, init))
2559 }
2560 ty::Array(ty, len) => {
2561 if #[allow(non_exhaustive_omitted_patterns)] match len.try_to_target_usize(cx.tcx)
{
Some(v) if v > 0 => true,
_ => false,
}matches!(len.try_to_target_usize(cx.tcx), Some(v) if v > 0) {
2562 ty_find_init_error(cx, *ty, init)
2564 } else {
2565 None
2567 }
2568 }
2569 _ => None,
2571 }
2572 }
2573
2574 if let Some(init) = is_dangerous_init(cx, expr) {
2575 let conjured_ty = cx.typeck_results().expr_ty(expr);
2579 if let Some(err) = {
let _guard = NoTrimmedGuard::new();
ty_find_init_error(cx, conjured_ty, init)
}with_no_trimmed_paths!(ty_find_init_error(cx, conjured_ty, init)) {
2580 let msg = match init {
2581 InitKind::Zeroed => {
2582 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the type `{$ty}` does not permit zero-initialization"))msg!("the type `{$ty}` does not permit zero-initialization")
2583 }
2584 InitKind::Uninit => {
2585 rustc_errors::DiagMessage::Inline(std::borrow::Cow::Borrowed("the type `{$ty}` does not permit being left uninitialized"))msg!("the type `{$ty}` does not permit being left uninitialized")
2586 }
2587 };
2588 let sub = BuiltinUnpermittedTypeInitSub { err };
2589 cx.emit_span_lint(
2590 INVALID_VALUE,
2591 expr.span,
2592 BuiltinUnpermittedTypeInit {
2593 msg,
2594 ty: conjured_ty,
2595 label: expr.span,
2596 sub,
2597 tcx: cx.tcx,
2598 },
2599 );
2600 }
2601 }
2602 }
2603}
2604
2605#[doc =
r" The `deref_nullptr` lint detects when a null pointer is dereferenced,"]
#[doc = r" which causes [undefined behavior]."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![allow(unused)]"]
#[doc = r" use std::ptr;"]
#[doc = r" unsafe {"]
#[doc = r" let x = &*ptr::null::<i32>();"]
#[doc = r" let x = ptr::addr_of!(*ptr::null::<i32>());"]
#[doc = r" let x = *(0 as *const i32);"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" Dereferencing a null pointer causes [undefined behavior] if it is accessed"]
#[doc = r" (loaded from or stored to)."]
#[doc = r""]
#[doc =
r" [undefined behavior]: https://doc.rust-lang.org/reference/behavior-considered-undefined.html"]
pub static DEREF_NULLPTR: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "DEREF_NULLPTR",
default_level: ::rustc_lint_defs::Deny,
desc: "detects when an null pointer is dereferenced",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2606 pub DEREF_NULLPTR,
2630 Deny,
2631 "detects when an null pointer is dereferenced"
2632}
2633
2634pub struct DerefNullPtr;
#[automatically_derived]
impl ::core::marker::Copy for DerefNullPtr { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for DerefNullPtr { }
#[automatically_derived]
impl ::core::clone::Clone for DerefNullPtr {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for DerefNullPtr {
fn name(&self) -> &'static str { "DerefNullPtr" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DEREF_NULLPTR]))
}
}
impl DerefNullPtr {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[DEREF_NULLPTR]))
}
}declare_lint_pass!(DerefNullPtr => [DEREF_NULLPTR]);
2635
2636impl<'tcx> LateLintPass<'tcx> for DerefNullPtr {
2637 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &hir::Expr<'_>) {
2638 fn is_null_ptr(cx: &LateContext<'_>, expr: &hir::Expr<'_>) -> bool {
2640 let pointer_ty = cx.typeck_results().expr_ty(expr);
2641 let ty::RawPtr(pointee, _) = pointer_ty.kind() else {
2642 return false;
2643 };
2644 if let Ok(layout) = cx.tcx.layout_of(cx.typing_env().as_query_input(*pointee)) {
2645 if layout.layout.size() == rustc_abi::Size::ZERO {
2646 return false;
2647 }
2648 }
2649
2650 match &expr.kind {
2651 hir::ExprKind::Cast(expr, ty) => {
2652 if let hir::TyKind::Ptr(_) = ty.kind {
2653 return is_zero(expr) || is_null_ptr(cx, expr);
2654 }
2655 }
2656 hir::ExprKind::Call(path, _) => {
2658 if let hir::ExprKind::Path(ref qpath) = path.kind
2659 && let Some(def_id) = cx.qpath_res(qpath, path.hir_id).opt_def_id()
2660 {
2661 return #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.get_diagnostic_name(def_id)
{
Some(sym::ptr_null | sym::ptr_null_mut) => true,
_ => false,
}matches!(
2662 cx.tcx.get_diagnostic_name(def_id),
2663 Some(sym::ptr_null | sym::ptr_null_mut)
2664 );
2665 }
2666 }
2667 _ => {}
2668 }
2669 false
2670 }
2671
2672 fn is_zero(expr: &hir::Expr<'_>) -> bool {
2674 match &expr.kind {
2675 hir::ExprKind::Lit(lit) => {
2676 if let LitKind::Int(a, _) = lit.node {
2677 return a == 0;
2678 }
2679 }
2680 _ => {}
2681 }
2682 false
2683 }
2684
2685 if let hir::ExprKind::Unary(hir::UnOp::Deref, expr_deref) = expr.kind
2686 && is_null_ptr(cx, expr_deref)
2687 {
2688 if let hir::Node::Expr(hir::Expr {
2689 kind: hir::ExprKind::AddrOf(hir::BorrowKind::Raw, ..),
2690 ..
2691 }) = cx.tcx.parent_hir_node(expr.hir_id)
2692 {
2693 } else {
2695 cx.emit_span_lint(
2696 DEREF_NULLPTR,
2697 expr.span,
2698 BuiltinDerefNullptr { label: expr.span },
2699 );
2700 }
2701 }
2702 }
2703}
2704
2705#[doc =
r" The `named_asm_labels` lint detects the use of named labels in the"]
#[doc = r" inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" # #![feature(asm_experimental_arch)]"]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" unsafe {"]
#[doc = r#" asm!("foo: bar");"#]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" LLVM is allowed to duplicate inline assembly blocks for any"]
#[doc =
r" reason, for example when it is in a function that gets inlined. Because"]
#[doc =
r" of this, GNU assembler [local labels] *must* be used instead of labels"]
#[doc =
r" with a name. Using named labels might cause assembler or linker errors."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc =
r" [local labels]: https://sourceware.org/binutils/docs/as/Symbol-Names.html#Local-Labels"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static NAMED_ASM_LABELS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "NAMED_ASM_LABELS",
default_level: ::rustc_lint_defs::Deny,
desc: "named labels in inline assembly",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2706 pub NAMED_ASM_LABELS,
2736 Deny,
2737 "named labels in inline assembly",
2738}
2739
2740#[doc =
r" The `binary_asm_labels` lint detects the use of numeric labels containing only binary"]
#[doc = r" digits in the inline `asm!` macro."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,ignore (fails on non-x86_64)"]
#[doc = r#" #![cfg(target_arch = "x86_64")]"#]
#[doc = r""]
#[doc = r" use std::arch::asm;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" unsafe {"]
#[doc = r#" asm!("0: jmp 0b");"#]
#[doc = r" }"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" This will produce:"]
#[doc = r""]
#[doc = r" ```text"]
#[doc =
r" error: avoid using labels containing only the digits `0` and `1` in inline assembly"]
#[doc = r" --> <source>:7:15"]
#[doc = r" |"]
#[doc = r#" 7 | asm!("0: jmp 0b");"#]
#[doc =
r" | ^ use a different label that doesn't start with `0` or `1`"]
#[doc = r" |"]
#[doc = r" = help: start numbering with `2` instead"]
#[doc =
r" = note: an LLVM bug makes these labels ambiguous with a binary literal number on x86"]
#[doc =
r" = note: see <https://github.com/llvm/llvm-project/issues/99547> for more information"]
#[doc = r" = note: `#[deny(binary_asm_labels)]` on by default"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc =
r" An [LLVM bug] causes this code to fail to compile because it interprets the `0b` as a binary"]
#[doc =
r" literal instead of a reference to the previous local label `0`. To work around this bug,"]
#[doc = r" don't use labels that could be confused with a binary literal."]
#[doc = r""]
#[doc = r" This behavior is platform-specific to x86 and x86-64."]
#[doc = r""]
#[doc = r" See the explanation in [Rust By Example] for more details."]
#[doc = r""]
#[doc = r" [LLVM bug]: https://github.com/llvm/llvm-project/issues/99547"]
#[doc =
r" [Rust By Example]: https://doc.rust-lang.org/nightly/rust-by-example/unsafe/asm.html#labels"]
pub static BINARY_ASM_LABELS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "BINARY_ASM_LABELS",
default_level: ::rustc_lint_defs::Deny,
desc: "labels in inline assembly containing only 0 or 1 digits",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
2741 pub BINARY_ASM_LABELS,
2786 Deny,
2787 "labels in inline assembly containing only 0 or 1 digits",
2788}
2789
2790pub struct AsmLabels;
#[automatically_derived]
impl ::core::marker::Copy for AsmLabels { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AsmLabels { }
#[automatically_derived]
impl ::core::clone::Clone for AsmLabels {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for AsmLabels {
fn name(&self) -> &'static str { "AsmLabels" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NAMED_ASM_LABELS, BINARY_ASM_LABELS]))
}
}
impl AsmLabels {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[NAMED_ASM_LABELS, BINARY_ASM_LABELS]))
}
}declare_lint_pass!(AsmLabels => [NAMED_ASM_LABELS, BINARY_ASM_LABELS]);
2791
2792#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AsmLabelKind {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
AsmLabelKind::Named => "Named",
AsmLabelKind::FormatArg => "FormatArg",
AsmLabelKind::Binary => "Binary",
})
}
}Debug, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for AsmLabelKind { }
#[automatically_derived]
impl ::core::clone::Clone for AsmLabelKind {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::marker::Copy for AsmLabelKind { }Copy, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for AsmLabelKind { }
#[automatically_derived]
impl ::core::cmp::PartialEq for AsmLabelKind {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for AsmLabelKind { }Eq)]
2793enum AsmLabelKind {
2794 Named,
2795 FormatArg,
2796 Binary,
2797}
2798
2799pub fn is_hexagon_register_span(possible_label: &str) -> bool {
2806 if let Some(colon_idx) = possible_label.find(':') {
2808 let after_colon = &possible_label[colon_idx + 1..];
2809 is_hexagon_register_span_impl(&possible_label[..colon_idx], after_colon)
2810 } else {
2811 false
2812 }
2813}
2814
2815fn is_hexagon_register_span_context(
2817 possible_label: &str,
2818 statement: &str,
2819 colon_idx: usize,
2820) -> bool {
2821 let after_colon_start = colon_idx + 1;
2823 if after_colon_start >= statement.len() {
2824 return false;
2825 }
2826
2827 let after_colon_full = &statement[after_colon_start..];
2829 let after_colon = after_colon_full
2830 .chars()
2831 .take_while(|&c| c.is_ascii_alphanumeric() || c == '.')
2832 .collect::<String>();
2833
2834 is_hexagon_register_span_impl(possible_label, &after_colon)
2835}
2836
2837fn is_hexagon_register_span_impl(before_colon: &str, after_colon: &str) -> bool {
2839 if before_colon.len() < 1 || after_colon.is_empty() {
2840 return false;
2841 }
2842
2843 let mut chars = before_colon.chars();
2844 let start = chars.next().unwrap();
2845
2846 if !start.is_ascii_alphabetic() {
2848 return false;
2849 }
2850
2851 let rest = &before_colon[1..];
2852
2853 if rest.is_empty() || !rest.chars().all(|c| c.is_ascii_digit()) {
2855 return false;
2856 }
2857
2858 let digits_after = after_colon.chars().take_while(|c| c.is_ascii_digit()).collect::<String>();
2860
2861 !digits_after.is_empty()
2862}
2863
2864impl<'tcx> LateLintPass<'tcx> for AsmLabels {
2865 fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
2866 if let hir::Expr {
2867 kind:
2868 hir::ExprKind::InlineAsm(hir::InlineAsm {
2869 asm_macro: asm_macro @ (AsmMacro::Asm | AsmMacro::NakedAsm),
2870 template_strs,
2871 options,
2872 ..
2873 }),
2874 ..
2875 } = expr
2876 {
2877 if *asm_macro == AsmMacro::NakedAsm {
2880 let def_id = expr.hir_id.owner.def_id;
2881 if !cx.tcx.generics_of(def_id).requires_monomorphization(cx.tcx) {
2882 return;
2883 }
2884 }
2885
2886 let raw = options.contains(InlineAsmOptions::RAW);
2888
2889 for (template_sym, template_snippet, template_span) in template_strs.iter() {
2890 let template_str = template_sym.as_str();
2891 let find_label_span = |needle: &str| -> Option<Span> {
2892 if let Some(template_snippet) = template_snippet {
2893 let snippet = template_snippet.as_str();
2894 if let Some(pos) = snippet.find(needle) {
2895 let end = pos
2896 + snippet[pos..]
2897 .find(|c| c == ':')
2898 .unwrap_or(snippet[pos..].len() - 1);
2899 let inner = InnerSpan::new(pos, end);
2900 return Some(template_span.from_inner(inner));
2901 }
2902 }
2903
2904 None
2905 };
2906
2907 let mut spans = Vec::new();
2909
2910 let statements = template_str.split(|c| #[allow(non_exhaustive_omitted_patterns)] match c {
'\n' | ';' => true,
_ => false,
}matches!(c, '\n' | ';'));
2913 for statement in statements {
2914 let statement = statement.find("//").map_or(statement, |idx| &statement[..idx]);
2916
2917 let mut start_idx = 0;
2919 'label_loop: for (idx, _) in statement.match_indices(':') {
2920 let possible_label = statement[start_idx..idx].trim();
2921 let mut chars = possible_label.chars();
2922
2923 let Some(start) = chars.next() else {
2924 break 'label_loop;
2927 };
2928
2929 let mut in_bracket = false;
2931 let mut label_kind = AsmLabelKind::Named;
2932
2933 if !raw && start == '{' {
2935 in_bracket = true;
2936 label_kind = AsmLabelKind::FormatArg;
2937 } else if #[allow(non_exhaustive_omitted_patterns)] match start {
'0' | '1' => true,
_ => false,
}matches!(start, '0' | '1') {
2938 label_kind = AsmLabelKind::Binary;
2940 } else if !(start.is_ascii_alphabetic() || #[allow(non_exhaustive_omitted_patterns)] match start {
'.' | '_' => true,
_ => false,
}matches!(start, '.' | '_')) {
2941 break 'label_loop;
2944 }
2945
2946 if #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
Some(InlineAsmArch::Hexagon) => true,
_ => false,
}matches!(cx.tcx.sess.asm_arch, Some(InlineAsmArch::Hexagon))
2949 && is_hexagon_register_span_context(possible_label, statement, idx)
2950 {
2951 break 'label_loop;
2952 }
2953
2954 for c in chars {
2955 if !raw && in_bracket {
2961 if c == '{' {
2962 break 'label_loop;
2965 }
2966
2967 if c == '}' {
2968 in_bracket = false;
2970 }
2971 } else if !raw && c == '{' {
2972 in_bracket = true;
2974 label_kind = AsmLabelKind::FormatArg;
2975 } else {
2976 let can_continue = match label_kind {
2977 AsmLabelKind::Named | AsmLabelKind::FormatArg => {
2980 c.is_ascii_alphanumeric() || #[allow(non_exhaustive_omitted_patterns)] match c {
'_' | '$' => true,
_ => false,
}matches!(c, '_' | '$')
2981 }
2982 AsmLabelKind::Binary => #[allow(non_exhaustive_omitted_patterns)] match c {
'0' | '1' => true,
_ => false,
}matches!(c, '0' | '1'),
2983 };
2984
2985 if !can_continue {
2986 break 'label_loop;
2989 }
2990 }
2991 }
2992
2993 spans.push((find_label_span(possible_label), label_kind));
2995 start_idx = idx + 1;
2996 }
2997 }
2998
2999 for (span, label_kind) in spans {
3000 let missing_precise_span = span.is_none();
3001 let span = span.unwrap_or(*template_span);
3002 match label_kind {
3003 AsmLabelKind::Named => {
3004 cx.emit_span_lint(
3005 NAMED_ASM_LABELS,
3006 span,
3007 InvalidAsmLabel::Named { missing_precise_span },
3008 );
3009 }
3010 AsmLabelKind::FormatArg => {
3011 cx.emit_span_lint(
3012 NAMED_ASM_LABELS,
3013 span,
3014 InvalidAsmLabel::FormatArg { missing_precise_span },
3015 );
3016 }
3017 AsmLabelKind::Binary
3019 if !options.contains(InlineAsmOptions::ATT_SYNTAX)
3020 && #[allow(non_exhaustive_omitted_patterns)] match cx.tcx.sess.asm_arch {
Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None => true,
_ => false,
}matches!(
3021 cx.tcx.sess.asm_arch,
3022 Some(InlineAsmArch::X86 | InlineAsmArch::X86_64) | None
3023 ) =>
3024 {
3025 cx.emit_span_lint(
3026 BINARY_ASM_LABELS,
3027 span,
3028 InvalidAsmLabel::Binary { missing_precise_span, span },
3029 )
3030 }
3031 AsmLabelKind::Binary => (),
3033 };
3034 }
3035 }
3036 }
3037 }
3038}
3039
3040#[doc = r" The `special_module_name` lint detects module"]
#[doc = r" declarations for files that have a special meaning."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" mod lib;"]
#[doc = r""]
#[doc = r" fn main() {"]
#[doc = r" lib::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" Cargo recognizes `lib.rs` and `main.rs` as the root of a"]
#[doc = r" library or binary crate, so declaring them as modules"]
#[doc = r" will lead to miscompilation of the crate unless configured"]
#[doc = r" explicitly."]
#[doc = r""]
#[doc = r" To access a library from a binary target within the same crate,"]
#[doc = r" use `your_crate_name::` as the path instead of `lib::`:"]
#[doc = r""]
#[doc = r" ```rust,compile_fail"]
#[doc = r" // bar/src/lib.rs"]
#[doc = r" fn run() {"]
#[doc = r" // ..."]
#[doc = r" }"]
#[doc = r""]
#[doc = r" // bar/src/main.rs"]
#[doc = r" fn main() {"]
#[doc = r" bar::run();"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" Binary targets cannot be used as libraries and so declaring"]
#[doc = r" one as a module is not allowed."]
pub static SPECIAL_MODULE_NAME: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "SPECIAL_MODULE_NAME",
default_level: ::rustc_lint_defs::Warn,
desc: "module declarations for files with a special meaning",
is_externally_loaded: false,
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
3041 pub SPECIAL_MODULE_NAME,
3081 Warn,
3082 "module declarations for files with a special meaning",
3083}
3084
3085pub struct SpecialModuleName;
#[automatically_derived]
impl ::core::marker::Copy for SpecialModuleName { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for SpecialModuleName { }
#[automatically_derived]
impl ::core::clone::Clone for SpecialModuleName {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for SpecialModuleName {
fn name(&self) -> &'static str { "SpecialModuleName" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SPECIAL_MODULE_NAME]))
}
}
impl SpecialModuleName {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[SPECIAL_MODULE_NAME]))
}
}declare_lint_pass!(SpecialModuleName => [SPECIAL_MODULE_NAME]);
3086
3087impl EarlyLintPass for SpecialModuleName {
3088 fn check_crate(&mut self, cx: &EarlyContext<'_>, krate: &ast::Crate) {
3089 for item in &krate.items {
3090 if let ast::ItemKind::Mod(
3091 _,
3092 ident,
3093 ast::ModKind::Unloaded | ast::ModKind::Loaded(_, ast::Inline::No { .. }, _),
3094 ) = item.kind
3095 {
3096 if item.attrs.iter().any(|a| a.has_name(sym::path)) {
3097 continue;
3098 }
3099
3100 match ident.name.as_str() {
3101 "lib" => cx.emit_span_lint(
3102 SPECIAL_MODULE_NAME,
3103 item.span,
3104 BuiltinSpecialModuleNameUsed::Lib,
3105 ),
3106 "main" => cx.emit_span_lint(
3107 SPECIAL_MODULE_NAME,
3108 item.span,
3109 BuiltinSpecialModuleNameUsed::Main,
3110 ),
3111 _ => continue,
3112 }
3113 }
3114 }
3115 }
3116}
3117
3118#[doc = r" The `internal_eq_trait_method_impls` lint detects manual"]
#[doc = r" implementations of `Eq::assert_receiver_is_total_eq`."]
#[doc = r""]
#[doc = r" ### Example"]
#[doc = r""]
#[doc = r" ```rust"]
#[doc = r" #[derive(PartialEq)]"]
#[doc = r" pub struct Foo;"]
#[doc = r""]
#[doc = r" impl Eq for Foo {"]
#[doc = r" fn assert_receiver_is_total_eq(&self) {}"]
#[doc = r" }"]
#[doc = r" ```"]
#[doc = r""]
#[doc = r" {{produces}}"]
#[doc = r""]
#[doc = r" ### Explanation"]
#[doc = r""]
#[doc = r" This method existed so that `#[derive(Eq)]` could check that all"]
#[doc = r" fields of a type implement `Eq`. Other users were never supposed"]
#[doc = r" to implement it and it was hidden from documentation."]
#[doc = r""]
#[doc = r" Unfortunately, it was not explicitly marked as unstable and some"]
#[doc =
r" people have now mistakenly assumed they had to implement this method."]
#[doc = r""]
#[doc =
r" As the method is never called by the standard library, you can safely"]
#[doc =
r" remove any implementations of the method and just write `impl Eq for Foo {}`."]
#[doc = r""]
#[doc = r" This is a [future-incompatible] lint to transition this to a hard"]
#[doc = r" error in the future. See [issue #152336] for more details."]
#[doc = r""]
#[doc = r" [issue #152336]: https://github.com/rust-lang/rust/issues/152336"]
pub static INTERNAL_EQ_TRAIT_METHOD_IMPLS: &::rustc_lint_defs::Lint =
&::rustc_lint_defs::Lint {
name: "INTERNAL_EQ_TRAIT_METHOD_IMPLS",
default_level: ::rustc_lint_defs::Warn,
desc: "manual implementation of the internal `Eq::assert_receiver_is_total_eq` method",
is_externally_loaded: false,
future_incompatible: Some(::rustc_lint_defs::FutureIncompatibleInfo {
reason: ::rustc_lint_defs::FutureIncompatibilityReason::FutureReleaseError(::rustc_lint_defs::ReleaseFcw {
issue_number: 152336,
}),
report_in_deps: false,
..::rustc_lint_defs::FutureIncompatibleInfo::default_fields_for_macro()
}),
..::rustc_lint_defs::Lint::default_fields_for_macro()
};declare_lint! {
3119 pub INTERNAL_EQ_TRAIT_METHOD_IMPLS,
3152 Warn,
3153 "manual implementation of the internal `Eq::assert_receiver_is_total_eq` method",
3154 @future_incompatible = FutureIncompatibleInfo {
3155 reason: fcw!(FutureReleaseError #152336),
3156 report_in_deps: false,
3157 };
3158}
3159
3160pub struct InternalEqTraitMethodImpls;
#[automatically_derived]
impl ::core::marker::Copy for InternalEqTraitMethodImpls { }
#[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for InternalEqTraitMethodImpls { }
#[automatically_derived]
impl ::core::clone::Clone for InternalEqTraitMethodImpls {
#[inline]
fn clone(&self) -> Self { *self }
}
impl ::rustc_lint_defs::LintPass for InternalEqTraitMethodImpls {
fn name(&self) -> &'static str { "InternalEqTraitMethodImpls" }
fn get_lints(&self) -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INTERNAL_EQ_TRAIT_METHOD_IMPLS]))
}
}
impl InternalEqTraitMethodImpls {
#[allow(unused)]
pub fn lint_vec() -> ::rustc_lint_defs::LintVec {
::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
[INTERNAL_EQ_TRAIT_METHOD_IMPLS]))
}
}declare_lint_pass!(InternalEqTraitMethodImpls => [INTERNAL_EQ_TRAIT_METHOD_IMPLS]);
3161
3162impl<'tcx> LateLintPass<'tcx> for InternalEqTraitMethodImpls {
3163 fn check_impl_item(&mut self, cx: &LateContext<'tcx>, item: &'tcx rustc_hir::ImplItem<'tcx>) {
3164 if let ImplItemImplKind::Trait { defaultness: _, trait_item_def_id: Ok(trait_item_def_id) } =
3165 item.impl_kind
3166 && cx.tcx.is_diagnostic_item(sym::assert_receiver_is_total_eq, trait_item_def_id)
3167 {
3168 cx.emit_span_lint(
3169 INTERNAL_EQ_TRAIT_METHOD_IMPLS,
3170 item.span,
3171 EqInternalMethodImplemented,
3172 );
3173 }
3174 }
3175}