Auto merge of #119002 - workingjubilee:rollup-dbfet7s, r=workingjubilee

Rollup of 5 pull requests

Successful merges:

 - #118396 (Collect lang items from AST, get rid of `GenericBound::LangItemTrait`)
 - #118727 (Don't pass lint back out of lint decorator)
 - #118956 (Make CStr documentation consistent ("nul" instead of "null"))
 - #118981 (Remove an unneeded allocation)
 - #118998 (Link to is_benchmark from the Ipv6Addr::is_global documentation)

r? `@ghost`
`@rustbot` modify labels: rollup
This commit is contained in:
bors 2023-12-15 22:09:47 +00:00
commit ca5c68a110
70 changed files with 564 additions and 572 deletions

View File

@ -2845,6 +2845,28 @@ impl Item {
pub fn span_with_attributes(&self) -> Span { pub fn span_with_attributes(&self) -> Span {
self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span)) self.attrs.iter().fold(self.span, |acc, attr| acc.to(attr.span))
} }
pub fn opt_generics(&self) -> Option<&Generics> {
match &self.kind {
ItemKind::ExternCrate(_)
| ItemKind::Use(_)
| ItemKind::Mod(_, _)
| ItemKind::ForeignMod(_)
| ItemKind::GlobalAsm(_)
| ItemKind::MacCall(_)
| ItemKind::MacroDef(_) => None,
ItemKind::Static(_) => None,
ItemKind::Const(i) => Some(&i.generics),
ItemKind::Fn(i) => Some(&i.generics),
ItemKind::TyAlias(i) => Some(&i.generics),
ItemKind::TraitAlias(generics, _)
| ItemKind::Enum(_, generics)
| ItemKind::Struct(_, generics)
| ItemKind::Union(_, generics) => Some(&generics),
ItemKind::Trait(i) => Some(&i.generics),
ItemKind::Impl(i) => Some(&i.generics),
}
}
} }
/// `extern` qualifier on a function item or function type. /// `extern` qualifier on a function item or function type.

View File

@ -453,6 +453,7 @@ pub fn lower_to_hir(tcx: TyCtxt<'_>, (): ()) -> hir::Crate<'_> {
tcx.ensure_with_value().output_filenames(()); tcx.ensure_with_value().output_filenames(());
tcx.ensure_with_value().early_lint_checks(()); tcx.ensure_with_value().early_lint_checks(());
tcx.ensure_with_value().debugger_visualizers(LOCAL_CRATE); tcx.ensure_with_value().debugger_visualizers(LOCAL_CRATE);
tcx.ensure_with_value().get_lang_items(());
let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal(); let (mut resolver, krate) = tcx.resolver_for_lowering(()).steal();
let ast_index = index_crate(&resolver.node_id_to_def_id, &krate); let ast_index = index_crate(&resolver.node_id_to_def_id, &krate);
@ -765,6 +766,28 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
self.resolver.get_import_res(id).present_items() self.resolver.get_import_res(id).present_items()
} }
fn make_lang_item_path(
&mut self,
lang_item: hir::LangItem,
span: Span,
args: Option<&'hir hir::GenericArgs<'hir>>,
) -> &'hir hir::Path<'hir> {
let def_id = self.tcx.require_lang_item(lang_item, Some(span));
let def_kind = self.tcx.def_kind(def_id);
let res = Res::Def(def_kind, def_id);
self.arena.alloc(hir::Path {
span,
res,
segments: self.arena.alloc_from_iter([hir::PathSegment {
ident: Ident::new(lang_item.name(), span),
hir_id: self.next_id(),
res,
args,
infer_args: false,
}]),
})
}
/// Reuses the span but adds information like the kind of the desugaring and features that are /// Reuses the span but adds information like the kind of the desugaring and features that are
/// allowed inside this span. /// allowed inside this span.
fn mark_span_with_reason( fn mark_span_with_reason(
@ -1976,18 +1999,27 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator), CoroutineKind::AsyncGen { .. } => (sym::Item, hir::LangItem::AsyncIterator),
}; };
let future_args = self.arena.alloc(hir::GenericArgs { let bound_args = self.arena.alloc(hir::GenericArgs {
args: &[], args: &[],
bindings: arena_vec![self; self.assoc_ty_binding(assoc_ty_name, opaque_ty_span, output_ty)], bindings: arena_vec![self; self.assoc_ty_binding(assoc_ty_name, opaque_ty_span, output_ty)],
parenthesized: hir::GenericArgsParentheses::No, parenthesized: hir::GenericArgsParentheses::No,
span_ext: DUMMY_SP, span_ext: DUMMY_SP,
}); });
hir::GenericBound::LangItemTrait( hir::GenericBound::Trait(
trait_lang_item, hir::PolyTraitRef {
opaque_ty_span, bound_generic_params: &[],
self.next_id(), trait_ref: hir::TraitRef {
future_args, path: self.make_lang_item_path(
trait_lang_item,
opaque_ty_span,
Some(bound_args),
),
hir_ref_id: self.next_id(),
},
span: opaque_ty_span,
},
hir::TraitBoundModifier::None,
) )
} }

View File

@ -788,28 +788,18 @@ impl<'tcx> MirBorrowckCtxt<'_, 'tcx> {
}; };
let opaque_ty = hir.item(id); let opaque_ty = hir.item(id);
if let hir::ItemKind::OpaqueTy(hir::OpaqueTy { if let hir::ItemKind::OpaqueTy(hir::OpaqueTy {
bounds: bounds: [hir::GenericBound::Trait(trait_ref, _)],
[
hir::GenericBound::LangItemTrait(
hir::LangItem::Future,
_,
_,
hir::GenericArgs {
bindings:
[
hir::TypeBinding {
ident: Ident { name: sym::Output, .. },
kind:
hir::TypeBindingKind::Equality { term: hir::Term::Ty(ty) },
..
},
],
..
},
),
],
.. ..
}) = opaque_ty.kind }) = opaque_ty.kind
&& let Some(segment) = trait_ref.trait_ref.path.segments.last()
&& let Some(args) = segment.args
&& let [
hir::TypeBinding {
ident: Ident { name: sym::Output, .. },
kind: hir::TypeBindingKind::Equality { term: hir::Term::Ty(ty) },
..
},
] = args.bindings
{ {
ty ty
} else { } else {

View File

@ -578,7 +578,9 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
hir_id, hir_id,
no_sanitize_span, no_sanitize_span,
"`no_sanitize` will have no effect after inlining", "`no_sanitize` will have no effect after inlining",
|lint| lint.span_note(inline_span, "inlining requested here"), |lint| {
lint.span_note(inline_span, "inlining requested here");
},
) )
} }
} }

View File

@ -435,8 +435,6 @@ pub enum TraitBoundModifier {
#[derive(Clone, Copy, Debug, HashStable_Generic)] #[derive(Clone, Copy, Debug, HashStable_Generic)]
pub enum GenericBound<'hir> { pub enum GenericBound<'hir> {
Trait(PolyTraitRef<'hir>, TraitBoundModifier), Trait(PolyTraitRef<'hir>, TraitBoundModifier),
// FIXME(davidtwco): Introduce `PolyTraitRef::LangItem`
LangItemTrait(LangItem, Span, HirId, &'hir GenericArgs<'hir>),
Outlives(&'hir Lifetime), Outlives(&'hir Lifetime),
} }
@ -451,7 +449,6 @@ impl GenericBound<'_> {
pub fn span(&self) -> Span { pub fn span(&self) -> Span {
match self { match self {
GenericBound::Trait(t, ..) => t.span, GenericBound::Trait(t, ..) => t.span,
GenericBound::LangItemTrait(_, span, ..) => *span,
GenericBound::Outlives(l) => l.ident.span, GenericBound::Outlives(l) => l.ident.span,
} }
} }

View File

@ -1075,10 +1075,6 @@ pub fn walk_param_bound<'v, V: Visitor<'v>>(visitor: &mut V, bound: &'v GenericB
GenericBound::Trait(ref typ, _modifier) => { GenericBound::Trait(ref typ, _modifier) => {
visitor.visit_poly_trait_ref(typ); visitor.visit_poly_trait_ref(typ);
} }
GenericBound::LangItemTrait(_, _span, hir_id, args) => {
visitor.visit_id(hir_id);
visitor.visit_generic_args(args);
}
GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime), GenericBound::Outlives(ref lifetime) => visitor.visit_lifetime(lifetime),
} }
} }

View File

@ -67,6 +67,42 @@ impl Display for Target {
} }
impl Target { impl Target {
pub fn is_associated_item(self) -> bool {
match self {
Target::AssocConst | Target::AssocTy | Target::Method(_) => true,
Target::ExternCrate
| Target::Use
| Target::Static
| Target::Const
| Target::Fn
| Target::Closure
| Target::Mod
| Target::ForeignMod
| Target::GlobalAsm
| Target::TyAlias
| Target::OpaqueTy
| Target::Enum
| Target::Variant
| Target::Struct
| Target::Field
| Target::Union
| Target::Trait
| Target::TraitAlias
| Target::Impl
| Target::Expression
| Target::Statement
| Target::Arm
| Target::ForeignFn
| Target::ForeignStatic
| Target::ForeignTy
| Target::GenericParam(_)
| Target::MacroDef
| Target::Param
| Target::PatField
| Target::ExprField => false,
}
}
pub fn from_item(item: &Item<'_>) -> Target { pub fn from_item(item: &Item<'_>) -> Target {
match item.kind { match item.kind {
ItemKind::ExternCrate(..) => Target::ExternCrate, ItemKind::ExternCrate(..) => Target::ExternCrate,

View File

@ -134,17 +134,6 @@ impl<'tcx> dyn AstConv<'tcx> + '_ {
only_self_bounds, only_self_bounds,
); );
} }
&hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
self.instantiate_lang_item_trait_ref(
lang_item,
span,
hir_id,
args,
param_ty,
bounds,
only_self_bounds,
);
}
hir::GenericBound::Outlives(lifetime) => { hir::GenericBound::Outlives(lifetime) => {
let region = self.ast_region_to_region(lifetime, None); let region = self.ast_region_to_region(lifetime, None);
bounds.push_region_bound( bounds.push_region_bound(

View File

@ -661,7 +661,7 @@ pub(crate) fn prohibit_explicit_late_bound_lifetimes(
args.args[0].hir_id(), args.args[0].hir_id(),
multispan, multispan,
msg, msg,
|lint| lint, |_| {},
); );
} }

View File

@ -122,7 +122,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
self.maybe_lint_blanket_trait_impl(self_ty, lint); self.maybe_lint_blanket_trait_impl(self_ty, lint);
lint
}, },
); );
} }

View File

@ -678,36 +678,57 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
) )
} }
fn instantiate_poly_trait_ref_inner( /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
/// a full trait reference. The resulting trait reference is returned. This may also generate
/// auxiliary bounds, which are added to `bounds`.
///
/// Example:
///
/// ```ignore (illustrative)
/// poly_trait_ref = Iterator<Item = u32>
/// self_ty = Foo
/// ```
///
/// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
///
/// **A note on binders:** against our usual convention, there is an implied binder around
/// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
/// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
/// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
/// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
/// however.
#[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
pub(crate) fn instantiate_poly_trait_ref(
&self, &self,
hir_id: hir::HirId, trait_ref: &hir::TraitRef<'_>,
span: Span, span: Span,
binding_span: Option<Span>,
constness: ty::BoundConstness, constness: ty::BoundConstness,
polarity: ty::ImplPolarity, polarity: ty::ImplPolarity,
self_ty: Ty<'tcx>,
bounds: &mut Bounds<'tcx>, bounds: &mut Bounds<'tcx>,
speculative: bool, speculative: bool,
trait_ref_span: Span,
trait_def_id: DefId,
trait_segment: &hir::PathSegment<'_>,
args: &GenericArgs<'_>,
infer_args: bool,
self_ty: Ty<'tcx>,
only_self_bounds: OnlySelfBounds, only_self_bounds: OnlySelfBounds,
) -> GenericArgCountResult { ) -> GenericArgCountResult {
let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
let trait_segment = trait_ref.path.segments.last().unwrap();
let args = trait_segment.args();
self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
let (generic_args, arg_count) = self.create_args_for_ast_path( let (generic_args, arg_count) = self.create_args_for_ast_path(
trait_ref_span, trait_ref.path.span,
trait_def_id, trait_def_id,
&[], &[],
trait_segment, trait_segment,
args, args,
infer_args, trait_segment.infer_args,
Some(self_ty), Some(self_ty),
constness, constness,
); );
let tcx = self.tcx(); let tcx = self.tcx();
let bound_vars = tcx.late_bound_vars(hir_id); let bound_vars = tcx.late_bound_vars(trait_ref.hir_ref_id);
debug!(?bound_vars); debug!(?bound_vars);
let assoc_bindings = self.create_assoc_bindings_for_generic_args(args); let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
@ -735,13 +756,13 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
// Specify type to assert that error was already reported in `Err` case. // Specify type to assert that error was already reported in `Err` case.
let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding( let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
hir_id, trait_ref.hir_ref_id,
poly_trait_ref, poly_trait_ref,
binding, binding,
bounds, bounds,
speculative, speculative,
&mut dup_bindings, &mut dup_bindings,
binding_span.unwrap_or(binding.span), binding.span,
constness, constness,
only_self_bounds, only_self_bounds,
polarity, polarity,
@ -752,102 +773,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
arg_count arg_count
} }
/// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
/// a full trait reference. The resulting trait reference is returned. This may also generate
/// auxiliary bounds, which are added to `bounds`.
///
/// Example:
///
/// ```ignore (illustrative)
/// poly_trait_ref = Iterator<Item = u32>
/// self_ty = Foo
/// ```
///
/// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
///
/// **A note on binders:** against our usual convention, there is an implied bounder around
/// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
/// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
/// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
/// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
/// however.
#[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
pub(crate) fn instantiate_poly_trait_ref(
&self,
trait_ref: &hir::TraitRef<'_>,
span: Span,
constness: ty::BoundConstness,
polarity: ty::ImplPolarity,
self_ty: Ty<'tcx>,
bounds: &mut Bounds<'tcx>,
speculative: bool,
only_self_bounds: OnlySelfBounds,
) -> GenericArgCountResult {
let hir_id = trait_ref.hir_ref_id;
let binding_span = None;
let trait_ref_span = trait_ref.path.span;
let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
let trait_segment = trait_ref.path.segments.last().unwrap();
let args = trait_segment.args();
let infer_args = trait_segment.infer_args;
self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
self.instantiate_poly_trait_ref_inner(
hir_id,
span,
binding_span,
constness,
polarity,
bounds,
speculative,
trait_ref_span,
trait_def_id,
trait_segment,
args,
infer_args,
self_ty,
only_self_bounds,
)
}
pub(crate) fn instantiate_lang_item_trait_ref(
&self,
lang_item: hir::LangItem,
span: Span,
hir_id: hir::HirId,
args: &GenericArgs<'_>,
self_ty: Ty<'tcx>,
bounds: &mut Bounds<'tcx>,
only_self_bounds: OnlySelfBounds,
) {
let binding_span = Some(span);
let constness = ty::BoundConstness::NotConst;
let speculative = false;
let trait_ref_span = span;
let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
let trait_segment = &hir::PathSegment::invalid();
let infer_args = false;
self.instantiate_poly_trait_ref_inner(
hir_id,
span,
binding_span,
constness,
ty::ImplPolarity::Positive,
bounds,
speculative,
trait_ref_span,
trait_def_id,
trait_segment,
args,
infer_args,
self_ty,
only_self_bounds,
);
}
fn ast_path_to_mono_trait_ref( fn ast_path_to_mono_trait_ref(
&self, &self,
span: Span, span: Span,
@ -1509,8 +1434,6 @@ impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident), format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
lint
}, },
); );
} }

View File

@ -51,7 +51,7 @@ pub fn check_abi(tcx: TyCtxt<'_>, hir_id: hir::HirId, span: Span, abi: Abi) {
hir_id, hir_id,
span, span,
"use of calling convention not supported on this target", "use of calling convention not supported on this target",
|lint| lint, |_| {},
); );
} }
} }
@ -190,7 +190,7 @@ fn check_static_inhabited(tcx: TyCtxt<'_>, def_id: LocalDefId) {
"static of uninhabited type", "static of uninhabited type",
|lint| { |lint| {
lint lint
.note("uninhabited statics cannot be initialized, and any access would be an immediate error") .note("uninhabited statics cannot be initialized, and any access would be an immediate error");
}, },
); );
} }
@ -1093,7 +1093,7 @@ pub(super) fn check_transparent<'tcx>(tcx: TyCtxt<'tcx>, adt: ty::AdtDef<'tcx>)
"this {descr} contains `{field_ty}`, which {note}, \ "this {descr} contains `{field_ty}`, which {note}, \
and makes it not a breaking change to become \ and makes it not a breaking change to become \
non-zero-sized in the future." non-zero-sized in the future."
)) ));
}, },
) )
} else { } else {

View File

@ -574,7 +574,6 @@ fn emit_implied_wf_lint<'tcx>(
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
lint
}, },
); );
} }

View File

@ -276,7 +276,6 @@ impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
lint.help(format!( lint.help(format!(
"or use `{{{idx}:{default_modifier}}}` to keep the default formatting of `{default_result}`", "or use `{{{idx}:{default_modifier}}}` to keep the default formatting of `{default_result}`",
)); ));
lint
}, },
); );
} }

View File

@ -45,7 +45,7 @@ fn check_unused_traits(tcx: TyCtxt<'_>, (): ()) {
item.hir_id(), item.hir_id(),
path.span, path.span,
msg, msg,
|lint| lint, |_| {},
); );
} }
} }

View File

@ -522,7 +522,7 @@ fn lint_auto_trait_impl<'tcx>(
format!( format!(
"try using the same sequence of generic parameters as the {self_descr} definition", "try using the same sequence of generic parameters as the {self_descr} definition",
), ),
) );
}, },
); );
} }

View File

@ -279,7 +279,7 @@ pub(super) fn generics_of(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::Generics {
param.hir_id, param.hir_id,
param.span, param.span,
TYPE_DEFAULT_NOT_ALLOWED, TYPE_DEFAULT_NOT_ALLOWED,
|lint| lint, |_| {},
); );
} }
Defaults::Deny => { Defaults::Deny => {

View File

@ -925,7 +925,7 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
"you can use the `'static` lifetime directly, in place of `{}`", "you can use the `'static` lifetime directly, in place of `{}`",
lifetime.ident, lifetime.ident,
); );
lint.help(help) lint.help(help);
}, },
); );
} }
@ -938,32 +938,6 @@ impl<'a, 'tcx> Visitor<'tcx> for BoundVarContext<'a, 'tcx> {
} }
} }
fn visit_param_bound(&mut self, bound: &'tcx hir::GenericBound<'tcx>) {
match bound {
hir::GenericBound::LangItemTrait(_, _, hir_id, _) => {
// FIXME(jackh726): This is pretty weird. `LangItemTrait` doesn't go
// through the regular poly trait ref code, so we don't get another
// chance to introduce a binder. For now, I'm keeping the existing logic
// of "if there isn't a Binder scope above us, add one", but I
// imagine there's a better way to go about this.
let (binders, scope_type) = self.poly_trait_ref_binder_info();
self.record_late_bound_vars(*hir_id, binders);
let scope = Scope::Binder {
hir_id: *hir_id,
bound_vars: FxIndexMap::default(),
s: self.scope,
scope_type,
where_bound_origin: None,
};
self.with(scope, |this| {
intravisit::walk_param_bound(this, bound);
});
}
_ => intravisit::walk_param_bound(self, bound),
}
}
fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) { fn visit_poly_trait_ref(&mut self, trait_ref: &'tcx hir::PolyTraitRef<'tcx>) {
self.visit_poly_trait_ref_inner(trait_ref, NonLifetimeBinderAllowed::Allow); self.visit_poly_trait_ref_inner(trait_ref, NonLifetimeBinderAllowed::Allow);
} }

View File

@ -2084,11 +2084,6 @@ impl<'a> State<'a> {
} }
self.print_poly_trait_ref(tref); self.print_poly_trait_ref(tref);
} }
GenericBound::LangItemTrait(lang_item, span, ..) => {
self.word("#[lang = \"");
self.print_ident(Ident::new(lang_item.name(), *span));
self.word("\"]");
}
GenericBound::Outlives(lt) => { GenericBound::Outlives(lt) => {
self.print_lifetime(lt); self.print_lifetime(lt);
} }

View File

@ -72,7 +72,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
orig_span, orig_span,
custom_note custom_note
.unwrap_or("any code following this expression is unreachable"), .unwrap_or("any code following this expression is unreachable"),
) );
}, },
) )
} }

View File

@ -825,9 +825,9 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
&& let hir::Node::Item(hir::Item { && let hir::Node::Item(hir::Item {
kind: hir::ItemKind::OpaqueTy(op_ty), .. kind: hir::ItemKind::OpaqueTy(op_ty), ..
}) = self.tcx.hir_node(item_id.hir_id()) }) = self.tcx.hir_node(item_id.hir_id())
&& let [ && let [hir::GenericBound::Trait(trait_ref, _)] = op_ty.bounds
hir::GenericBound::LangItemTrait(hir::LangItem::Future, _, _, generic_args), && let Some(hir::PathSegment { args: Some(generic_args), .. }) =
] = op_ty.bounds trait_ref.trait_ref.path.segments.last()
&& let hir::GenericArgs { bindings: [ty_binding], .. } = generic_args && let hir::GenericArgs { bindings: [ty_binding], .. } = generic_args
&& let hir::TypeBindingKind::Equality { term: hir::Term::Ty(term) } = && let hir::TypeBindingKind::Equality { term: hir::Term::Ty(term) } =
ty_binding.kind ty_binding.kind

View File

@ -122,8 +122,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
format!("disambiguate the method call with `({self_adjusted})`",), format!("disambiguate the method call with `({self_adjusted})`",),
); );
} }
lint
}, },
); );
} else { } else {
@ -187,8 +185,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
), ),
); );
} }
lint
}, },
); );
} }
@ -307,8 +303,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
format!("<{} as {}>::{}", self_ty_name, trait_name, method_name.name,), format!("<{} as {}>::{}", self_ty_name, trait_name, method_name.name,),
Applicability::MachineApplicable, Applicability::MachineApplicable,
); );
lint
}, },
); );
} }

View File

@ -445,7 +445,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
scope_expr_id, scope_expr_id,
span, span,
"type annotations needed", "type annotations needed",
|lint| lint, |_| {},
); );
} }
} else { } else {
@ -1427,8 +1427,6 @@ impl<'tcx> Pick<'tcx> {
)); ));
} }
} }
lint
}, },
); );
} }

View File

@ -1849,8 +1849,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
lint.note(format!( lint.note(format!(
"the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found", "the pattern is of type `{ty}` and the `non_exhaustive_omitted_patterns` attribute was found",
)); ));
lint
}); });
} }

View File

@ -912,8 +912,6 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
Applicability::HasPlaceholders Applicability::HasPlaceholders
); );
} }
lint
}, },
); );
} }

View File

@ -668,26 +668,16 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
( (
hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }), hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: last_bounds, .. }),
hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }), hir::ItemKind::OpaqueTy(hir::OpaqueTy { bounds: exp_bounds, .. }),
) if std::iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| { ) if std::iter::zip(*last_bounds, *exp_bounds).all(|(left, right)| match (
match (left, right) { left, right,
( ) {
hir::GenericBound::Trait(tl, ml), (hir::GenericBound::Trait(tl, ml), hir::GenericBound::Trait(tr, mr))
hir::GenericBound::Trait(tr, mr), if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
) if tl.trait_ref.trait_def_id() == tr.trait_ref.trait_def_id()
&& ml == mr => && ml == mr =>
{ {
true true
}
(
hir::GenericBound::LangItemTrait(langl, _, _, argsl),
hir::GenericBound::LangItemTrait(langr, _, _, argsr),
) if langl == langr => {
// FIXME: consider the bounds!
debug!("{:?} {:?}", argsl, argsr);
true
}
_ => false,
} }
_ => false,
}) => }) =>
{ {
StatementAsExpression::NeedsBoxing StatementAsExpression::NeedsBoxing

View File

@ -2800,7 +2800,7 @@ impl<'tcx> LateLintPass<'tcx> for NamedAsmLabels {
NAMED_ASM_LABELS, NAMED_ASM_LABELS,
Some(target_spans), Some(target_spans),
fluent::lint_builtin_asm_labels, fluent::lint_builtin_asm_labels,
|lint| lint, |_| {},
BuiltinLintDiagnostics::NamedAsmLabel( BuiltinLintDiagnostics::NamedAsmLabel(
"only local labels of the form `<number>:` should be used in inline asm" "only local labels of the form `<number>:` should be used in inline asm"
.to_string(), .to_string(),

View File

@ -520,9 +520,6 @@ pub trait LintContext {
/// Emit a lint at the appropriate level, with an optional associated span and an existing /// Emit a lint at the appropriate level, with an optional associated span and an existing
/// diagnostic. /// diagnostic.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed
/// explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
fn lookup_with_diagnostics( fn lookup_with_diagnostics(
@ -530,9 +527,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: Option<impl Into<MultiSpan>>, span: Option<impl Into<MultiSpan>>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
diagnostic: BuiltinLintDiagnostics, diagnostic: BuiltinLintDiagnostics,
) { ) {
// We first generate a blank diagnostic. // We first generate a blank diagnostic.
@ -986,8 +981,6 @@ pub trait LintContext {
// set the span in their `decorate` function (preferably using set_span). // set the span in their `decorate` function (preferably using set_span).
/// Emit a lint at the appropriate level, with an optional associated span. /// Emit a lint at the appropriate level, with an optional associated span.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
fn lookup<S: Into<MultiSpan>>( fn lookup<S: Into<MultiSpan>>(
@ -995,9 +988,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
); );
/// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`, /// Emit a lint at `span` from a lint struct (some type that implements `DecorateLint`,
@ -1008,13 +999,13 @@ pub trait LintContext {
span: S, span: S,
decorator: impl for<'a> DecorateLint<'a, ()>, decorator: impl for<'a> DecorateLint<'a, ()>,
) { ) {
self.lookup(lint, Some(span), decorator.msg(), |diag| decorator.decorate_lint(diag)); self.lookup(lint, Some(span), decorator.msg(), |diag| {
decorator.decorate_lint(diag);
});
} }
/// Emit a lint at the appropriate level, with an associated span. /// Emit a lint at the appropriate level, with an associated span.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
fn struct_span_lint<S: Into<MultiSpan>>( fn struct_span_lint<S: Into<MultiSpan>>(
@ -1022,9 +1013,7 @@ pub trait LintContext {
lint: &'static Lint, lint: &'static Lint,
span: S, span: S,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
self.lookup(lint, Some(span), msg, decorate); self.lookup(lint, Some(span), msg, decorate);
} }
@ -1033,23 +1022,19 @@ pub trait LintContext {
/// generated by `#[derive(LintDiagnostic)]`). /// generated by `#[derive(LintDiagnostic)]`).
fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) { fn emit_lint(&self, lint: &'static Lint, decorator: impl for<'a> DecorateLint<'a, ()>) {
self.lookup(lint, None as Option<Span>, decorator.msg(), |diag| { self.lookup(lint, None as Option<Span>, decorator.msg(), |diag| {
decorator.decorate_lint(diag) decorator.decorate_lint(diag);
}); });
} }
/// Emit a lint at the appropriate level, with no associated span. /// Emit a lint at the appropriate level, with no associated span.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
fn lint( fn lint(
&self, &self,
lint: &'static Lint, lint: &'static Lint,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
self.lookup(lint, None as Option<Span>, msg, decorate); self.lookup(lint, None as Option<Span>, msg, decorate);
} }
@ -1113,9 +1098,7 @@ impl<'tcx> LintContext for LateContext<'tcx> {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
let hir_id = self.last_node_with_lint_attrs; let hir_id = self.last_node_with_lint_attrs;
@ -1142,9 +1125,7 @@ impl LintContext for EarlyContext<'_> {
lint: &'static Lint, lint: &'static Lint,
span: Option<S>, span: Option<S>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
self.builder.struct_lint(lint, span.map(|s| s.into()), msg, decorate) self.builder.struct_lint(lint, span.map(|s| s.into()), msg, decorate)
} }

View File

@ -45,13 +45,7 @@ impl<'a, T: EarlyLintPass> EarlyContextAndPass<'a, T> {
fn inlined_check_id(&mut self, id: ast::NodeId) { fn inlined_check_id(&mut self, id: ast::NodeId) {
for early_lint in self.context.buffered.take(id) { for early_lint in self.context.buffered.take(id) {
let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint; let BufferedEarlyLint { span, msg, node_id: _, lint_id, diagnostic } = early_lint;
self.context.lookup_with_diagnostics( self.context.lookup_with_diagnostics(lint_id.lint, Some(span), msg, |_| {}, diagnostic);
lint_id.lint,
Some(span),
msg,
|lint| lint,
diagnostic,
);
} }
} }

View File

@ -1077,7 +1077,6 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
GateIssue::Language, GateIssue::Language,
lint_from_cli, lint_from_cli,
); );
lint
}, },
); );
return false; return false;
@ -1094,8 +1093,6 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
/// Used to emit a lint-related diagnostic based on the current state of /// Used to emit a lint-related diagnostic based on the current state of
/// this lint context. /// this lint context.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
@ -1104,9 +1101,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
lint: &'static Lint, lint: &'static Lint,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
let (level, src) = self.lint_level(lint); let (level, src) = self.lint_level(lint);
struct_lint_level(self.sess, lint, level, src, span, msg, decorate) struct_lint_level(self.sess, lint, level, src, span, msg, decorate)
@ -1121,7 +1116,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
) { ) {
let (level, src) = self.lint_level(lint); let (level, src) = self.lint_level(lint);
struct_lint_level(self.sess, lint, level, src, Some(span), decorate.msg(), |lint| { struct_lint_level(self.sess, lint, level, src, Some(span), decorate.msg(), |lint| {
decorate.decorate_lint(lint) decorate.decorate_lint(lint);
}); });
} }
@ -1129,7 +1124,7 @@ impl<'s, P: LintLevelsProvider> LintLevelsBuilder<'s, P> {
pub fn emit_lint(&self, lint: &'static Lint, decorate: impl for<'a> DecorateLint<'a, ()>) { pub fn emit_lint(&self, lint: &'static Lint, decorate: impl for<'a> DecorateLint<'a, ()>) {
let (level, src) = self.lint_level(lint); let (level, src) = self.lint_level(lint);
struct_lint_level(self.sess, lint, level, src, None, decorate.msg(), |lint| { struct_lint_level(self.sess, lint, level, src, None, decorate.msg(), |lint| {
decorate.decorate_lint(lint) decorate.decorate_lint(lint);
}); });
} }
} }

View File

@ -126,7 +126,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
lint.note(fluent::lint_more_info_note); lint.note(fluent::lint_more_info_note);
if !is_arg_inside_call(arg_span, span) { if !is_arg_inside_call(arg_span, span) {
// No clue where this argument is coming from. // No clue where this argument is coming from.
return lint; return;
} }
if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) { if arg_macro.is_some_and(|id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
// A case of `panic!(format!(..))`. // A case of `panic!(format!(..))`.
@ -207,7 +207,6 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
} }
} }
} }
lint
}); });
} }

View File

@ -253,29 +253,10 @@ pub fn explain_lint_level_source(
/// - [`TyCtxt::struct_lint_node`] /// - [`TyCtxt::struct_lint_node`]
/// - `LintContext::lookup` /// - `LintContext::lookup`
/// ///
/// ## `decorate` signature /// ## `decorate`
/// ///
/// The return value of `decorate` is ignored by this function. So what is the /// It is not intended to call `emit`/`cancel` on the `DiagnosticBuilder` passed
/// point of returning `&'b mut DiagnosticBuilder<'a, ()>`? /// in the `decorate` callback.
///
/// There are 2 reasons for this signature.
///
/// First of all, it prevents accidental use of `.emit()` -- it's clear that the
/// builder will be later used and shouldn't be emitted right away (this is
/// especially important because the old API expected you to call `.emit()` in
/// the closure).
///
/// Second of all, it makes the most common case of adding just a single label
/// /suggestion much nicer, since [`DiagnosticBuilder`] methods return
/// `&mut DiagnosticBuilder`, you can just chain methods, without needed
/// awkward `{ ...; }`:
/// ```ignore pseudo-code
/// struct_lint_level(
/// ...,
/// |lint| lint.span_label(sp, "lbl")
/// // ^^^^^^^^^^^^^^^^^^^^^ returns `&mut DiagnosticBuilder` by default
/// )
/// ```
#[track_caller] #[track_caller]
pub fn struct_lint_level( pub fn struct_lint_level(
sess: &Session, sess: &Session,
@ -284,9 +265,7 @@ pub fn struct_lint_level(
src: LintLevelSource, src: LintLevelSource,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
// Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to // Avoid codegen bloat from monomorphization by immediately doing dyn dispatch of `decorate` to
// the "real" work. // the "real" work.
@ -298,12 +277,7 @@ pub fn struct_lint_level(
src: LintLevelSource, src: LintLevelSource,
span: Option<MultiSpan>, span: Option<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: Box< decorate: Box<dyn '_ + for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>)>,
dyn '_
+ for<'a, 'b> FnOnce(
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
>,
) { ) {
// Check for future incompatibility lints and issue a stronger warning. // Check for future incompatibility lints and issue a stronger warning.
let future_incompatible = lint.future_incompatible; let future_incompatible = lint.future_incompatible;

View File

@ -223,7 +223,6 @@ fn late_report_deprecation(
let kind = tcx.def_descr(def_id); let kind = tcx.def_descr(def_id);
deprecation_suggestion(diag, kind, suggestion, method_span); deprecation_suggestion(diag, kind, suggestion, method_span);
} }
diag
}); });
} }
@ -587,7 +586,7 @@ impl<'tcx> TyCtxt<'tcx> {
unmarked: impl FnOnce(Span, DefId), unmarked: impl FnOnce(Span, DefId),
) -> bool { ) -> bool {
let soft_handler = |lint, span, msg: String| { let soft_handler = |lint, span, msg: String| {
self.struct_span_lint_hir(lint, id.unwrap_or(hir::CRATE_HIR_ID), span, msg, |lint| lint) self.struct_span_lint_hir(lint, id.unwrap_or(hir::CRATE_HIR_ID), span, msg, |_| {})
}; };
let eval_result = let eval_result =
self.eval_stability_allow_unstable(def_id, id, span, method_span, allow_unstable); self.eval_stability_allow_unstable(def_id, id, span, method_span, allow_unstable);

View File

@ -113,7 +113,7 @@ impl<'tcx> TyCtxt<'tcx> {
self.local_def_id_to_hir_id(local_def_id), self.local_def_id_to_hir_id(local_def_id),
self.def_span(ct.def), self.def_span(ct.def),
"cannot use constants which depend on generic parameters in types", "cannot use constants which depend on generic parameters in types",
|err| err, |_| {},
) )
} }
} }

View File

@ -2030,14 +2030,12 @@ impl<'tcx> TyCtxt<'tcx> {
let msg = decorator.msg(); let msg = decorator.msg();
let (level, src) = self.lint_level_at_node(lint, hir_id); let (level, src) = self.lint_level_at_node(lint, hir_id);
struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, |diag| { struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, |diag| {
decorator.decorate_lint(diag) decorator.decorate_lint(diag);
}) })
} }
/// Emit a lint at the appropriate level for a hir node, with an associated span. /// Emit a lint at the appropriate level for a hir node, with an associated span.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
@ -2047,9 +2045,7 @@ impl<'tcx> TyCtxt<'tcx> {
hir_id: HirId, hir_id: HirId,
span: impl Into<MultiSpan>, span: impl Into<MultiSpan>,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
let (level, src) = self.lint_level_at_node(lint, hir_id); let (level, src) = self.lint_level_at_node(lint, hir_id);
struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, decorate); struct_lint_level(self.sess, lint, level, src, Some(span.into()), msg, decorate);
@ -2064,13 +2060,13 @@ impl<'tcx> TyCtxt<'tcx> {
id: HirId, id: HirId,
decorator: impl for<'a> DecorateLint<'a, ()>, decorator: impl for<'a> DecorateLint<'a, ()>,
) { ) {
self.struct_lint_node(lint, id, decorator.msg(), |diag| decorator.decorate_lint(diag)) self.struct_lint_node(lint, id, decorator.msg(), |diag| {
decorator.decorate_lint(diag);
})
} }
/// Emit a lint at the appropriate level for a hir node. /// Emit a lint at the appropriate level for a hir node.
/// ///
/// Return value of the `decorate` closure is ignored, see [`struct_lint_level`] for a detailed explanation.
///
/// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature /// [`struct_lint_level`]: rustc_middle::lint::struct_lint_level#decorate-signature
#[rustc_lint_diagnostics] #[rustc_lint_diagnostics]
#[track_caller] #[track_caller]
@ -2079,9 +2075,7 @@ impl<'tcx> TyCtxt<'tcx> {
lint: &'static Lint, lint: &'static Lint,
id: HirId, id: HirId,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
decorate: impl for<'a, 'b> FnOnce( decorate: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
let (level, src) = self.lint_level_at_node(lint, id); let (level, src) = self.lint_level_at_node(lint, id);
struct_lint_level(self.sess, lint, level, src, None, msg, decorate); struct_lint_level(self.sess, lint, level, src, None, msg, decorate);

View File

@ -429,7 +429,7 @@ impl<'v> hir_visit::Visitor<'v> for StatCollector<'v> {
fn visit_param_bound(&mut self, b: &'v hir::GenericBound<'v>) { fn visit_param_bound(&mut self, b: &'v hir::GenericBound<'v>) {
record_variants!( record_variants!(
(self, b, b, Id::None, hir, GenericBound, GenericBound), (self, b, b, Id::None, hir, GenericBound, GenericBound),
[Trait, LangItemTrait, Outlives] [Trait, Outlives]
); );
hir_visit::walk_param_bound(self, b) hir_visit::walk_param_bound(self, b)
} }

View File

@ -7,18 +7,18 @@
//! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`. //! * Traits that represent operators; e.g., `Add`, `Sub`, `Index`.
//! * Functions called by the compiler itself. //! * Functions called by the compiler itself.
use crate::check_attr::target_from_impl_item;
use crate::errors::{ use crate::errors::{
DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem, DuplicateLangItem, IncorrectTarget, LangItemOnIncorrectTarget, UnknownLangItem,
}; };
use crate::weak_lang_items; use crate::weak_lang_items;
use rustc_hir as hir; use rustc_ast as ast;
use rustc_hir::def::DefKind; use rustc_ast::visit;
use rustc_data_structures::fx::FxHashMap;
use rustc_hir::def_id::{DefId, LocalDefId}; use rustc_hir::def_id::{DefId, LocalDefId};
use rustc_hir::lang_items::{extract, GenericRequirement}; use rustc_hir::lang_items::{extract, GenericRequirement};
use rustc_hir::{LangItem, LanguageItems, Target}; use rustc_hir::{LangItem, LanguageItems, MethodKind, Target};
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::{ResolverAstLowering, TyCtxt};
use rustc_session::cstore::ExternCrate; use rustc_session::cstore::ExternCrate;
use rustc_span::symbol::kw::Empty; use rustc_span::symbol::kw::Empty;
use rustc_span::Span; use rustc_span::Span;
@ -31,28 +31,55 @@ pub(crate) enum Duplicate {
CrateDepends, CrateDepends,
} }
struct LanguageItemCollector<'tcx> { struct LanguageItemCollector<'ast, 'tcx> {
items: LanguageItems, items: LanguageItems,
tcx: TyCtxt<'tcx>, tcx: TyCtxt<'tcx>,
resolver: &'ast ResolverAstLowering,
// FIXME(#118552): We should probably feed def_span eagerly on def-id creation
// so we can avoid constructing this map for local def-ids.
item_spans: FxHashMap<DefId, Span>,
parent_item: Option<&'ast ast::Item>,
} }
impl<'tcx> LanguageItemCollector<'tcx> { impl<'ast, 'tcx> LanguageItemCollector<'ast, 'tcx> {
fn new(tcx: TyCtxt<'tcx>) -> LanguageItemCollector<'tcx> { fn new(
LanguageItemCollector { tcx, items: LanguageItems::new() } tcx: TyCtxt<'tcx>,
resolver: &'ast ResolverAstLowering,
) -> LanguageItemCollector<'ast, 'tcx> {
LanguageItemCollector {
tcx,
resolver,
items: LanguageItems::new(),
item_spans: FxHashMap::default(),
parent_item: None,
}
} }
fn check_for_lang(&mut self, actual_target: Target, def_id: LocalDefId) { fn check_for_lang(
let attrs = self.tcx.hir().attrs(self.tcx.local_def_id_to_hir_id(def_id)); &mut self,
if let Some((name, span)) = extract(attrs) { actual_target: Target,
def_id: LocalDefId,
attrs: &'ast [ast::Attribute],
item_span: Span,
generics: Option<&'ast ast::Generics>,
) {
if let Some((name, attr_span)) = extract(attrs) {
match LangItem::from_name(name) { match LangItem::from_name(name) {
// Known lang item with attribute on correct target. // Known lang item with attribute on correct target.
Some(lang_item) if actual_target == lang_item.target() => { Some(lang_item) if actual_target == lang_item.target() => {
self.collect_item_extended(lang_item, def_id, span); self.collect_item_extended(
lang_item,
def_id,
item_span,
attr_span,
generics,
actual_target,
);
} }
// Known lang item with attribute on incorrect target. // Known lang item with attribute on incorrect target.
Some(lang_item) => { Some(lang_item) => {
self.tcx.sess.emit_err(LangItemOnIncorrectTarget { self.tcx.sess.emit_err(LangItemOnIncorrectTarget {
span, span: attr_span,
name, name,
expected_target: lang_item.target(), expected_target: lang_item.target(),
actual_target, actual_target,
@ -60,127 +87,131 @@ impl<'tcx> LanguageItemCollector<'tcx> {
} }
// Unknown lang item. // Unknown lang item.
_ => { _ => {
self.tcx.sess.emit_err(UnknownLangItem { span, name }); self.tcx.sess.emit_err(UnknownLangItem { span: attr_span, name });
} }
} }
} }
} }
fn collect_item(&mut self, lang_item: LangItem, item_def_id: DefId) { fn collect_item(&mut self, lang_item: LangItem, item_def_id: DefId, item_span: Option<Span>) {
// Check for duplicates. // Check for duplicates.
if let Some(original_def_id) = self.items.get(lang_item) { if let Some(original_def_id) = self.items.get(lang_item)
if original_def_id != item_def_id { && original_def_id != item_def_id
let local_span = self.tcx.hir().span_if_local(item_def_id); {
let lang_item_name = lang_item.name(); let lang_item_name = lang_item.name();
let crate_name = self.tcx.crate_name(item_def_id.krate); let crate_name = self.tcx.crate_name(item_def_id.krate);
let mut dependency_of = Empty; let mut dependency_of = Empty;
let is_local = item_def_id.is_local(); let is_local = item_def_id.is_local();
let path = if is_local { let path = if is_local {
String::new() String::new()
} else { } else {
self.tcx self.tcx
.crate_extern_paths(item_def_id.krate) .crate_extern_paths(item_def_id.krate)
.iter() .iter()
.map(|p| p.display().to_string()) .map(|p| p.display().to_string())
.collect::<Vec<_>>() .collect::<Vec<_>>()
.join(", ") .join(", ")
}; };
let first_defined_span = self.tcx.hir().span_if_local(original_def_id);
let mut orig_crate_name = Empty; let first_defined_span = self.item_spans.get(&original_def_id).copied();
let mut orig_dependency_of = Empty; let mut orig_crate_name = Empty;
let orig_is_local = original_def_id.is_local(); let mut orig_dependency_of = Empty;
let orig_path = if orig_is_local { let orig_is_local = original_def_id.is_local();
String::new() let orig_path = if orig_is_local {
} else { String::new()
self.tcx } else {
.crate_extern_paths(original_def_id.krate) self.tcx
.iter() .crate_extern_paths(original_def_id.krate)
.map(|p| p.display().to_string()) .iter()
.collect::<Vec<_>>() .map(|p| p.display().to_string())
.join(", ") .collect::<Vec<_>>()
}; .join(", ")
if first_defined_span.is_none() { };
orig_crate_name = self.tcx.crate_name(original_def_id.krate);
if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) = if first_defined_span.is_none() {
self.tcx.extern_crate(original_def_id) orig_crate_name = self.tcx.crate_name(original_def_id.krate);
{ if let Some(ExternCrate { dependency_of: inner_dependency_of, .. }) =
orig_dependency_of = self.tcx.crate_name(*inner_dependency_of); self.tcx.extern_crate(original_def_id)
} {
orig_dependency_of = self.tcx.crate_name(*inner_dependency_of);
} }
}
let duplicate = if local_span.is_some() { let duplicate = if item_span.is_some() {
Duplicate::Plain Duplicate::Plain
} else { } else {
match self.tcx.extern_crate(item_def_id) { match self.tcx.extern_crate(item_def_id) {
Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => { Some(ExternCrate { dependency_of: inner_dependency_of, .. }) => {
dependency_of = self.tcx.crate_name(*inner_dependency_of); dependency_of = self.tcx.crate_name(*inner_dependency_of);
Duplicate::CrateDepends Duplicate::CrateDepends
}
_ => Duplicate::Crate,
} }
}; _ => Duplicate::Crate,
}
};
self.tcx.sess.emit_err(DuplicateLangItem { self.tcx.sess.emit_err(DuplicateLangItem {
local_span, local_span: item_span,
lang_item_name, lang_item_name,
crate_name, crate_name,
dependency_of, dependency_of,
is_local, is_local,
path, path,
first_defined_span, first_defined_span,
orig_crate_name, orig_crate_name,
orig_dependency_of, orig_dependency_of,
orig_is_local, orig_is_local,
orig_path, orig_path,
duplicate, duplicate,
}); });
} else {
// Matched.
self.items.set(lang_item, item_def_id);
// Collect span for error later
if let Some(item_span) = item_span {
self.item_spans.insert(item_def_id, item_span);
} }
} }
// Matched.
self.items.set(lang_item, item_def_id);
} }
// Like collect_item() above, but also checks whether the lang item is declared // Like collect_item() above, but also checks whether the lang item is declared
// with the right number of generic arguments. // with the right number of generic arguments.
fn collect_item_extended(&mut self, lang_item: LangItem, item_def_id: LocalDefId, span: Span) { fn collect_item_extended(
&mut self,
lang_item: LangItem,
item_def_id: LocalDefId,
item_span: Span,
attr_span: Span,
generics: Option<&'ast ast::Generics>,
target: Target,
) {
let name = lang_item.name(); let name = lang_item.name();
// Now check whether the lang_item has the expected number of generic if let Some(generics) = generics {
// arguments. Generally speaking, binary and indexing operations have // Now check whether the lang_item has the expected number of generic
// one (for the RHS/index), unary operations have none, the closure // arguments. Generally speaking, binary and indexing operations have
// traits have one for the argument list, coroutines have one for the // one (for the RHS/index), unary operations have none, the closure
// resume argument, and ordering/equality relations have one for the RHS // traits have one for the argument list, coroutines have one for the
// Some other types like Box and various functions like drop_in_place // resume argument, and ordering/equality relations have one for the RHS
// have minimum requirements. // Some other types like Box and various functions like drop_in_place
// have minimum requirements.
if let hir::Node::Item(hir::Item { kind, span: item_span, .. }) = // FIXME: This still doesn't count, e.g., elided lifetimes and APITs.
self.tcx.hir_node_by_def_id(item_def_id) let mut actual_num = generics.params.len();
{ if target.is_associated_item() {
let (actual_num, generics_span) = match kind.generics() { actual_num += self
Some(generics) => ( .parent_item
generics .unwrap()
.params .opt_generics()
.iter() .map_or(0, |generics| generics.params.len());
.filter(|p| { }
!matches!(
p.kind,
hir::GenericParamKind::Const { is_host_effect: true, .. }
)
})
.count(),
generics.span,
),
None => (0, *item_span),
};
let mut at_least = false; let mut at_least = false;
let required = match lang_item.required_generics() { let required = match lang_item.required_generics() {
GenericRequirement::Exact(num) if num != actual_num => Some(num), GenericRequirement::Exact(num) if num != actual_num => Some(num),
GenericRequirement::Minimum(num) if actual_num < num => { GenericRequirement::Minimum(num) if actual_num < num => {
at_least = true; at_least = true;
Some(num)} Some(num)
, }
// If the number matches, or there is no requirement, handle it normally // If the number matches, or there is no requirement, handle it normally
_ => None, _ => None,
}; };
@ -190,10 +221,10 @@ impl<'tcx> LanguageItemCollector<'tcx> {
// item kind of the target is correct, the target is still wrong // item kind of the target is correct, the target is still wrong
// because of the wrong number of generic arguments. // because of the wrong number of generic arguments.
self.tcx.sess.emit_err(IncorrectTarget { self.tcx.sess.emit_err(IncorrectTarget {
span, span: attr_span,
generics_span, generics_span: generics.span,
name: name.as_str(), name: name.as_str(),
kind: kind.descr(), kind: target.name(),
num, num,
actual_num, actual_num,
at_least, at_least,
@ -204,58 +235,117 @@ impl<'tcx> LanguageItemCollector<'tcx> {
} }
} }
self.collect_item(lang_item, item_def_id.to_def_id()); self.collect_item(lang_item, item_def_id.to_def_id(), Some(item_span));
} }
} }
/// Traverses and collects all the lang items in all crates. /// Traverses and collects all the lang items in all crates.
fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems { fn get_lang_items(tcx: TyCtxt<'_>, (): ()) -> LanguageItems {
let resolver = tcx.resolver_for_lowering(()).borrow();
let (resolver, krate) = &*resolver;
// Initialize the collector. // Initialize the collector.
let mut collector = LanguageItemCollector::new(tcx); let mut collector = LanguageItemCollector::new(tcx, resolver);
// Collect lang items in other crates. // Collect lang items in other crates.
for &cnum in tcx.crates(()).iter() { for &cnum in tcx.crates(()).iter() {
for &(def_id, lang_item) in tcx.defined_lang_items(cnum).iter() { for &(def_id, lang_item) in tcx.defined_lang_items(cnum).iter() {
collector.collect_item(lang_item, def_id); collector.collect_item(lang_item, def_id, None);
} }
} }
// Collect lang items in this crate. // Collect lang items local to this crate.
let crate_items = tcx.hir_crate_items(()); visit::Visitor::visit_crate(&mut collector, krate);
for id in crate_items.items() {
collector
.check_for_lang(Target::from_def_kind(tcx.def_kind(id.owner_id)), id.owner_id.def_id);
if matches!(tcx.def_kind(id.owner_id), DefKind::Enum) {
let item = tcx.hir().item(id);
if let hir::ItemKind::Enum(def, ..) = &item.kind {
for variant in def.variants {
collector.check_for_lang(Target::Variant, variant.def_id);
}
}
}
}
// FIXME: avoid calling trait_item() when possible
for id in crate_items.trait_items() {
let item = tcx.hir().trait_item(id);
collector.check_for_lang(Target::from_trait_item(item), item.owner_id.def_id)
}
// FIXME: avoid calling impl_item() when possible
for id in crate_items.impl_items() {
let item = tcx.hir().impl_item(id);
collector.check_for_lang(target_from_impl_item(tcx, item), item.owner_id.def_id)
}
// Extract out the found lang items.
let LanguageItemCollector { mut items, .. } = collector;
// Find all required but not-yet-defined lang items. // Find all required but not-yet-defined lang items.
weak_lang_items::check_crate(tcx, &mut items); weak_lang_items::check_crate(tcx, &mut collector.items, krate);
items // Return all the lang items that were found.
collector.items
}
impl<'ast, 'tcx> visit::Visitor<'ast> for LanguageItemCollector<'ast, 'tcx> {
fn visit_item(&mut self, i: &'ast ast::Item) {
let target = match &i.kind {
ast::ItemKind::ExternCrate(_) => Target::ExternCrate,
ast::ItemKind::Use(_) => Target::Use,
ast::ItemKind::Static(_) => Target::Static,
ast::ItemKind::Const(_) => Target::Const,
ast::ItemKind::Fn(_) => Target::Fn,
ast::ItemKind::Mod(_, _) => Target::Mod,
ast::ItemKind::ForeignMod(_) => Target::ForeignFn,
ast::ItemKind::GlobalAsm(_) => Target::GlobalAsm,
ast::ItemKind::TyAlias(_) => Target::TyAlias,
ast::ItemKind::Enum(_, _) => Target::Enum,
ast::ItemKind::Struct(_, _) => Target::Struct,
ast::ItemKind::Union(_, _) => Target::Union,
ast::ItemKind::Trait(_) => Target::Trait,
ast::ItemKind::TraitAlias(_, _) => Target::TraitAlias,
ast::ItemKind::Impl(_) => Target::Impl,
ast::ItemKind::MacroDef(_) => Target::MacroDef,
ast::ItemKind::MacCall(_) => unreachable!("macros should have been expanded"),
};
self.check_for_lang(
target,
self.resolver.node_id_to_def_id[&i.id],
&i.attrs,
i.span,
i.opt_generics(),
);
let parent_item = self.parent_item.replace(i);
visit::walk_item(self, i);
self.parent_item = parent_item;
}
fn visit_enum_def(&mut self, enum_definition: &'ast ast::EnumDef) {
for variant in &enum_definition.variants {
self.check_for_lang(
Target::Variant,
self.resolver.node_id_to_def_id[&variant.id],
&variant.attrs,
variant.span,
None,
);
}
visit::walk_enum_def(self, enum_definition);
}
fn visit_assoc_item(&mut self, i: &'ast ast::AssocItem, ctxt: visit::AssocCtxt) {
let (target, generics) = match &i.kind {
ast::AssocItemKind::Fn(fun) => (
match &self.parent_item.unwrap().kind {
ast::ItemKind::Impl(i) => {
if i.of_trait.is_some() {
Target::Method(MethodKind::Trait { body: fun.body.is_some() })
} else {
Target::Method(MethodKind::Inherent)
}
}
ast::ItemKind::Trait(_) => {
Target::Method(MethodKind::Trait { body: fun.body.is_some() })
}
_ => unreachable!(),
},
&fun.generics,
),
ast::AssocItemKind::Const(ct) => (Target::AssocConst, &ct.generics),
ast::AssocItemKind::Type(ty) => (Target::AssocTy, &ty.generics),
ast::AssocItemKind::MacCall(_) => unreachable!("macros should have been expanded"),
};
self.check_for_lang(
target,
self.resolver.node_id_to_def_id[&i.id],
&i.attrs,
i.span,
Some(generics),
);
visit::walk_assoc_item(self, i, ctxt);
}
} }
pub fn provide(providers: &mut Providers) { pub fn provide(providers: &mut Providers) {

View File

@ -1,5 +1,7 @@
//! Validity checking for weak lang items //! Validity checking for weak lang items
use rustc_ast as ast;
use rustc_ast::visit;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_hir::lang_items::{self, LangItem}; use rustc_hir::lang_items::{self, LangItem};
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS; use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
@ -11,7 +13,7 @@ use crate::errors::{MissingLangItem, MissingPanicHandler, UnknownExternLangItem}
/// Checks the crate for usage of weak lang items, returning a vector of all the /// Checks the crate for usage of weak lang items, returning a vector of all the
/// language items required by this crate, but not defined yet. /// language items required by this crate, but not defined yet.
pub fn check_crate(tcx: TyCtxt<'_>, items: &mut lang_items::LanguageItems) { pub fn check_crate(tcx: TyCtxt<'_>, items: &mut lang_items::LanguageItems, krate: &ast::Crate) {
// These are never called by user code, they're generated by the compiler. // These are never called by user code, they're generated by the compiler.
// They will never implicitly be added to the `missing` array unless we do // They will never implicitly be added to the `missing` array unless we do
// so here. // so here.
@ -22,24 +24,30 @@ pub fn check_crate(tcx: TyCtxt<'_>, items: &mut lang_items::LanguageItems) {
items.missing.push(LangItem::EhCatchTypeinfo); items.missing.push(LangItem::EhCatchTypeinfo);
} }
let crate_items = tcx.hir_crate_items(()); visit::Visitor::visit_crate(&mut WeakLangItemVisitor { tcx, items }, krate);
for id in crate_items.foreign_items() {
let attrs = tcx.hir().attrs(id.hir_id()); verify(tcx, items);
if let Some((lang_item, _)) = lang_items::extract(attrs) { }
struct WeakLangItemVisitor<'a, 'tcx> {
tcx: TyCtxt<'tcx>,
items: &'a mut lang_items::LanguageItems,
}
impl<'ast> visit::Visitor<'ast> for WeakLangItemVisitor<'_, '_> {
fn visit_foreign_item(&mut self, i: &'ast ast::ForeignItem) {
if let Some((lang_item, _)) = lang_items::extract(&i.attrs) {
if let Some(item) = LangItem::from_name(lang_item) if let Some(item) = LangItem::from_name(lang_item)
&& item.is_weak() && item.is_weak()
{ {
if items.get(item).is_none() { if self.items.get(item).is_none() {
items.missing.push(item); self.items.missing.push(item);
} }
} else { } else {
let span = tcx.def_span(id.owner_id); self.tcx.sess.emit_err(UnknownExternLangItem { span: i.span, lang_item });
tcx.sess.emit_err(UnknownExternLangItem { span, lang_item });
} }
} }
} }
verify(tcx, items);
} }
fn verify(tcx: TyCtxt<'_>, items: &lang_items::LanguageItems) { fn verify(tcx: TyCtxt<'_>, items: &lang_items::LanguageItems) {

View File

@ -273,7 +273,6 @@ fn overlap<'tcx>(
causing the impls to overlap", causing the impls to overlap",
infcx.resolve_vars_if_possible(failing_obligation.predicate) infcx.resolve_vars_if_possible(failing_obligation.predicate)
)); ));
lint
}, },
); );
} }

View File

@ -4665,7 +4665,7 @@ pub trait NextTypeParamName {
impl NextTypeParamName for &[hir::GenericParam<'_>] { impl NextTypeParamName for &[hir::GenericParam<'_>] {
fn next_type_param_name(&self, name: Option<&str>) -> String { fn next_type_param_name(&self, name: Option<&str>) -> String {
// This is the list of possible parameter names that we might suggest. // This is the list of possible parameter names that we might suggest.
let name = name.and_then(|n| n.chars().next()).map(|c| c.to_string().to_uppercase()); let name = name.and_then(|n| n.chars().next()).map(|c| c.to_uppercase().to_string());
let name = name.as_deref(); let name = name.as_deref();
let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"]; let possible_names = [name.unwrap_or("T"), "T", "U", "V", "X", "Y", "Z", "A", "B", "C"];
let used_names = self let used_names = self
@ -4783,8 +4783,14 @@ pub fn suggest_desugaring_async_fn_to_impl_future_in_trait<'tcx>(
}; };
let future = tcx.hir_node_by_def_id(opaque_def_id).expect_item().expect_opaque_ty(); let future = tcx.hir_node_by_def_id(opaque_def_id).expect_item().expect_opaque_ty();
let Some(hir::GenericBound::LangItemTrait(_, _, _, generics)) = future.bounds.get(0) else { let [hir::GenericBound::Trait(trait_ref, _)] = future.bounds else {
// `async fn` should always lower to a lang item bound... but don't ICE. // `async fn` should always lower to a single bound... but don't ICE.
return None;
};
let Some(hir::PathSegment { args: Some(generics), .. }) =
trait_ref.trait_ref.path.segments.last()
else {
// desugaring to a single path segment for `Future<...>`.
return None; return None;
}; };
let Some(hir::TypeBindingKind::Equality { term: hir::Term::Ty(future_output_ty) }) = let Some(hir::TypeBindingKind::Equality { term: hir::Term::Ty(future_output_ty) }) =

View File

@ -194,7 +194,6 @@ fn lint_object_unsafe_trait(
// Only provide the help if its a local trait, otherwise it's not // Only provide the help if its a local trait, otherwise it's not
violation.solution().add_to(err); violation.solution().add_to(err);
} }
err
}, },
); );
} }

View File

@ -450,7 +450,6 @@ fn report_conflicting_impls<'tcx>(
msg, msg,
|err| { |err| {
decorate(tcx, &overlap, impl_span, err); decorate(tcx, &overlap, impl_span, err);
err
}, },
); );
} }

View File

@ -421,7 +421,7 @@ impl CString {
/// Failure to call [`CString::from_raw`] will lead to a memory leak. /// Failure to call [`CString::from_raw`] will lead to a memory leak.
/// ///
/// The C side must **not** modify the length of the string (by writing a /// The C side must **not** modify the length of the string (by writing a
/// `null` somewhere inside the string or removing the final one) before /// nul byte somewhere inside the string or removing the final one) before
/// it makes it back into Rust using [`CString::from_raw`]. See the safety section /// it makes it back into Rust using [`CString::from_raw`]. See the safety section
/// in [`CString::from_raw`]. /// in [`CString::from_raw`].
/// ///
@ -797,7 +797,7 @@ impl From<Box<CStr>> for CString {
#[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")] #[stable(feature = "cstring_from_vec_of_nonzerou8", since = "1.43.0")]
impl From<Vec<NonZeroU8>> for CString { impl From<Vec<NonZeroU8>> for CString {
/// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without /// Converts a <code>[Vec]<[NonZeroU8]></code> into a [`CString`] without
/// copying nor checking for inner null bytes. /// copying nor checking for inner nul bytes.
#[inline] #[inline]
fn from(v: Vec<NonZeroU8>) -> CString { fn from(v: Vec<NonZeroU8>) -> CString {
unsafe { unsafe {
@ -809,7 +809,7 @@ impl From<Vec<NonZeroU8>> for CString {
let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v); let (ptr, len, cap): (*mut NonZeroU8, _, _) = Vec::into_raw_parts(v);
Vec::from_raw_parts(ptr.cast::<u8>(), len, cap) Vec::from_raw_parts(ptr.cast::<u8>(), len, cap)
}; };
// SAFETY: `v` cannot contain null bytes, given the type-level // SAFETY: `v` cannot contain nul bytes, given the type-level
// invariant of `NonZeroU8`. // invariant of `NonZeroU8`.
Self::_from_vec_unchecked(v) Self::_from_vec_unchecked(v)
} }

View File

@ -205,7 +205,7 @@ impl CStr {
/// * The memory pointed to by `ptr` must contain a valid nul terminator at the /// * The memory pointed to by `ptr` must contain a valid nul terminator at the
/// end of the string. /// end of the string.
/// ///
/// * `ptr` must be [valid] for reads of bytes up to and including the null terminator. /// * `ptr` must be [valid] for reads of bytes up to and including the nul terminator.
/// This means in particular: /// This means in particular:
/// ///
/// * The entire memory range of this `CStr` must be contained within a single allocated object! /// * The entire memory range of this `CStr` must be contained within a single allocated object!
@ -415,7 +415,7 @@ impl CStr {
let mut i = bytes.len().saturating_sub(1); let mut i = bytes.len().saturating_sub(1);
assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated"); assert!(!bytes.is_empty() && bytes[i] == 0, "input was not nul-terminated");
// Ending null byte exists, skip to the rest. // Ending nul byte exists, skip to the rest.
while i != 0 { while i != 0 {
i -= 1; i -= 1;
let byte = bytes[i]; let byte = bytes[i];

View File

@ -1437,7 +1437,7 @@ impl Ipv6Addr {
/// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified)) /// - The [unspecified address] ([`is_unspecified`](Ipv6Addr::is_unspecified))
/// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback)) /// - The [loopback address] ([`is_loopback`](Ipv6Addr::is_loopback))
/// - IPv4-mapped addresses /// - IPv4-mapped addresses
/// - Addresses reserved for benchmarking /// - Addresses reserved for benchmarking ([`is_benchmarking`](Ipv6Addr::is_benchmarking))
/// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation)) /// - Addresses reserved for documentation ([`is_documentation`](Ipv6Addr::is_documentation))
/// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local)) /// - Unique local addresses ([`is_unique_local`](Ipv6Addr::is_unique_local))
/// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local)) /// - Unicast addresses with link-local scope ([`is_unicast_link_local`](Ipv6Addr::is_unicast_link_local))

View File

@ -588,7 +588,7 @@ pub fn panicking() -> bool {
} }
/// Entry point of panics from the core crate (`panic_impl` lang item). /// Entry point of panics from the core crate (`panic_impl` lang item).
#[cfg(not(test))] #[cfg(not(any(test, doctest)))]
#[panic_handler] #[panic_handler]
pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! { pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
struct FormatStringPayload<'a> { struct FormatStringPayload<'a> {
@ -669,7 +669,7 @@ pub fn begin_panic_handler(info: &PanicInfo<'_>) -> ! {
/// panic!() and assert!(). In particular, this is the only entry point that supports /// panic!() and assert!(). In particular, this is the only entry point that supports
/// arbitrary payloads, not just format strings. /// arbitrary payloads, not just format strings.
#[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")] #[unstable(feature = "libstd_sys_internals", reason = "used by the panic! macro", issue = "none")]
#[cfg_attr(not(test), lang = "begin_panic")] #[cfg_attr(not(any(test, doctest)), lang = "begin_panic")]
// lang item for CTFE panic support // lang item for CTFE panic support
// never inline unless panic_immediate_abort to avoid code // never inline unless panic_immediate_abort to avoid code
// bloat at the call sites as much as possible // bloat at the call sites as much as possible

View File

@ -2311,7 +2311,7 @@ pub fn id() -> u32 {
/// of the `main` function, this trait is likely to be available only on /// of the `main` function, this trait is likely to be available only on
/// standard library's runtime for convenience. Other runtimes are not required /// standard library's runtime for convenience. Other runtimes are not required
/// to provide similar functionality. /// to provide similar functionality.
#[cfg_attr(not(test), lang = "termination")] #[cfg_attr(not(any(test, doctest)), lang = "termination")]
#[stable(feature = "termination_trait_lib", since = "1.61.0")] #[stable(feature = "termination_trait_lib", since = "1.61.0")]
#[rustc_on_unimplemented(on( #[rustc_on_unimplemented(on(
cause = "MainFunctionType", cause = "MainFunctionType",

View File

@ -154,7 +154,7 @@ fn lang_start_internal(
ret_code ret_code
} }
#[cfg(not(test))] #[cfg(not(any(test, doctest)))]
#[lang = "start"] #[lang = "start"]
fn lang_start<T: crate::process::Termination + 'static>( fn lang_start<T: crate::process::Termination + 'static>(
main: fn() -> T, main: fn() -> T,

View File

@ -12,7 +12,7 @@
mod dwarf; mod dwarf;
#[cfg(not(test))] #[cfg(not(any(test, doctest)))]
cfg_if::cfg_if! { cfg_if::cfg_if! {
if #[cfg(target_os = "emscripten")] { if #[cfg(target_os = "emscripten")] {
mod emcc; mod emcc;

View File

@ -184,22 +184,6 @@ fn clean_generic_bound<'tcx>(
) -> Option<GenericBound> { ) -> Option<GenericBound> {
Some(match *bound { Some(match *bound {
hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)), hir::GenericBound::Outlives(lt) => GenericBound::Outlives(clean_lifetime(lt, cx)),
hir::GenericBound::LangItemTrait(lang_item, span, _, generic_args) => {
let def_id = cx.tcx.require_lang_item(lang_item, Some(span));
let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(cx.tcx, def_id));
let generic_args = clean_generic_args(generic_args, cx);
let GenericArgs::AngleBracketed { bindings, .. } = generic_args else {
bug!("clean: parenthesized `GenericBound::LangItemTrait`");
};
let trait_ = clean_trait_ref_with_bindings(cx, trait_ref, bindings);
GenericBound::TraitBound(
PolyTrait { trait_, generic_params: vec![] },
hir::TraitBoundModifier::None,
)
}
hir::GenericBound::Trait(ref t, modifier) => { hir::GenericBound::Trait(ref t, modifier) => {
// `T: ~const Destruct` is hidden because `T: Destruct` is a no-op. // `T: ~const Destruct` is hidden because `T: Destruct` is a no-op.
if modifier == hir::TraitBoundModifier::MaybeConst if modifier == hir::TraitBoundModifier::MaybeConst

View File

@ -380,7 +380,9 @@ pub(crate) fn run_global_ctxt(
crate::lint::MISSING_CRATE_LEVEL_DOCS, crate::lint::MISSING_CRATE_LEVEL_DOCS,
DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(), DocContext::as_local_hir_id(tcx, krate.module.item_id).unwrap(),
"no documentation found for this crate's top-level module", "no documentation found for this crate's top-level module",
|lint| lint.help(help), |lint| {
lint.help(help);
},
); );
} }

View File

@ -835,7 +835,7 @@ impl<'tcx> ExtraInfo<'tcx> {
self.tcx.local_def_id_to_hir_id(def_id), self.tcx.local_def_id_to_hir_id(def_id),
self.sp, self.sp,
msg, msg,
|l| l, |_| {},
); );
} }
} }
@ -843,9 +843,7 @@ impl<'tcx> ExtraInfo<'tcx> {
fn error_invalid_codeblock_attr_with_help( fn error_invalid_codeblock_attr_with_help(
&self, &self,
msg: impl Into<DiagnosticMessage>, msg: impl Into<DiagnosticMessage>,
f: impl for<'a, 'b> FnOnce( f: impl for<'a, 'b> FnOnce(&'b mut DiagnosticBuilder<'a, ()>),
&'b mut DiagnosticBuilder<'a, ()>,
) -> &'b mut DiagnosticBuilder<'a, ()>,
) { ) {
if let Some(def_id) = self.def_id.as_local() { if let Some(def_id) = self.def_id.as_local() {
self.tcx.struct_span_lint_hir( self.tcx.struct_span_lint_hir(
@ -1296,7 +1294,7 @@ impl LangString {
lint.help(format!( lint.help(format!(
"there is an attribute with a similar name: `edition{}`", "there is an attribute with a similar name: `edition{}`",
&x[4..], &x[4..],
)) ));
}, },
); );
} }
@ -1350,7 +1348,7 @@ impl LangString {
lint.help(format!( lint.help(format!(
"there is an attribute with a similar name: `{flag}`" "there is an attribute with a similar name: `{flag}`"
)) ))
.help(help) .help(help);
}, },
); );
} }

View File

@ -131,7 +131,7 @@ pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item
hir_id, hir_id,
sp, sp,
"missing code example in this documentation", "missing code example in this documentation",
|lint| lint, |_| {},
); );
} }
} else if tests.found_tests > 0 } else if tests.found_tests > 0
@ -142,7 +142,7 @@ pub(crate) fn look_for_tests<'tcx>(cx: &DocContext<'tcx>, dox: &str, item: &Item
hir_id, hir_id,
item.attr_span(cx.tcx), item.attr_span(cx.tcx),
"documentation test in private item", "documentation test in private item",
|lint| lint, |_| {},
); );
} }
} }

View File

@ -1755,8 +1755,6 @@ fn report_diagnostic(
} }
decorate(lint, span, link_range); decorate(lint, span, link_range);
lint
}); });
} }

View File

@ -31,7 +31,7 @@ pub(super) fn visit_item(cx: &DocContext<'_>, item: &Item) {
"use an automatic link instead", "use an automatic link instead",
format!("<{url}>"), format!("<{url}>"),
Applicability::MachineApplicable, Applicability::MachineApplicable,
) );
}); });
}; };

View File

@ -131,8 +131,6 @@ fn check_rust_syntax(
for message in buffer.messages.iter() { for message in buffer.messages.iter() {
lint.note(message.clone()); lint.note(message.clone());
} }
lint
}); });
} }

View File

@ -89,7 +89,7 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) {
if (generics_start > 0 && dox.as_bytes()[generics_start - 1] == b'<') if (generics_start > 0 && dox.as_bytes()[generics_start - 1] == b'<')
|| (generics_end < dox.len() && dox.as_bytes()[generics_end] == b'>') || (generics_end < dox.len() && dox.as_bytes()[generics_end] == b'>')
{ {
return lint; return;
} }
// multipart form is chosen here because ``Vec<i32>`` would be confusing. // multipart form is chosen here because ``Vec<i32>`` would be confusing.
lint.multipart_suggestion( lint.multipart_suggestion(
@ -101,8 +101,6 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) {
Applicability::MaybeIncorrect, Applicability::MaybeIncorrect,
); );
} }
lint
}); });
}; };

View File

@ -181,8 +181,6 @@ fn check_inline_or_reference_unknown_redundancy(
.span_label(display_span, "because label contains path that resolves to same destination") .span_label(display_span, "because label contains path that resolves to same destination")
.note("when a link's destination is not specified,\nthe label is used to resolve intra-doc links") .note("when a link's destination is not specified,\nthe label is used to resolve intra-doc links")
.span_suggestion_with_style(link_span, "remove explicit link target", format!("[{}]", link_data.display_link), Applicability::MaybeIncorrect, SuggestionStyle::ShowAlways); .span_suggestion_with_style(link_span, "remove explicit link target", format!("[{}]", link_data.display_link), Applicability::MaybeIncorrect, SuggestionStyle::ShowAlways);
lint
}); });
} }
@ -234,8 +232,6 @@ fn check_reference_redundancy(
.span_note(def_span, "referenced explicit link target defined here") .span_note(def_span, "referenced explicit link target defined here")
.note("when a link's destination is not specified,\nthe label is used to resolve intra-doc links") .note("when a link's destination is not specified,\nthe label is used to resolve intra-doc links")
.span_suggestion_with_style(link_span, "remove explicit link target", format!("[{}]", link_data.display_link), Applicability::MaybeIncorrect, SuggestionStyle::ShowAlways); .span_suggestion_with_style(link_span, "remove explicit link target", format!("[{}]", link_data.display_link), Applicability::MaybeIncorrect, SuggestionStyle::ShowAlways);
lint
}); });
} }

View File

@ -111,8 +111,6 @@ pub(crate) fn visit_item(cx: &DocContext<'_>, item: &Item) {
} }
suggest_insertion(cx, item, &dox, lint, backtick_index, '\\', "if you meant to use a literal backtick, escape it"); suggest_insertion(cx, item, &dox, lint, backtick_index, '\\', "if you meant to use a literal backtick, escape it");
lint
}); });
} }
Event::Code(_) => { Event::Code(_) => {

View File

@ -8,8 +8,8 @@ use rustc_hir::def::Res;
use rustc_hir::def_id::{DefId, DefIdSet}; use rustc_hir::def_id::{DefId, DefIdSet};
use rustc_hir::{ use rustc_hir::{
AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind, AssocItemKind, BinOpKind, Expr, ExprKind, FnRetTy, GenericArg, GenericBound, ImplItem, ImplItemKind,
ImplicitSelfKind, Item, ItemKind, LangItem, Mutability, Node, PatKind, PathSegment, PrimTy, QPath, TraitItemRef, ImplicitSelfKind, Item, ItemKind, Mutability, Node, PatKind, PathSegment, PrimTy, QPath, TraitItemRef,
TyKind, TypeBindingKind, TyKind, TypeBindingKind, OpaqueTyOrigin,
}; };
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{self, AssocKind, FnSig, Ty}; use rustc_middle::ty::{self, AssocKind, FnSig, Ty};
@ -289,8 +289,10 @@ fn extract_future_output<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> Option<&
kind: ItemKind::OpaqueTy(opaque), kind: ItemKind::OpaqueTy(opaque),
.. ..
} = item } = item
&& opaque.bounds.len() == 1 && let OpaqueTyOrigin::AsyncFn(_) = opaque.origin
&& let GenericBound::LangItemTrait(LangItem::Future, _, _, generic_args) = &opaque.bounds[0] && let [GenericBound::Trait(trait_ref, _)] = &opaque.bounds
&& let Some(segment) = trait_ref.trait_ref.path.segments.last()
&& let Some(generic_args) = segment.args
&& generic_args.bindings.len() == 1 && generic_args.bindings.len() == 1
&& let TypeBindingKind::Equality { && let TypeBindingKind::Equality {
term: term:

View File

@ -49,7 +49,6 @@ pub fn span_lint<T: LintContext>(cx: &T, lint: &'static Lint, sp: impl Into<Mult
#[expect(clippy::disallowed_methods)] #[expect(clippy::disallowed_methods)]
cx.struct_span_lint(lint, sp, msg.to_string(), |diag| { cx.struct_span_lint(lint, sp, msg.to_string(), |diag| {
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }
@ -90,7 +89,6 @@ pub fn span_lint_and_help<T: LintContext>(
diag.help(help.to_string()); diag.help(help.to_string());
} }
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }
@ -134,7 +132,6 @@ pub fn span_lint_and_note<T: LintContext>(
diag.note(note); diag.note(note);
} }
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }
@ -152,7 +149,6 @@ where
cx.struct_span_lint(lint, sp, msg.to_string(), |diag| { cx.struct_span_lint(lint, sp, msg.to_string(), |diag| {
f(diag); f(diag);
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }
@ -160,7 +156,6 @@ pub fn span_lint_hir(cx: &LateContext<'_>, lint: &'static Lint, hir_id: HirId, s
#[expect(clippy::disallowed_methods)] #[expect(clippy::disallowed_methods)]
cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| { cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| {
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }
@ -176,7 +171,6 @@ pub fn span_lint_hir_and_then(
cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| { cx.tcx.struct_span_lint_hir(lint, hir_id, sp, msg.to_string(), |diag| {
f(diag); f(diag);
docs_link(diag, lint); docs_link(diag, lint);
diag
}); });
} }

View File

@ -1,8 +1,11 @@
error[E0152]: found duplicate lang item `panic_impl` error[E0152]: found duplicate lang item `panic_impl`
--> $DIR/duplicate_entry_error.rs:11:1 --> $DIR/duplicate_entry_error.rs:11:1
| |
LL | fn panic_impl(info: &PanicInfo) -> ! { LL | / fn panic_impl(info: &PanicInfo) -> ! {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | |
LL | | loop {}
LL | | }
| |_^
| |
= note: the lang item is first defined in crate `std` (which `duplicate_entry_error` depends on) = note: the lang item is first defined in crate `std` (which `duplicate_entry_error` depends on)
= note: first definition in `std` loaded from SYSROOT/libstd-*.rlib = note: first definition in `std` loaded from SYSROOT/libstd-*.rlib

View File

@ -2,7 +2,7 @@ error[E0152]: found duplicate lang item `owned_box`
--> $DIR/E0152.rs:5:1 --> $DIR/E0152.rs:5:1
| |
LL | struct Foo<T>(T); LL | struct Foo<T>(T);
| ^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^
| |
= note: the lang item is first defined in crate `alloc` (which `std` depends on) = note: the lang item is first defined in crate `alloc` (which `std` depends on)
= note: first definition in `alloc` loaded from SYSROOT/liballoc-*.rlib = note: first definition in `alloc` loaded from SYSROOT/liballoc-*.rlib

View File

@ -2,7 +2,7 @@ error[E0264]: unknown external lang item: `cake`
--> $DIR/E0264.rs:5:5 --> $DIR/E0264.rs:5:5
| |
LL | fn cake(); LL | fn cake();
| ^^^^^^^^^ | ^^^^^^^^^^
error: aborting due to 1 previous error error: aborting due to 1 previous error

View File

@ -22,6 +22,8 @@ trait MyIndex<'a, T> {}
#[lang = "phantom_data"] #[lang = "phantom_data"]
//~^ ERROR `phantom_data` language item must be applied to a struct with 1 generic argument //~^ ERROR `phantom_data` language item must be applied to a struct with 1 generic argument
struct MyPhantomData<T, U>; struct MyPhantomData<T, U>;
//~^ ERROR parameter `T` is never used
//~| ERROR parameter `U` is never used
#[lang = "owned_box"] #[lang = "owned_box"]
//~^ ERROR `owned_box` language item must be applied to a struct with at least 1 generic argument //~^ ERROR `owned_box` language item must be applied to a struct with at least 1 generic argument
@ -40,6 +42,7 @@ fn ice() {
let r = 5; let r = 5;
let a = 6; let a = 6;
r + a; r + a;
//~^ ERROR cannot add `{integer}` to `{integer}`
// Use drop in place // Use drop in place
my_ptr_drop(); my_ptr_drop();

View File

@ -33,7 +33,7 @@ LL | struct MyPhantomData<T, U>;
| ------ this struct has 2 generic arguments | ------ this struct has 2 generic arguments
error[E0718]: `owned_box` language item must be applied to a struct with at least 1 generic argument error[E0718]: `owned_box` language item must be applied to a struct with at least 1 generic argument
--> $DIR/lang-item-generic-requirements.rs:26:1 --> $DIR/lang-item-generic-requirements.rs:28:1
| |
LL | #[lang = "owned_box"] LL | #[lang = "owned_box"]
| ^^^^^^^^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^^^^^
@ -42,7 +42,7 @@ LL | struct Foo;
| - this struct has 0 generic arguments | - this struct has 0 generic arguments
error[E0718]: `start` language item must be applied to a function with 1 generic argument error[E0718]: `start` language item must be applied to a function with 1 generic argument
--> $DIR/lang-item-generic-requirements.rs:32:1 --> $DIR/lang-item-generic-requirements.rs:34:1
| |
LL | #[lang = "start"] LL | #[lang = "start"]
| ^^^^^^^^^^^^^^^^^ | ^^^^^^^^^^^^^^^^^
@ -50,6 +50,35 @@ LL |
LL | fn start(_: *const u8, _: isize, _: *const *const u8) -> isize { LL | fn start(_: *const u8, _: isize, _: *const *const u8) -> isize {
| - this function has 0 generic arguments | - this function has 0 generic arguments
error: aborting due to 6 previous errors error[E0392]: parameter `T` is never used
--> $DIR/lang-item-generic-requirements.rs:24:22
|
LL | struct MyPhantomData<T, U>;
| ^ unused parameter
|
= help: consider removing `T` or referring to it in a field
= help: if you intended `T` to be a const parameter, use `const T: usize` instead
For more information about this error, try `rustc --explain E0718`. error[E0392]: parameter `U` is never used
--> $DIR/lang-item-generic-requirements.rs:24:25
|
LL | struct MyPhantomData<T, U>;
| ^ unused parameter
|
= help: consider removing `U` or referring to it in a field
= help: if you intended `U` to be a const parameter, use `const U: usize` instead
error[E0369]: cannot add `{integer}` to `{integer}`
--> $DIR/lang-item-generic-requirements.rs:44:7
|
LL | r + a;
| - ^ - {integer}
| |
| {integer}
error: requires `copy` lang_item
error: aborting due to 10 previous errors
Some errors have detailed explanations: E0369, E0392, E0718.
For more information about an error, try `rustc --explain E0369`.

View File

@ -1,14 +1,18 @@
error[E0152]: found duplicate lang item `panic_impl` error[E0152]: found duplicate lang item `panic_impl`
--> $DIR/panic-handler-duplicate.rs:15:1 --> $DIR/panic-handler-duplicate.rs:15:1
| |
LL | fn panic2(info: &PanicInfo) -> ! { LL | / fn panic2(info: &PanicInfo) -> ! {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | | loop {}
LL | | }
| |_^
| |
note: the lang item is first defined here note: the lang item is first defined here
--> $DIR/panic-handler-duplicate.rs:10:1 --> $DIR/panic-handler-duplicate.rs:10:1
| |
LL | fn panic(info: &PanicInfo) -> ! { LL | / fn panic(info: &PanicInfo) -> ! {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | | loop {}
LL | | }
| |_^
error: aborting due to 1 previous error error: aborting due to 1 previous error

View File

@ -1,8 +1,10 @@
error[E0152]: found duplicate lang item `panic_impl` error[E0152]: found duplicate lang item `panic_impl`
--> $DIR/panic-handler-std.rs:8:1 --> $DIR/panic-handler-std.rs:8:1
| |
LL | fn panic(info: PanicInfo) -> ! { LL | / fn panic(info: PanicInfo) -> ! {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ LL | | loop {}
LL | | }
| |_^
| |
= note: the lang item is first defined in crate `std` (which `panic_handler_std` depends on) = note: the lang item is first defined in crate `std` (which `panic_handler_std` depends on)
= note: first definition in `std` loaded from SYSROOT/libstd-*.rlib = note: first definition in `std` loaded from SYSROOT/libstd-*.rlib

View File

@ -7,6 +7,7 @@ trait Sized { } //~ ERROR found duplicate lang item `sized`
fn ref_Struct(self: &Struct, f: &u32) -> &u32 { fn ref_Struct(self: &Struct, f: &u32) -> &u32 {
//~^ ERROR `self` parameter is only allowed in associated functions //~^ ERROR `self` parameter is only allowed in associated functions
//~| ERROR cannot find type `Struct` in this scope //~| ERROR cannot find type `Struct` in this scope
//~| ERROR mismatched types
let x = x << 1; let x = x << 1;
//~^ ERROR cannot find value `x` in this scope //~^ ERROR cannot find value `x` in this scope
} }

View File

@ -13,7 +13,7 @@ LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 {
| ^^^^^^ not found in this scope | ^^^^^^ not found in this scope
error[E0425]: cannot find value `x` in this scope error[E0425]: cannot find value `x` in this scope
--> $DIR/issue-102989.rs:10:13 --> $DIR/issue-102989.rs:11:13
| |
LL | let x = x << 1; LL | let x = x << 1;
| ^ help: a local variable with a similar name exists: `f` | ^ help: a local variable with a similar name exists: `f`
@ -22,13 +22,27 @@ error[E0152]: found duplicate lang item `sized`
--> $DIR/issue-102989.rs:5:1 --> $DIR/issue-102989.rs:5:1
| |
LL | trait Sized { } LL | trait Sized { }
| ^^^^^^^^^^^ | ^^^^^^^^^^^^^^^
| |
= note: the lang item is first defined in crate `core` (which `std` depends on) = note: the lang item is first defined in crate `core` (which `std` depends on)
= note: first definition in `core` loaded from SYSROOT/libcore-*.rlib = note: first definition in `core` loaded from SYSROOT/libcore-*.rlib
= note: second definition in the local crate (`issue_102989`) = note: second definition in the local crate (`issue_102989`)
error: aborting due to 4 previous errors error[E0308]: mismatched types
--> $DIR/issue-102989.rs:7:42
|
LL | fn ref_Struct(self: &Struct, f: &u32) -> &u32 {
| ---------- ^^^^ expected `&u32`, found `()`
| |
| implicitly returns `()` as its body has no tail or `return` expression
|
help: consider returning the local binding `f`
|
LL ~ let x = x << 1;
LL + f
|
Some errors have detailed explanations: E0152, E0412, E0425. error: aborting due to 5 previous errors
Some errors have detailed explanations: E0152, E0308, E0412, E0425.
For more information about an error, try `rustc --explain E0152`. For more information about an error, try `rustc --explain E0152`.