}
#[derive(Clone, Encodable, Decodable, Debug)]
-pub struct TraitKind(
- pub IsAuto,
- pub Unsafe,
- pub Generics,
- pub GenericBounds,
- pub Vec<P<AssocItem>>,
-);
+pub struct Trait {
+ pub unsafety: Unsafe,
+ pub is_auto: IsAuto,
+ pub generics: Generics,
+ pub bounds: GenericBounds,
+ pub items: Vec<P<AssocItem>>,
+}
#[derive(Clone, Encodable, Decodable, Debug)]
-pub struct TyAliasKind(pub Defaultness, pub Generics, pub GenericBounds, pub Option<P<Ty>>);
+pub struct TyAlias {
+ pub defaultness: Defaultness,
+ pub generics: Generics,
+ pub bounds: GenericBounds,
+ pub ty: Option<P<Ty>>,
+}
#[derive(Clone, Encodable, Decodable, Debug)]
-pub struct ImplKind {
- pub unsafety: Unsafe,
- pub polarity: ImplPolarity,
+pub struct Impl {
pub defaultness: Defaultness,
- pub constness: Const,
+ pub unsafety: Unsafe,
pub generics: Generics,
-
+ pub constness: Const,
+ pub polarity: ImplPolarity,
/// The trait being implemented, if any.
pub of_trait: Option<TraitRef>,
-
pub self_ty: P<Ty>,
pub items: Vec<P<AssocItem>>,
}
#[derive(Clone, Encodable, Decodable, Debug)]
-pub struct FnKind(pub Defaultness, pub FnSig, pub Generics, pub Option<P<Block>>);
+pub struct Fn {
+ pub defaultness: Defaultness,
+ pub generics: Generics,
+ pub sig: FnSig,
+ pub body: Option<P<Block>>,
+}
#[derive(Clone, Encodable, Decodable, Debug)]
pub enum ItemKind {
/// A function declaration (`fn`).
///
/// E.g., `fn foo(bar: usize) -> usize { .. }`.
- Fn(Box<FnKind>),
+ Fn(Box<Fn>),
/// A module declaration (`mod`).
///
/// E.g., `mod foo;` or `mod foo { .. }`.
/// A type alias (`type`).
///
/// E.g., `type Foo = Bar<u8>;`.
- TyAlias(Box<TyAliasKind>),
+ TyAlias(Box<TyAlias>),
/// An enum definition (`enum`).
///
/// E.g., `enum Foo<A, B> { C<A>, D<B> }`.
/// A trait declaration (`trait`).
///
/// E.g., `trait Foo { .. }`, `trait Foo<T> { .. }` or `auto trait Foo {}`.
- Trait(Box<TraitKind>),
+ Trait(Box<Trait>),
/// Trait alias
///
/// E.g., `trait Foo = Bar + Quux;`.
/// An implementation.
///
/// E.g., `impl<A> Foo<A> { .. }` or `impl<A> Trait for Foo<A> { .. }`.
- Impl(Box<ImplKind>),
+ Impl(Box<Impl>),
/// A macro invocation.
///
/// E.g., `foo!(..)`.
pub fn generics(&self) -> Option<&Generics> {
match self {
- Self::Fn(box FnKind(_, _, generics, _))
- | Self::TyAlias(box TyAliasKind(_, generics, ..))
+ Self::Fn(box Fn { generics, .. })
+ | Self::TyAlias(box TyAlias { generics, .. })
| Self::Enum(_, generics)
| Self::Struct(_, generics)
| Self::Union(_, generics)
- | Self::Trait(box TraitKind(_, _, generics, ..))
+ | Self::Trait(box Trait { generics, .. })
| Self::TraitAlias(generics, _)
- | Self::Impl(box ImplKind { generics, .. }) => Some(generics),
+ | Self::Impl(box Impl { generics, .. }) => Some(generics),
_ => None,
}
}
/// If `def` is parsed, then the constant is provided, and otherwise required.
Const(Defaultness, P<Ty>, Option<P<Expr>>),
/// An associated function.
- Fn(Box<FnKind>),
+ Fn(Box<Fn>),
/// An associated type.
- TyAlias(Box<TyAliasKind>),
+ TyAlias(Box<TyAlias>),
/// A macro expanding to associated items.
MacCall(MacCall),
}
impl AssocItemKind {
pub fn defaultness(&self) -> Defaultness {
match *self {
- Self::Const(def, ..)
- | Self::Fn(box FnKind(def, ..))
- | Self::TyAlias(box TyAliasKind(def, ..)) => def,
+ Self::Const(defaultness, ..)
+ | Self::Fn(box Fn { defaultness, .. })
+ | Self::TyAlias(box TyAlias { defaultness, .. }) => defaultness,
Self::MacCall(..) => Defaultness::Final,
}
}
/// A foreign static item (`static FOO: u8`).
Static(P<Ty>, Mutability, Option<P<Expr>>),
/// An foreign function.
- Fn(Box<FnKind>),
+ Fn(Box<Fn>),
/// An foreign type.
- TyAlias(Box<TyAliasKind>),
+ TyAlias(Box<TyAlias>),
/// A macro expanding to foreign items.
MacCall(MacCall),
}
vis.visit_mt(mt);
}
TyKind::BareFn(bft) => {
- let BareFnTy { unsafety: _, ext: _, generic_params, decl } = bft.deref_mut();
+ let BareFnTy { unsafety, ext: _, generic_params, decl } = bft.deref_mut();
+ visit_unsafety(unsafety, vis);
generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param));
vis.visit_fn_decl(decl);
}
}
pub fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: &mut T) {
- let ForeignMod { unsafety: _, abi: _, items } = foreign_mod;
+ let ForeignMod { unsafety, abi: _, items } = foreign_mod;
+ visit_unsafety(unsafety, vis);
items.flat_map_in_place(|item| vis.flat_map_foreign_item(item));
}
}
}
+// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
+pub fn visit_defaultness<T: MutVisitor>(defaultness: &mut Defaultness, vis: &mut T) {
+ match defaultness {
+ Defaultness::Default(span) => vis.visit_span(span),
+ Defaultness::Final => {}
+ }
+}
+
+// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
+pub fn visit_unsafety<T: MutVisitor>(unsafety: &mut Unsafe, vis: &mut T) {
+ match unsafety {
+ Unsafe::Yes(span) => vis.visit_span(span),
+ Unsafe::No => {}
+ }
+}
+
+// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
+pub fn visit_polarity<T: MutVisitor>(polarity: &mut ImplPolarity, vis: &mut T) {
+ match polarity {
+ ImplPolarity::Positive => {}
+ ImplPolarity::Negative(span) => vis.visit_span(span),
+ }
+}
+
+// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
+pub fn visit_constness<T: MutVisitor>(constness: &mut Const, vis: &mut T) {
+ match constness {
+ Const::Yes(span) => vis.visit_span(span),
+ Const::No => {}
+ }
+}
+
pub fn noop_visit_asyncness<T: MutVisitor>(asyncness: &mut Async, vis: &mut T) {
match asyncness {
Async::Yes { span: _, closure_id, return_impl_trait_id } => {
match kind {
ItemKind::ExternCrate(_orig_name) => {}
ItemKind::Use(use_tree) => vis.visit_use_tree(use_tree),
- ItemKind::Static(ty, _, expr) | ItemKind::Const(_, ty, expr) => {
+ ItemKind::Static(ty, _, expr) => {
vis.visit_ty(ty);
visit_opt(expr, |expr| vis.visit_expr(expr));
}
- ItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ ItemKind::Const(defaultness, ty, expr) => {
+ visit_defaultness(defaultness, vis);
+ vis.visit_ty(ty);
+ visit_opt(expr, |expr| vis.visit_expr(expr));
+ }
+ ItemKind::Fn(box Fn { defaultness, generics, sig, body }) => {
+ visit_defaultness(defaultness, vis);
visit_fn_sig(sig, vis);
vis.visit_generics(generics);
visit_opt(body, |body| vis.visit_block(body));
}
- ItemKind::Mod(_unsafety, mod_kind) => match mod_kind {
- ModKind::Loaded(items, _inline, inner_span) => {
- vis.visit_span(inner_span);
- items.flat_map_in_place(|item| vis.flat_map_item(item));
+ ItemKind::Mod(unsafety, mod_kind) => {
+ visit_unsafety(unsafety, vis);
+ match mod_kind {
+ ModKind::Loaded(items, _inline, inner_span) => {
+ vis.visit_span(inner_span);
+ items.flat_map_in_place(|item| vis.flat_map_item(item));
+ }
+ ModKind::Unloaded => {}
}
- ModKind::Unloaded => {}
- },
+ }
ItemKind::ForeignMod(nm) => vis.visit_foreign_mod(nm),
ItemKind::GlobalAsm(asm) => noop_visit_inline_asm(asm, vis),
- ItemKind::TyAlias(box TyAliasKind(_, generics, bounds, ty)) => {
+ ItemKind::TyAlias(box TyAlias { defaultness, generics, bounds, ty }) => {
+ visit_defaultness(defaultness, vis);
vis.visit_generics(generics);
visit_bounds(bounds, vis);
visit_opt(ty, |ty| vis.visit_ty(ty));
vis.visit_variant_data(variant_data);
vis.visit_generics(generics);
}
- ItemKind::Impl(box ImplKind {
- unsafety: _,
- polarity: _,
- defaultness: _,
- constness: _,
+ ItemKind::Impl(box Impl {
+ defaultness,
+ unsafety,
generics,
+ constness,
+ polarity,
of_trait,
self_ty,
items,
}) => {
+ visit_defaultness(defaultness, vis);
+ visit_unsafety(unsafety, vis);
vis.visit_generics(generics);
+ visit_constness(constness, vis);
+ visit_polarity(polarity, vis);
visit_opt(of_trait, |trait_ref| vis.visit_trait_ref(trait_ref));
vis.visit_ty(self_ty);
items.flat_map_in_place(|item| vis.flat_map_impl_item(item));
}
- ItemKind::Trait(box TraitKind(.., generics, bounds, items)) => {
+ ItemKind::Trait(box Trait { unsafety, is_auto: _, generics, bounds, items }) => {
+ visit_unsafety(unsafety, vis);
vis.visit_generics(generics);
visit_bounds(bounds, vis);
items.flat_map_in_place(|item| vis.flat_map_trait_item(item));
visitor.visit_vis(vis);
visit_attrs(attrs, visitor);
match kind {
- AssocItemKind::Const(_, ty, expr) => {
+ AssocItemKind::Const(defaultness, ty, expr) => {
+ visit_defaultness(defaultness, visitor);
visitor.visit_ty(ty);
visit_opt(expr, |expr| visitor.visit_expr(expr));
}
- AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ AssocItemKind::Fn(box Fn { defaultness, generics, sig, body }) => {
+ visit_defaultness(defaultness, visitor);
visitor.visit_generics(generics);
visit_fn_sig(sig, visitor);
visit_opt(body, |body| visitor.visit_block(body));
}
- AssocItemKind::TyAlias(box TyAliasKind(_, generics, bounds, ty)) => {
+ AssocItemKind::TyAlias(box TyAlias { defaultness, generics, bounds, ty }) => {
+ visit_defaultness(defaultness, visitor);
visitor.visit_generics(generics);
visit_bounds(bounds, visitor);
visit_opt(ty, |ty| visitor.visit_ty(ty));
}
pub fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) {
- let FnHeader { unsafety: _, asyncness, constness: _, ext: _ } = header;
+ let FnHeader { unsafety, asyncness, constness, ext: _ } = header;
+ visit_constness(constness, vis);
vis.visit_asyncness(asyncness);
+ visit_unsafety(unsafety, vis);
}
// FIXME: Avoid visiting the crate as a `Mod` item, flat map only the inner items if possible,
visitor.visit_ty(ty);
visit_opt(expr, |expr| visitor.visit_expr(expr));
}
- ForeignItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ ForeignItemKind::Fn(box Fn { defaultness, generics, sig, body }) => {
+ visit_defaultness(defaultness, visitor);
visitor.visit_generics(generics);
visit_fn_sig(sig, visitor);
visit_opt(body, |body| visitor.visit_block(body));
}
- ForeignItemKind::TyAlias(box TyAliasKind(_, generics, bounds, ty)) => {
+ ForeignItemKind::TyAlias(box TyAlias { defaultness, generics, bounds, ty }) => {
+ visit_defaultness(defaultness, visitor);
visitor.visit_generics(generics);
visit_bounds(bounds, visitor);
visit_opt(ty, |ty| visitor.visit_ty(ty));
i += 1;
}
// like the first, a last line of all stars should be omitted
- if j > i && lines[j - 1].chars().skip(1).all(|c| c == '*') {
+ if j > i && !lines[j - 1].is_empty() && lines[j - 1].chars().all(|c| c == '*') {
j -= 1;
}
visitor.visit_ty(typ);
walk_list!(visitor, visit_expr, expr);
}
- ItemKind::Fn(box FnKind(_, ref sig, ref generics, ref body)) => {
+ ItemKind::Fn(box Fn { defaultness: _, ref generics, ref sig, ref body }) => {
visitor.visit_generics(generics);
let kind = FnKind::Fn(FnCtxt::Free, item.ident, sig, &item.vis, body.as_deref());
visitor.visit_fn(kind, item.span, item.id)
walk_list!(visitor, visit_foreign_item, &foreign_module.items);
}
ItemKind::GlobalAsm(ref asm) => walk_inline_asm(visitor, asm),
- ItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref ty)) => {
+ ItemKind::TyAlias(box TyAlias { defaultness: _, ref generics, ref bounds, ref ty }) => {
visitor.visit_generics(generics);
walk_list!(visitor, visit_param_bound, bounds);
walk_list!(visitor, visit_ty, ty);
visitor.visit_generics(generics);
visitor.visit_enum_def(enum_definition, generics, item.id, item.span)
}
- ItemKind::Impl(box ImplKind {
- unsafety: _,
- polarity: _,
+ ItemKind::Impl(box Impl {
defaultness: _,
- constness: _,
+ unsafety: _,
ref generics,
+ constness: _,
+ polarity: _,
ref of_trait,
ref self_ty,
ref items,
visitor.visit_generics(generics);
visitor.visit_variant_data(struct_definition);
}
- ItemKind::Trait(box TraitKind(.., ref generics, ref bounds, ref items)) => {
+ ItemKind::Trait(box Trait {
+ unsafety: _,
+ is_auto: _,
+ ref generics,
+ ref bounds,
+ ref items,
+ }) => {
visitor.visit_generics(generics);
walk_list!(visitor, visit_param_bound, bounds);
walk_list!(visitor, visit_assoc_item, items, AssocCtxt::Trait);
visitor.visit_ty(ty);
walk_list!(visitor, visit_expr, expr);
}
- ForeignItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ ForeignItemKind::Fn(box Fn { defaultness: _, ref generics, ref sig, ref body }) => {
visitor.visit_generics(generics);
let kind = FnKind::Fn(FnCtxt::Foreign, ident, sig, vis, body.as_deref());
visitor.visit_fn(kind, span, id);
}
- ForeignItemKind::TyAlias(box TyAliasKind(_, generics, bounds, ty)) => {
+ ForeignItemKind::TyAlias(box TyAlias { defaultness: _, generics, bounds, ty }) => {
visitor.visit_generics(generics);
walk_list!(visitor, visit_param_bound, bounds);
walk_list!(visitor, visit_ty, ty);
visitor.visit_ty(ty);
walk_list!(visitor, visit_expr, expr);
}
- AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ AssocItemKind::Fn(box Fn { defaultness: _, ref generics, ref sig, ref body }) => {
visitor.visit_generics(generics);
let kind = FnKind::Fn(FnCtxt::Assoc(ctxt), ident, sig, vis, body.as_deref());
visitor.visit_fn(kind, span, id);
}
- AssocItemKind::TyAlias(box TyAliasKind(_, generics, bounds, ty)) => {
+ AssocItemKind::TyAlias(box TyAlias { defaultness: _, generics, bounds, ty }) => {
visitor.visit_generics(generics);
walk_list!(visitor, visit_param_bound, bounds);
walk_list!(visitor, visit_ty, ty);
self.lctx.with_parent_item_lifetime_defs(hir_id, |this| {
let this = &mut ItemLowerer { lctx: this };
match item.kind {
- ItemKind::Impl(box ImplKind { ref of_trait, .. }) => {
+ ItemKind::Impl(box Impl { ref of_trait, .. }) => {
this.with_trait_impl_ref(of_trait, |this| visit::walk_item(this, item));
}
_ => visit::walk_item(this, item),
let (ty, body_id) = self.lower_const_item(t, span, e.as_deref());
hir::ItemKind::Const(ty, body_id)
}
- ItemKind::Fn(box FnKind(
- _,
- FnSig { ref decl, header, span: fn_sig_span },
+ ItemKind::Fn(box Fn {
+ sig: FnSig { ref decl, header, span: fn_sig_span },
ref generics,
ref body,
- )) => {
+ ..
+ }) => {
let fn_def_id = self.resolver.local_def_id(id);
self.with_new_scopes(|this| {
this.current_item = Some(ident.span);
ItemKind::GlobalAsm(ref asm) => {
hir::ItemKind::GlobalAsm(self.lower_inline_asm(span, asm))
}
- ItemKind::TyAlias(box TyAliasKind(_, ref gen, _, Some(ref ty))) => {
+ ItemKind::TyAlias(box TyAlias { ref generics, ty: Some(ref ty), .. }) => {
// We lower
//
// type Foo = impl Trait
capturable_lifetimes: &mut FxHashSet::default(),
},
);
- let generics = self.lower_generics(gen, ImplTraitContext::disallowed());
+ let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
hir::ItemKind::TyAlias(ty, generics)
}
- ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, None)) => {
+ ItemKind::TyAlias(box TyAlias { ref generics, ty: None, .. }) => {
let ty = self.arena.alloc(self.ty(span, hir::TyKind::Err));
let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
hir::ItemKind::TyAlias(ty, generics)
self.lower_generics(generics, ImplTraitContext::disallowed()),
)
}
- ItemKind::Impl(box ImplKind {
+ ItemKind::Impl(box Impl {
unsafety,
polarity,
defaultness,
items: new_impl_items,
})
}
- ItemKind::Trait(box TraitKind(
+ ItemKind::Trait(box Trait {
is_auto,
unsafety,
ref generics,
ref bounds,
ref items,
- )) => {
+ }) => {
let bounds = self.lower_param_bounds(bounds, ImplTraitContext::disallowed());
let items = self
.arena
def_id,
ident: self.lower_ident(i.ident),
kind: match i.kind {
- ForeignItemKind::Fn(box FnKind(_, ref sig, ref generics, _)) => {
+ ForeignItemKind::Fn(box Fn { ref sig, ref generics, .. }) => {
let fdec = &sig.decl;
let (generics, (fn_dec, fn_args)) = self.add_in_band_defs(
generics,
let body = default.as_ref().map(|x| self.lower_const_body(i.span, Some(x)));
(hir::Generics::empty(), hir::TraitItemKind::Const(ty, body))
}
- AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, None)) => {
+ AssocItemKind::Fn(box Fn { ref sig, ref generics, body: None, .. }) => {
let names = self.lower_fn_params_to_names(&sig.decl);
let (generics, sig) =
self.lower_method_sig(generics, sig, trait_item_def_id, false, None);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Required(names)))
}
- AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, Some(ref body))) => {
+ AssocItemKind::Fn(box Fn { ref sig, ref generics, body: Some(ref body), .. }) => {
let asyncness = sig.header.asyncness;
let body_id =
self.lower_maybe_async_body(i.span, &sig.decl, asyncness, Some(&body));
);
(generics, hir::TraitItemKind::Fn(sig, hir::TraitFn::Provided(body_id)))
}
- AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref default)) => {
- let ty = default.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
+ AssocItemKind::TyAlias(box TyAlias { ref generics, ref bounds, ref ty, .. }) => {
+ let ty = ty.as_ref().map(|x| self.lower_ty(x, ImplTraitContext::disallowed()));
let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
let kind = hir::TraitItemKind::Type(
self.lower_param_bounds(bounds, ImplTraitContext::disallowed()),
fn lower_trait_item_ref(&mut self, i: &AssocItem) -> hir::TraitItemRef {
let (kind, has_default) = match &i.kind {
AssocItemKind::Const(_, _, default) => (hir::AssocItemKind::Const, default.is_some()),
- AssocItemKind::TyAlias(box TyAliasKind(_, _, _, default)) => {
- (hir::AssocItemKind::Type, default.is_some())
+ AssocItemKind::TyAlias(box TyAlias { ty, .. }) => {
+ (hir::AssocItemKind::Type, ty.is_some())
}
- AssocItemKind::Fn(box FnKind(_, sig, _, default)) => {
- (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, default.is_some())
+ AssocItemKind::Fn(box Fn { sig, body, .. }) => {
+ (hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }, body.is_some())
}
AssocItemKind::MacCall(..) => unimplemented!(),
};
hir::ImplItemKind::Const(ty, self.lower_const_body(i.span, expr.as_deref())),
)
}
- AssocItemKind::Fn(box FnKind(_, sig, generics, body)) => {
+ AssocItemKind::Fn(box Fn { sig, generics, body, .. }) => {
self.current_item = Some(i.span);
let asyncness = sig.header.asyncness;
let body_id =
(generics, hir::ImplItemKind::Fn(sig, body_id))
}
- AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, ty)) => {
+ AssocItemKind::TyAlias(box TyAlias { generics, ty, .. }) => {
let generics = self.lower_generics(generics, ImplTraitContext::disallowed());
let kind = match ty {
None => {
kind: match &i.kind {
AssocItemKind::Const(..) => hir::AssocItemKind::Const,
AssocItemKind::TyAlias(..) => hir::AssocItemKind::Type,
- AssocItemKind::Fn(box FnKind(_, sig, ..)) => {
+ AssocItemKind::Fn(box Fn { sig, .. }) => {
hir::AssocItemKind::Fn { has_self: sig.decl.has_self() }
}
AssocItemKind::MacCall(..) => unimplemented!(),
}
match item.kind {
- ItemKind::Impl(box ImplKind {
+ ItemKind::Impl(box Impl {
unsafety,
polarity,
defaultness: _,
});
return; // Avoid visiting again.
}
- ItemKind::Impl(box ImplKind {
+ ItemKind::Impl(box Impl {
unsafety,
polarity,
defaultness,
.emit();
}
}
- ItemKind::Fn(box FnKind(def, ref sig, ref generics, ref body)) => {
- self.check_defaultness(item.span, def);
+ ItemKind::Fn(box Fn { defaultness, ref sig, ref generics, ref body }) => {
+ self.check_defaultness(item.span, defaultness);
if body.is_none() {
let msg = "free function without a body";
}
}
}
- ItemKind::Trait(box TraitKind(
- is_auto,
- _,
- ref generics,
- ref bounds,
- ref trait_items,
- )) => {
+ ItemKind::Trait(box Trait { is_auto, ref generics, ref bounds, ref items, .. }) => {
if is_auto == IsAuto::Yes {
// Auto traits cannot have generics, super traits nor contain items.
self.deny_generic_params(generics, item.ident.span);
self.deny_super_traits(bounds, item.ident.span);
self.deny_where_clause(&generics.where_clause, item.ident.span);
- self.deny_items(trait_items, item.ident.span);
+ self.deny_items(items, item.ident.span);
}
self.no_questions_in_bounds(bounds, "supertraits", true);
self.visit_ident(item.ident);
self.visit_generics(generics);
self.with_banned_tilde_const(|this| walk_list!(this, visit_param_bound, bounds));
- walk_list!(self, visit_assoc_item, trait_items, AssocCtxt::Trait);
+ walk_list!(self, visit_assoc_item, items, AssocCtxt::Trait);
walk_list!(self, visit_attribute, &item.attrs);
return;
}
let msg = "free static item without body";
self.error_item_without_body(item.span, "static", msg, " = <expr>;");
}
- ItemKind::TyAlias(box TyAliasKind(def, _, ref bounds, ref body)) => {
- self.check_defaultness(item.span, def);
- if body.is_none() {
+ ItemKind::TyAlias(box TyAlias { defaultness, ref bounds, ref ty, .. }) => {
+ self.check_defaultness(item.span, defaultness);
+ if ty.is_none() {
let msg = "free type alias without body";
self.error_item_without_body(item.span, "type", msg, " = <type>;");
}
fn visit_foreign_item(&mut self, fi: &'a ForeignItem) {
match &fi.kind {
- ForeignItemKind::Fn(box FnKind(def, sig, _, body)) => {
- self.check_defaultness(fi.span, *def);
+ ForeignItemKind::Fn(box Fn { defaultness, sig, body, .. }) => {
+ self.check_defaultness(fi.span, *defaultness);
self.check_foreign_fn_bodyless(fi.ident, body.as_deref());
self.check_foreign_fn_headerless(fi.ident, fi.span, sig.header);
self.check_foreign_item_ascii_only(fi.ident);
}
- ForeignItemKind::TyAlias(box TyAliasKind(def, generics, bounds, body)) => {
- self.check_defaultness(fi.span, *def);
- self.check_foreign_kind_bodyless(fi.ident, "type", body.as_ref().map(|b| b.span));
+ ForeignItemKind::TyAlias(box TyAlias { defaultness, generics, bounds, ty, .. }) => {
+ self.check_defaultness(fi.span, *defaultness);
+ self.check_foreign_kind_bodyless(fi.ident, "type", ty.as_ref().map(|b| b.span));
self.check_type_no_bounds(bounds, "`extern` blocks");
self.check_foreign_ty_genericless(generics);
self.check_foreign_item_ascii_only(fi.ident);
AssocItemKind::Const(_, _, body) => {
self.check_impl_item_provided(item.span, body, "constant", " = <expr>;");
}
- AssocItemKind::Fn(box FnKind(_, _, _, body)) => {
+ AssocItemKind::Fn(box Fn { body, .. }) => {
self.check_impl_item_provided(item.span, body, "function", " { <body> }");
}
- AssocItemKind::TyAlias(box TyAliasKind(_, _, bounds, body)) => {
- self.check_impl_item_provided(item.span, body, "type", " = <type>;");
+ AssocItemKind::TyAlias(box TyAlias { bounds, ty, .. }) => {
+ self.check_impl_item_provided(item.span, ty, "type", " = <type>;");
self.check_type_no_bounds(bounds, "`impl`s");
}
_ => {}
if ctxt == AssocCtxt::Trait || self.in_trait_impl {
self.invalid_visibility(&item.vis, None);
- if let AssocItemKind::Fn(box FnKind(_, sig, _, _)) = &item.kind {
+ if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
self.check_trait_fn_not_const(sig.header.constness);
self.check_trait_fn_not_async(item.span, sig.header.asyncness);
}
}
match item.kind {
- AssocItemKind::TyAlias(box TyAliasKind(_, ref generics, ref bounds, ref ty))
+ AssocItemKind::TyAlias(box TyAlias { ref generics, ref bounds, ref ty, .. })
if ctxt == AssocCtxt::Trait =>
{
self.visit_vis(&item.vis);
});
walk_list!(self, visit_ty, ty);
}
- AssocItemKind::Fn(box FnKind(_, ref sig, ref generics, ref body))
+ AssocItemKind::Fn(box Fn { ref sig, ref generics, ref body, .. })
if self.in_const_trait_impl
|| ctxt == AssocCtxt::Trait
|| matches!(sig.header.constness, Const::Yes(_)) =>
}
}
- ast::ItemKind::Impl(box ast::ImplKind {
- polarity, defaultness, ref of_trait, ..
- }) => {
+ ast::ItemKind::Impl(box ast::Impl { polarity, defaultness, ref of_trait, .. }) => {
if let ast::ImplPolarity::Negative(span) = polarity {
gate_feature_post!(
&self,
}
}
- ast::ItemKind::Trait(box ast::TraitKind(ast::IsAuto::Yes, ..)) => {
+ ast::ItemKind::Trait(box ast::Trait { is_auto: ast::IsAuto::Yes, .. }) => {
gate_feature_post!(
&self,
auto_traits,
gate_feature_post!(&self, decl_macro, i.span, msg);
}
- ast::ItemKind::TyAlias(box ast::TyAliasKind(_, _, _, Some(ref ty))) => {
+ ast::ItemKind::TyAlias(box ast::TyAlias { ty: Some(ref ty), .. }) => {
self.check_impl_trait(&ty)
}
ast::ExprKind::TryBlock(_) => {
gate_feature_post!(&self, try_blocks, e.span, "`try` expression is experimental");
}
- ast::ExprKind::Block(_, opt_label) => {
- if let Some(label) = opt_label {
- gate_feature_post!(
- &self,
- label_break_value,
- label.ident.span,
- "labels on blocks are unstable"
- );
- }
+ ast::ExprKind::Block(_, Some(label)) => {
+ gate_feature_post!(
+ &self,
+ label_break_value,
+ label.ident.span,
+ "labels on blocks are unstable"
+ );
}
_ => {}
}
fn visit_assoc_item(&mut self, i: &'a ast::AssocItem, ctxt: AssocCtxt) {
let is_fn = match i.kind {
ast::AssocItemKind::Fn(_) => true,
- ast::AssocItemKind::TyAlias(box ast::TyAliasKind(_, ref generics, _, ref ty)) => {
+ ast::AssocItemKind::TyAlias(box ast::TyAlias { ref generics, ref ty, .. }) => {
if let (Some(_), AssocCtxt::Trait) = (ty, ctxt) {
gate_feature_post!(
&self,
self.maybe_print_comment(span.lo());
self.print_outer_attributes(attrs);
match kind {
- ast::ForeignItemKind::Fn(box ast::FnKind(def, sig, gen, body)) => {
- self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
+ ast::ForeignItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
+ self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
}
ast::ForeignItemKind::Static(ty, mutbl, body) => {
let def = ast::Defaultness::Final;
self.print_item_const(ident, Some(*mutbl), ty, body.as_deref(), vis, def);
}
- ast::ForeignItemKind::TyAlias(box ast::TyAliasKind(def, generics, bounds, ty)) => {
- self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
+ ast::ForeignItemKind::TyAlias(box ast::TyAlias {
+ defaultness,
+ generics,
+ bounds,
+ ty,
+ }) => {
+ self.print_associated_type(
+ ident,
+ generics,
+ bounds,
+ ty.as_deref(),
+ vis,
+ *defaultness,
+ );
}
ast::ForeignItemKind::MacCall(m) => {
self.print_mac(m);
ast::ItemKind::Const(def, ref ty, ref body) => {
self.print_item_const(item.ident, None, ty, body.as_deref(), &item.vis, def);
}
- ast::ItemKind::Fn(box ast::FnKind(def, ref sig, ref gen, ref body)) => {
+ ast::ItemKind::Fn(box ast::Fn { defaultness, ref sig, ref generics, ref body }) => {
let body = body.as_deref();
- self.print_fn_full(sig, item.ident, gen, &item.vis, def, body, &item.attrs);
+ self.print_fn_full(
+ sig,
+ item.ident,
+ generics,
+ &item.vis,
+ defaultness,
+ body,
+ &item.attrs,
+ );
}
ast::ItemKind::Mod(unsafety, ref mod_kind) => {
self.head(self.to_string(|s| {
self.print_inline_asm(asm);
self.end();
}
- ast::ItemKind::TyAlias(box ast::TyAliasKind(def, ref generics, ref bounds, ref ty)) => {
+ ast::ItemKind::TyAlias(box ast::TyAlias {
+ defaultness,
+ ref generics,
+ ref bounds,
+ ref ty,
+ }) => {
let ty = ty.as_deref();
- self.print_associated_type(item.ident, generics, bounds, ty, &item.vis, def);
+ self.print_associated_type(
+ item.ident,
+ generics,
+ bounds,
+ ty,
+ &item.vis,
+ defaultness,
+ );
}
ast::ItemKind::Enum(ref enum_definition, ref params) => {
self.print_enum_def(enum_definition, params, item.ident, item.span, &item.vis);
self.head(visibility_qualified(&item.vis, "union"));
self.print_struct(struct_def, generics, item.ident, item.span, true);
}
- ast::ItemKind::Impl(box ast::ImplKind {
+ ast::ItemKind::Impl(box ast::Impl {
unsafety,
polarity,
defaultness,
}
self.bclose(item.span);
}
- ast::ItemKind::Trait(box ast::TraitKind(
+ ast::ItemKind::Trait(box ast::Trait {
is_auto,
unsafety,
ref generics,
ref bounds,
- ref trait_items,
- )) => {
+ ref items,
+ ..
+ }) => {
self.head("");
self.print_visibility(&item.vis);
self.print_unsafety(unsafety);
self.s.word(" ");
self.bopen();
self.print_inner_attributes(&item.attrs);
- for trait_item in trait_items {
+ for trait_item in items {
self.print_assoc_item(trait_item);
}
self.bclose(item.span);
}
}
- crate fn print_record_struct_body(
- &mut self,
- fields: &Vec<ast::FieldDef>,
- span: rustc_span::Span,
- ) {
+ crate fn print_record_struct_body(&mut self, fields: &[ast::FieldDef], span: rustc_span::Span) {
self.nbsp();
self.bopen();
self.hardbreak_if_not_bol();
self.maybe_print_comment(span.lo());
self.print_outer_attributes(attrs);
match kind {
- ast::AssocItemKind::Fn(box ast::FnKind(def, sig, gen, body)) => {
- self.print_fn_full(sig, ident, gen, vis, *def, body.as_deref(), attrs);
+ ast::AssocItemKind::Fn(box ast::Fn { defaultness, sig, generics, body }) => {
+ self.print_fn_full(sig, ident, generics, vis, *defaultness, body.as_deref(), attrs);
}
ast::AssocItemKind::Const(def, ty, body) => {
self.print_item_const(ident, None, ty, body.as_deref(), vis, *def);
}
- ast::AssocItemKind::TyAlias(box ast::TyAliasKind(def, generics, bounds, ty)) => {
- self.print_associated_type(ident, generics, bounds, ty.as_deref(), vis, *def);
+ ast::AssocItemKind::TyAlias(box ast::TyAlias { defaultness, generics, bounds, ty }) => {
+ self.print_associated_type(
+ ident,
+ generics,
+ bounds,
+ ty.as_deref(),
+ vis,
+ *defaultness,
+ );
}
ast::AssocItemKind::MacCall(m) => {
self.print_mac(m);
// If the region is live at at least one location in the promoted MIR,
// then add a liveness constraint to the main MIR for this region
// at the location provided as an argument to this method
- if let Some(_) = liveness_constraints.get_elements(region).next() {
+ if liveness_constraints.get_elements(region).next().is_some() {
self.cx
.borrowck_context
.constraints
if let Some(snippet) = &template_snippet {
if let Some(pos) = snippet.find(needle) {
let end = pos
- + &snippet[pos..]
+ + snippet[pos..]
.find(|c| matches!(c, '\n' | ';' | '\\' | '"'))
.unwrap_or(snippet[pos..].len() - 1);
let inner = InnerSpan::new(pos, end);
tokens: None,
},
attrs: Vec::new(),
- kind: ast::AssocItemKind::TyAlias(Box::new(ast::TyAliasKind(
- ast::Defaultness::Final,
- Generics::default(),
- Vec::new(),
- Some(type_def.to_ty(cx, self.span, type_ident, generics)),
- ))),
+ kind: ast::AssocItemKind::TyAlias(Box::new(ast::TyAlias {
+ defaultness: ast::Defaultness::Final,
+ generics: Generics::default(),
+ bounds: Vec::new(),
+ ty: Some(type_def.to_ty(cx, self.span, type_ident, generics)),
+ })),
tokens: None,
})
});
self.span,
Ident::empty(),
a,
- ast::ItemKind::Impl(Box::new(ast::ImplKind {
+ ast::ItemKind::Impl(Box::new(ast::Impl {
unsafety,
polarity: ast::ImplPolarity::Positive,
defaultness: ast::Defaultness::Final,
decl: fn_decl,
span: trait_.span,
};
- let def = ast::Defaultness::Final;
+ let defaultness = ast::Defaultness::Final;
// Create the method.
P(ast::AssocItem {
tokens: None,
},
ident: method_ident,
- kind: ast::AssocItemKind::Fn(Box::new(ast::FnKind(
- def,
+ kind: ast::AssocItemKind::Fn(Box::new(ast::Fn {
+ defaultness,
sig,
- fn_generics,
- Some(body_block),
- ))),
+ generics: fn_generics,
+ body: Some(body_block),
+ })),
tokens: None,
})
}
use rustc_ast as ast;
use rustc_ast::ptr::P;
-use rustc_ast::{ImplKind, ItemKind, MetaItem};
+use rustc_ast::{Impl, ItemKind, MetaItem};
use rustc_expand::base::{Annotatable, ExpandResult, ExtCtxt, MultiItemModifier};
use rustc_span::symbol::{sym, Ident, Symbol};
use rustc_span::Span;
span,
Ident::empty(),
attrs,
- ItemKind::Impl(Box::new(ImplKind {
+ ItemKind::Impl(Box::new(Impl {
unsafety: ast::Unsafe::No,
polarity: ast::ImplPolarity::Positive,
defaultness: ast::Defaultness::Final,
/// Actually builds the expression which the format_args! block will be
/// expanded to.
fn into_expr(self) -> P<ast::Expr> {
- let mut locals =
- Vec::with_capacity((0..self.args.len()).map(|i| self.arg_unique_types[i].len()).sum());
- let mut counts = Vec::with_capacity(self.count_args.len());
- let mut pats = Vec::with_capacity(self.args.len());
+ let mut args = Vec::with_capacity(
+ self.arg_unique_types.iter().map(|v| v.len()).sum::<usize>() + self.count_args.len(),
+ );
let mut heads = Vec::with_capacity(self.args.len());
- let names_pos: Vec<_> = (0..self.args.len())
- .map(|i| Ident::from_str_and_span(&format!("arg{}", i), self.macsp))
- .collect();
-
// First, build up the static array which will become our precompiled
// format "string"
let pieces = self.ecx.expr_vec_slice(self.fmtsp, self.str_pieces);
// of each variable because we don't want to move out of the arguments
// passed to this function.
for (i, e) in self.args.into_iter().enumerate() {
- let name = names_pos[i];
- let span = self.ecx.with_def_site_ctxt(e.span);
- pats.push(self.ecx.pat_ident(span, name));
for arg_ty in self.arg_unique_types[i].iter() {
- locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, name));
+ args.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty, i));
}
heads.push(self.ecx.expr_addr_of(e.span, e));
}
Exact(i) => i,
_ => panic!("should never happen"),
};
- let name = names_pos[index];
let span = spans_pos[index];
- counts.push(Context::format_arg(self.ecx, self.macsp, span, &Count, name));
+ args.push(Context::format_arg(self.ecx, self.macsp, span, &Count, index));
}
- // Now create a vector containing all the arguments
- let args = locals.into_iter().chain(counts.into_iter());
-
- let args_array = self.ecx.expr_vec(self.macsp, args.collect());
+ let args_array = self.ecx.expr_vec(self.macsp, args);
// Constructs an AST equivalent to:
//
// But the nested match expression is proved to perform not as well
// as series of let's; the first approach does.
let args_match = {
- let pat = self.ecx.pat_tuple(self.macsp, pats);
+ let pat = self.ecx.pat_ident(self.macsp, Ident::new(sym::_args, self.macsp));
let arm = self.ecx.arm(self.macsp, pat, args_array);
let head = self.ecx.expr(self.macsp, ast::ExprKind::Tup(heads));
self.ecx.expr_match(self.macsp, head, vec![arm])
macsp: Span,
mut sp: Span,
ty: &ArgumentType,
- arg: Ident,
+ arg_index: usize,
) -> P<ast::Expr> {
sp = ecx.with_def_site_ctxt(sp);
- let arg = ecx.expr_ident(sp, arg);
+ let arg = ecx.expr_ident(sp, Ident::new(sym::_args, sp));
+ let arg = ecx.expr(sp, ast::ExprKind::Field(arg, Ident::new(sym::integer(arg_index), sp)));
let trait_ = match *ty {
Placeholder(trait_) if trait_ == "<invalid>" => return DummyResult::raw_expr(sp, true),
Placeholder(trait_) => trait_,
};
use rustc_ast::ptr::P;
use rustc_ast::{self as ast, Attribute, Expr, FnHeader, FnSig, Generics, Param, StmtKind};
-use rustc_ast::{FnKind, ItemKind, Mutability, Stmt, Ty, TyKind, Unsafe};
+use rustc_ast::{Fn, ItemKind, Mutability, Stmt, Ty, TyKind, Unsafe};
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span;
let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty));
let header = FnHeader { unsafety: Unsafe::Yes(self.span), ..FnHeader::default() };
let sig = FnSig { decl, header, span: self.span };
- let block = Some(self.cx.block_expr(output_expr));
- let kind = ItemKind::Fn(Box::new(FnKind(
- ast::Defaultness::Final,
+ let body = Some(self.cx.block_expr(output_expr));
+ let kind = ItemKind::Fn(Box::new(Fn {
+ defaultness: ast::Defaultness::Final,
sig,
- Generics::default(),
- block,
- )));
+ generics: Generics::default(),
+ body,
+ }));
let item = self.cx.item(
self.span,
Ident::from_str_and_span(&self.kind.fn_name(method.name), self.span),
fn has_test_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
let has_should_panic_attr = cx.sess.contains_name(&i.attrs, sym::should_panic);
let sd = &cx.sess.parse_sess.span_diagnostic;
- if let ast::ItemKind::Fn(box ast::FnKind(_, ref sig, ref generics, _)) = i.kind {
+ if let ast::ItemKind::Fn(box ast::Fn { ref sig, ref generics, .. }) = i.kind {
if let ast::Unsafe::Yes(span) = sig.header.unsafety {
sd.struct_span_err(i.span, "unsafe functions cannot be used for tests")
.span_label(span, "`unsafe` because of this")
}
fn has_bench_signature(cx: &ExtCtxt<'_>, i: &ast::Item) -> bool {
- let has_sig = if let ast::ItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) = i.kind {
+ let has_sig = if let ast::ItemKind::Fn(box ast::Fn { ref sig, .. }) = i.kind {
// N.B., inadequate check, but we're running
// well before resolve, can't get too deep.
sig.decl.inputs.len() == 1
let decl = ecx.fn_decl(vec![], ast::FnRetTy::Ty(main_ret_ty));
let sig = ast::FnSig { decl, header: ast::FnHeader::default(), span: sp };
- let def = ast::Defaultness::Final;
- let main = ast::ItemKind::Fn(Box::new(ast::FnKind(
- def,
+ let defaultness = ast::Defaultness::Final;
+ let main = ast::ItemKind::Fn(Box::new(ast::Fn {
+ defaultness,
sig,
- ast::Generics::default(),
- Some(main_body),
- )));
+ generics: ast::Generics::default(),
+ body: Some(main_body),
+ }));
// Honor the reexport_test_harness_main attribute
let main_id = match cx.reexport_test_harness_main {
}
fn link_sanitizer_runtime(sess: &Session, linker: &mut dyn Linker, name: &str) {
- fn find_sanitizer_runtime(sess: &Session, filename: &String) -> PathBuf {
+ fn find_sanitizer_runtime(sess: &Session, filename: &str) -> PathBuf {
let session_tlib =
filesearch::make_target_lib_path(&sess.sysroot, sess.opts.target_triple.triple());
- let path = session_tlib.join(&filename);
+ let path = session_tlib.join(filename);
if path.exists() {
return session_tlib;
} else {
#[track_caller]
pub fn borrow(&self) -> MappedReadGuard<'_, T> {
let borrow = self.value.borrow();
- if let None = &*borrow {
+ if borrow.is_none() {
panic!("attempted to read from stolen value: {}", std::any::type_name::<T>());
}
ReadGuard::map(borrow, |opt| opt.as_ref().unwrap())
E0783: include_str!("./error_codes/E0783.md"),
E0784: include_str!("./error_codes/E0784.md"),
E0785: include_str!("./error_codes/E0785.md"),
+E0786: include_str!("./error_codes/E0786.md"),
;
// E0006, // merged with E0005
// E0008, // cannot bind by-move into a pattern guard
--- /dev/null
+A metadata file was invalid.
+
+Erroneous code example:
+
+```ignore (needs extern files)
+use ::foo; // error: found invalid metadata files for crate `foo`
+```
+
+When loading crates, each crate must have a valid metadata file.
+Invalid files could be caused by filesystem corruption,
+an IO error while reading the file, or (rarely) a bug in the compiler itself.
+
+Consider deleting the file and recreating it,
+or reporting a bug against the compiler.
let mut returned_async_output_error = false;
for &sp in values {
if sp.is_desugaring(DesugaringKind::Async) && !returned_async_output_error {
- if &[sp] != err.span.primary_spans() {
+ if [sp] != err.span.primary_spans() {
let mut span: MultiSpan = sp.into();
span.push_span_label(
sp,
use std::io::{self, BufWriter, Write};
use std::lazy::SyncLazy;
use std::marker::PhantomPinned;
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::pin::Pin;
use std::rc::Rc;
use std::{env, fs, iter};
None
}
-fn output_contains_path(output_paths: &[PathBuf], input_path: &PathBuf) -> bool {
+fn output_contains_path(output_paths: &[PathBuf], input_path: &Path) -> bool {
let input_path = input_path.canonicalize().ok();
if input_path.is_none() {
return false;
check_output(output_paths, check)
}
-fn escape_dep_filename(filename: &String) -> String {
+fn escape_dep_filename(filename: &str) -> String {
// Apparently clang and gcc *only* escape spaces:
// https://llvm.org/klaus/clang/commit/9d50634cfc268ecc9a7250226dd5ca0e945240d4
filename.replace(" ", "\\ ")
fn visit_item_kind(&mut self, i: &mut ast::ItemKind) {
let is_const = match i {
ast::ItemKind::Static(..) | ast::ItemKind::Const(..) => true,
- ast::ItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
+ ast::ItemKind::Fn(box ast::Fn { ref sig, .. }) => Self::is_sig_const(sig),
_ => false,
};
self.run(is_const, |s| noop_visit_item_kind(i, s))
fn flat_map_trait_item(&mut self, i: P<ast::AssocItem>) -> SmallVec<[P<ast::AssocItem>; 1]> {
let is_const = match i.kind {
ast::AssocItemKind::Const(..) => true,
- ast::AssocItemKind::Fn(box ast::FnKind(_, ref sig, _, _)) => Self::is_sig_const(sig),
+ ast::AssocItemKind::Fn(box ast::Fn { ref sig, .. }) => Self::is_sig_const(sig),
_ => false,
};
self.run(is_const, |s| noop_flat_map_assoc_item(i, s))
fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
match it.kind {
- ast::ItemKind::Trait(box ast::TraitKind(_, ast::Unsafe::Yes(_), ..)) => self
+ ast::ItemKind::Trait(box ast::Trait { unsafety: ast::Unsafe::Yes(_), .. }) => self
.report_unsafe(cx, it.span, |lint| {
lint.build("declaration of an `unsafe` trait").emit()
}),
- ast::ItemKind::Impl(box ast::ImplKind { unsafety: ast::Unsafe::Yes(_), .. }) => self
+ ast::ItemKind::Impl(box ast::Impl { unsafety: ast::Unsafe::Yes(_), .. }) => self
.report_unsafe(cx, it.span, |lint| {
lint.build("implementation of an `unsafe` trait").emit()
}),
// This is a hard error in future editions; avoid linting and erroring
return;
}
- if let ast::AssocItemKind::Fn(box FnKind(_, ref sig, _, _)) = it.kind {
+ if let ast::AssocItemKind::Fn(box Fn { ref sig, .. }) = it.kind {
for arg in sig.decl.inputs.iter() {
if let ast::PatKind::Ident(_, ident, None) = arg.pat.kind {
if ident.name == kw::Empty {
false
}
- if let rustc_hir::ExprKind::Unary(ref un_op, ref expr_deref) = expr.kind {
- if let rustc_hir::UnOp::Deref = un_op {
- if is_null_ptr(cx, expr_deref) {
- cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| {
- let mut err = lint.build("dereferencing a null pointer");
- err.span_label(
- expr.span,
- "this code causes undefined behavior when executed",
- );
- err.emit();
- });
- }
+ if let rustc_hir::ExprKind::Unary(rustc_hir::UnOp::Deref, expr_deref) = expr.kind {
+ if is_null_ptr(cx, expr_deref) {
+ cx.struct_span_lint(DEREF_NULLPTR, expr.span, |lint| {
+ let mut err = lint.build("dereferencing a null pointer");
+ err.span_label(expr.span, "this code causes undefined behavior when executed");
+ err.emit();
+ });
}
}
}
let snippet = template_snippet.as_str();
if let Some(pos) = snippet.find(needle) {
let end = pos
- + &snippet[pos..]
+ + snippet[pos..]
.find(|c| c == ':')
.unwrap_or(snippet[pos..].len() - 1);
let inner = InnerSpan::new(pos, end);
fn check_ty(&mut self, cx: &LateContext<'_>, ty: &'tcx Ty<'tcx>) {
match &ty.kind {
- TyKind::Path(qpath) => {
- if let QPath::Resolved(_, path) = qpath {
- if let Some(last) = path.segments.iter().last() {
- if lint_ty_kind_usage(cx, last) {
- cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
- lint.build("usage of `ty::TyKind`")
- .help("try using `Ty` instead")
- .emit();
- })
- } else {
- if ty.span.from_expansion() {
- return;
- }
- if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
- if path.segments.len() > 1 {
- cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
- lint.build(&format!("usage of qualified `ty::{}`", t))
- .span_suggestion(
- path.span,
- "try using it unqualified",
- t,
- // The import probably needs to be changed
- Applicability::MaybeIncorrect,
- )
- .emit();
- })
- }
+ TyKind::Path(QPath::Resolved(_, path)) => {
+ if let Some(last) = path.segments.iter().last() {
+ if lint_ty_kind_usage(cx, last) {
+ cx.struct_span_lint(USAGE_OF_TY_TYKIND, path.span, |lint| {
+ lint.build("usage of `ty::TyKind`")
+ .help("try using `Ty` instead")
+ .emit();
+ })
+ } else {
+ if ty.span.from_expansion() {
+ return;
+ }
+ if let Some(t) = is_ty_or_ty_ctxt(cx, ty) {
+ if path.segments.len() > 1 {
+ cx.struct_span_lint(USAGE_OF_QUALIFIED_TY, path.span, |lint| {
+ lint.build(&format!("usage of qualified `ty::{}`", t))
+ .span_suggestion(
+ path.span,
+ "try using it unqualified",
+ t,
+ // The import probably needs to be changed
+ Applicability::MaybeIncorrect,
+ )
+ .emit();
+ })
}
}
}
}
fn is_ty_or_ty_ctxt(cx: &LateContext<'_>, ty: &Ty<'_>) -> Option<String> {
- if let TyKind::Path(qpath) = &ty.kind {
- if let QPath::Resolved(_, path) = qpath {
- match path.res {
- Res::Def(_, def_id) => {
- if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id)
- {
- return Some(format!(
- "{}{}",
- name,
- gen_args(path.segments.last().unwrap())
- ));
- }
+ if let TyKind::Path(QPath::Resolved(_, path)) = &ty.kind {
+ match path.res {
+ Res::Def(_, def_id) => {
+ if let Some(name @ (sym::Ty | sym::TyCtxt)) = cx.tcx.get_diagnostic_name(def_id) {
+ return Some(format!("{}{}", name, gen_args(path.segments.last().unwrap())));
}
- // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
- Res::SelfTy(None, Some((did, _))) => {
- if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
- if let Some(name @ (sym::Ty | sym::TyCtxt)) =
- cx.tcx.get_diagnostic_name(adt.did)
- {
- // NOTE: This path is currently unreachable as `Ty<'tcx>` is
- // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
- // is not actually allowed.
- //
- // I(@lcnr) still kept this branch in so we don't miss this
- // if we ever change it in the future.
- return Some(format!("{}<{}>", name, substs[0]));
- }
+ }
+ // Only lint on `&Ty` and `&TyCtxt` if it is used outside of a trait.
+ Res::SelfTy(None, Some((did, _))) => {
+ if let ty::Adt(adt, substs) = cx.tcx.type_of(did).kind() {
+ if let Some(name @ (sym::Ty | sym::TyCtxt)) =
+ cx.tcx.get_diagnostic_name(adt.did)
+ {
+ // NOTE: This path is currently unreachable as `Ty<'tcx>` is
+ // defined as a type alias meaning that `impl<'tcx> Ty<'tcx>`
+ // is not actually allowed.
+ //
+ // I(@lcnr) still kept this branch in so we don't miss this
+ // if we ever change it in the future.
+ return Some(format!("{}<{}>", name, substs[0]));
}
}
- _ => (),
}
+ _ => (),
}
}
impl EarlyLintPass for LintPassImpl {
fn check_item(&mut self, cx: &EarlyContext<'_>, item: &ast::Item) {
- if let ast::ItemKind::Impl(box ast::ImplKind { of_trait: Some(lint_pass), .. }) = &item.kind
- {
+ if let ast::ItemKind::Impl(box ast::Impl { of_trait: Some(lint_pass), .. }) = &item.kind {
if let Some(last) = lint_pass.path.segments.last() {
if last.ident.name == sym::LintPass {
let expn_data = lint_pass.path.span.ctxt().outer_expn_data();
}
if meta.path().is_ident("project") {
if let Meta::List(list) = meta {
- if let Some(nested) = list.nested.iter().next() {
- if let NestedMeta::Meta(meta) = nested {
- attrs.project = meta.path().get_ident().cloned();
- any_attr = true;
- }
+ if let Some(NestedMeta::Meta(meta)) = list.nested.iter().next() {
+ attrs.project = meta.path().get_ident().cloned();
+ any_attr = true;
}
}
}
use proc_macro::bridge::client::ProcMacro;
use std::collections::BTreeMap;
+use std::ops::Fn;
use std::path::Path;
use std::{cmp, env};
use tracing::{debug, info};
self.crate_rejections.via_kind.clear();
self.crate_rejections.via_version.clear();
self.crate_rejections.via_filename.clear();
+ self.crate_rejections.via_invalid.clear();
}
crate fn maybe_load_library_crate(&mut self) -> Result<Option<Library>, CrateError> {
continue;
}
}
- Err(err) => {
+ Err(MetadataError::LoadFailure(err)) => {
+ info!("no metadata found: {}", err);
+ // The file was present and created by the same compiler version, but we
+ // couldn't load it for some reason. Give a hard error instead of silently
+ // ignoring it, but only if we would have given an error anyway.
+ self.crate_rejections
+ .via_invalid
+ .push(CrateMismatch { path: lib, got: err });
+ continue;
+ }
+ Err(err @ MetadataError::NotPresent(_)) => {
info!("no metadata found: {}", err);
continue;
}
fn get_metadata_section(
target: &Target,
flavor: CrateFlavor,
- filename: &Path,
+ filename: &'p Path,
loader: &dyn MetadataLoader,
-) -> Result<MetadataBlob, String> {
+) -> Result<MetadataBlob, MetadataError<'p>> {
if !filename.exists() {
- return Err(format!("no such file: '{}'", filename.display()));
+ return Err(MetadataError::NotPresent(filename));
}
let raw_bytes: MetadataRef = match flavor {
- CrateFlavor::Rlib => loader.get_rlib_metadata(target, filename)?,
+ CrateFlavor::Rlib => {
+ loader.get_rlib_metadata(target, filename).map_err(MetadataError::LoadFailure)?
+ }
CrateFlavor::Dylib => {
- let buf = loader.get_dylib_metadata(target, filename)?;
+ let buf =
+ loader.get_dylib_metadata(target, filename).map_err(MetadataError::LoadFailure)?;
// The header is uncompressed
let header_len = METADATA_HEADER.len();
debug!("checking {} bytes of metadata-version stamp", header_len);
let header = &buf[..cmp::min(header_len, buf.len())];
if header != METADATA_HEADER {
- return Err(format!(
- "incompatible metadata version found: '{}'",
+ return Err(MetadataError::LoadFailure(format!(
+ "invalid metadata version found: {}",
filename.display()
- ));
+ )));
}
// Header is okay -> inflate the actual metadata
match FrameDecoder::new(compressed_bytes).read_to_end(&mut inflated) {
Ok(_) => rustc_erase_owner!(OwningRef::new(inflated).map_owner_box()),
Err(_) => {
- return Err(format!("failed to decompress metadata: {}", filename.display()));
+ return Err(MetadataError::LoadFailure(format!(
+ "failed to decompress metadata: {}",
+ filename.display()
+ )));
}
}
}
CrateFlavor::Rmeta => {
// mmap the file, because only a small fraction of it is read.
- let file = std::fs::File::open(filename)
- .map_err(|_| format!("failed to open rmeta metadata: '{}'", filename.display()))?;
+ let file = std::fs::File::open(filename).map_err(|_| {
+ MetadataError::LoadFailure(format!(
+ "failed to open rmeta metadata: '{}'",
+ filename.display()
+ ))
+ })?;
let mmap = unsafe { Mmap::map(file) };
- let mmap = mmap
- .map_err(|_| format!("failed to mmap rmeta metadata: '{}'", filename.display()))?;
+ let mmap = mmap.map_err(|_| {
+ MetadataError::LoadFailure(format!(
+ "failed to mmap rmeta metadata: '{}'",
+ filename.display()
+ ))
+ })?;
rustc_erase_owner!(OwningRef::new(mmap).map_owner_box())
}
if blob.is_compatible() {
Ok(blob)
} else {
- Err(format!("incompatible metadata version found: '{}'", filename.display()))
+ Err(MetadataError::LoadFailure(format!(
+ "invalid metadata version found: {}",
+ filename.display()
+ )))
}
}
via_kind: Vec<CrateMismatch>,
via_version: Vec<CrateMismatch>,
via_filename: Vec<CrateMismatch>,
+ via_invalid: Vec<CrateMismatch>,
}
/// Candidate rejection reasons collected during crate search.
NonDylibPlugin(Symbol),
}
+enum MetadataError<'a> {
+ /// The file was missing.
+ NotPresent(&'a Path),
+ /// The file was present and invalid.
+ LoadFailure(String),
+}
+
+impl fmt::Display for MetadataError<'_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ MetadataError::NotPresent(filename) => {
+ f.write_str(&format!("no such file: '{}'", filename.display()))
+ }
+ MetadataError::LoadFailure(msg) => f.write_str(msg),
+ }
+ }
+}
+
impl CrateError {
crate fn report(self, sess: &Session, span: Span, missing_core: bool) -> ! {
let mut err = match self {
}
err.note(&msg);
err
+ } else if !locator.crate_rejections.via_invalid.is_empty() {
+ let mut err = struct_span_err!(
+ sess,
+ span,
+ E0786,
+ "found invalid metadata files for crate `{}`{}",
+ crate_name,
+ add,
+ );
+ for CrateMismatch { path: _, got } in locator.crate_rejections.via_invalid {
+ err.note(&got);
+ }
+ err
} else {
let mut err = struct_span_err!(
sess,
.libs
.iter()
.filter_map(|lib| lib.name.as_ref())
- .any(|n| &n.as_str() == &lib.name);
+ .any(|n| n.as_str() == lib.name);
if new_name.is_empty() {
self.tcx.sess.err(&format!(
"an empty renaming target was specified for library `{}`",
} else if self.check_fn_front_matter(def_final) {
// FUNCTION ITEM
let (ident, sig, generics, body) = self.parse_fn(attrs, req_name, lo)?;
- (ident, ItemKind::Fn(Box::new(FnKind(def(), sig, generics, body))))
+ (ident, ItemKind::Fn(Box::new(Fn { defaultness: def(), sig, generics, body })))
} else if self.eat_keyword(kw::Extern) {
if self.eat_keyword(kw::Crate) {
// EXTERN CRATE
};
let trait_ref = TraitRef { path, ref_id: ty_first.id };
- ItemKind::Impl(Box::new(ImplKind {
+ ItemKind::Impl(Box::new(Impl {
unsafety,
polarity,
defaultness,
}
None => {
// impl Type
- ItemKind::Impl(Box::new(ImplKind {
+ ItemKind::Impl(Box::new(Impl {
unsafety,
polarity,
defaultness,
self.expect_keyword(kw::Trait)?;
let ident = self.parse_ident()?;
- let mut tps = self.parse_generics()?;
+ let mut generics = self.parse_generics()?;
// Parse optional colon and supertrait bounds.
let had_colon = self.eat(&token::Colon);
}
let bounds = self.parse_generic_bounds(None)?;
- tps.where_clause = self.parse_where_clause()?;
+ generics.where_clause = self.parse_where_clause()?;
self.expect_semi()?;
let whole_span = lo.to(self.prev_token.span);
self.sess.gated_spans.gate(sym::trait_alias, whole_span);
- Ok((ident, ItemKind::TraitAlias(tps, bounds)))
+ Ok((ident, ItemKind::TraitAlias(generics, bounds)))
} else {
// It's a normal trait.
- tps.where_clause = self.parse_where_clause()?;
+ generics.where_clause = self.parse_where_clause()?;
let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
- Ok((ident, ItemKind::Trait(Box::new(TraitKind(is_auto, unsafety, tps, bounds, items)))))
+ Ok((
+ ident,
+ ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })),
+ ))
}
}
/// TypeAlias = "type" Ident Generics {":" GenericBounds}? {"=" Ty}? ";" ;
/// ```
/// The `"type"` has already been eaten.
- fn parse_type_alias(&mut self, def: Defaultness) -> PResult<'a, ItemInfo> {
+ fn parse_type_alias(&mut self, defaultness: Defaultness) -> PResult<'a, ItemInfo> {
let ident = self.parse_ident()?;
let mut generics = self.parse_generics()?;
if self.eat(&token::Colon) { self.parse_generic_bounds(None)? } else { Vec::new() };
generics.where_clause = self.parse_where_clause()?;
- let default = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
+ let ty = if self.eat(&token::Eq) { Some(self.parse_ty()?) } else { None };
self.expect_semi()?;
- Ok((ident, ItemKind::TyAlias(Box::new(TyAliasKind(def, generics, bounds, default)))))
+ Ok((ident, ItemKind::TyAlias(Box::new(TyAlias { defaultness, generics, bounds, ty }))))
}
/// Parses a `UseTree`.
};
match impl_info.1 {
- ItemKind::Impl(box ImplKind {
- of_trait: Some(ref trai), ref mut constness, ..
- }) => {
+ ItemKind::Impl(box Impl { of_trait: Some(ref trai), ref mut constness, .. }) => {
*constness = Const::Yes(const_span);
let before_trait = trai.path.span.shrink_to_lo();
required_gates.iter().copied().filter(|&g| !features.enabled(g)).collect();
match missing_gates.as_slice() {
- &[] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),
+ [] => struct_span_err!(tcx.sess, span, E0744, "{}", msg).emit(),
- &[missing_primary, ref missing_secondary @ ..] => {
- let mut err = feature_err(&tcx.sess.parse_sess, missing_primary, span, &msg);
+ [missing_primary, ref missing_secondary @ ..] => {
+ let mut err = feature_err(&tcx.sess.parse_sess, *missing_primary, span, &msg);
// If multiple feature gates would be required to enable this expression, include
// them as help messages. Don't emit a separate error for each missing feature gate.
prof_timer.finish_with_query_invocation_id(dep_node_index.into());
if let Some(result) = result {
+ let prev_fingerprint = tcx
+ .dep_context()
+ .dep_graph()
+ .prev_fingerprint_of(dep_node)
+ .unwrap_or(Fingerprint::ZERO);
// If `-Zincremental-verify-ich` is specified, re-hash results from
// the cache and make sure that they have the expected fingerprint.
- if unlikely!(tcx.dep_context().sess().opts.debugging_opts.incremental_verify_ich) {
+ //
+ // If not, we still seek to verify a subset of fingerprints loaded
+ // from disk. Re-hashing results is fairly expensive, so we can't
+ // currently afford to verify every hash. This subset should still
+ // give us some coverage of potential bugs though.
+ let try_verify = prev_fingerprint.as_value().1 % 32 == 0;
+ if unlikely!(
+ try_verify || tcx.dep_context().sess().opts.debugging_opts.incremental_verify_ich
+ ) {
incremental_verify_ich(*tcx.dep_context(), &result, dep_node, query);
}
use rustc_ast::visit::{self, AssocCtxt, Visitor};
use rustc_ast::{self as ast, AssocItem, AssocItemKind, MetaItemKind, StmtKind};
-use rustc_ast::{Block, FnKind, ForeignItem, ForeignItemKind, ImplKind, Item, ItemKind, NodeId};
+use rustc_ast::{Block, Fn, ForeignItem, ForeignItemKind, Impl, Item, ItemKind, NodeId};
use rustc_ast_lowering::ResolverAstLowering;
use rustc_attr as attr;
use rustc_data_structures::sync::Lrc;
}
// These items do not add names to modules.
- ItemKind::Impl(box ImplKind { of_trait: Some(..), .. }) => {
+ ItemKind::Impl(box Impl { of_trait: Some(..), .. }) => {
self.r.trait_impl_items.insert(local_def_id);
}
ItemKind::Impl { .. } | ItemKind::ForeignMod(..) | ItemKind::GlobalAsm(..) => {}
if ctxt == AssocCtxt::Trait {
let (def_kind, ns) = match item.kind {
AssocItemKind::Const(..) => (DefKind::AssocConst, ValueNS),
- AssocItemKind::Fn(box FnKind(_, ref sig, _, _)) => {
+ AssocItemKind::Fn(box Fn { ref sig, .. }) => {
if sig.decl.has_self() {
self.r.has_self.insert(def_id);
}
}
fn visit_foreign_item(&mut self, foreign_item: &'ast ForeignItem) {
match foreign_item.kind {
- ForeignItemKind::Fn(box FnKind(_, _, ref generics, _))
- | ForeignItemKind::TyAlias(box TyAliasKind(_, ref generics, ..)) => {
+ ForeignItemKind::Fn(box Fn { ref generics, .. })
+ | ForeignItemKind::TyAlias(box TyAlias { ref generics, .. }) => {
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_foreign_item(this, foreign_item);
});
debug!("(resolving item) resolving {} ({:?})", name, item.kind);
match item.kind {
- ItemKind::TyAlias(box TyAliasKind(_, ref generics, _, _))
- | ItemKind::Fn(box FnKind(_, _, ref generics, _)) => {
+ ItemKind::TyAlias(box TyAlias { ref generics, .. })
+ | ItemKind::Fn(box Fn { ref generics, .. }) => {
self.compute_num_lifetime_params(item.id, generics);
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
visit::walk_item(this, item)
self.resolve_adt(item, generics);
}
- ItemKind::Impl(box ImplKind {
+ ItemKind::Impl(box Impl {
ref generics,
ref of_trait,
ref self_ty,
self.resolve_implementation(generics, of_trait, &self_ty, item.id, impl_items);
}
- ItemKind::Trait(box TraitKind(.., ref generics, ref bounds, ref trait_items)) => {
+ ItemKind::Trait(box Trait { ref generics, ref bounds, ref items, .. }) => {
self.compute_num_lifetime_params(item.id, generics);
// Create a new rib for the trait-wide type parameters.
self.with_generic_param_rib(generics, ItemRibKind(HasGenericParams::Yes), |this| {
});
};
- this.with_trait_items(trait_items, |this| {
- for item in trait_items {
+ this.with_trait_items(items, |this| {
+ for item in items {
match &item.kind {
AssocItemKind::Const(_, ty, default) => {
this.visit_ty(ty);
);
}
}
- AssocItemKind::Fn(box FnKind(_, _, generics, _)) => {
+ AssocItemKind::Fn(box Fn { generics, .. }) => {
walk_assoc_item(this, generics, item);
}
- AssocItemKind::TyAlias(box TyAliasKind(_, generics, _, _)) => {
+ AssocItemKind::TyAlias(box TyAlias { generics, .. }) => {
walk_assoc_item(this, generics, item);
}
AssocItemKind::MacCall(_) => {
},
);
}
- AssocItemKind::Fn(box FnKind(.., generics, _)) => {
+ AssocItemKind::Fn(box Fn { generics, .. }) => {
debug!("resolve_implementation AssocItemKind::Fn");
// We also need a new scope for the impl item type parameters.
this.with_generic_param_rib(
},
);
}
- AssocItemKind::TyAlias(box TyAliasKind(
- _,
- generics,
- _,
- _,
- )) => {
+ AssocItemKind::TyAlias(box TyAlias {
+ generics, ..
+ }) => {
debug!("resolve_implementation AssocItemKind::TyAlias");
// We also need a new scope for the impl item type parameters.
this.with_generic_param_rib(
if assoc_item.ident == ident {
return Some(match &assoc_item.kind {
ast::AssocItemKind::Const(..) => AssocSuggestion::AssocConst,
- ast::AssocItemKind::Fn(box ast::FnKind(_, sig, ..))
- if sig.decl.has_self() =>
- {
+ ast::AssocItemKind::Fn(box ast::Fn { sig, .. }) if sig.decl.has_self() => {
AssocSuggestion::MethodWithSelf
}
ast::AssocItemKind::Fn(..) => AssocSuggestion::AssocFn,
} else {
// Search in module.
let mod_path = &path[..path.len() - 1];
- if let PathResult::Module(module) =
+ if let PathResult::Module(ModuleOrUniformRoot::Module(module)) =
self.resolve_path(mod_path, Some(TypeNS), false, span, CrateLint::No)
{
- if let ModuleOrUniformRoot::Module(module) = module {
- self.r.add_module_candidates(module, &mut names, &filter_fn);
- }
+ self.r.add_module_candidates(module, &mut names, &filter_fn);
}
}
let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) = c
.generic_params
.iter()
- .filter_map(|param| match param.kind {
- GenericParamKind::Lifetime { .. } => Some(param),
- _ => None,
- })
+ .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
.enumerate()
.map(|(late_bound_idx, param)| {
let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
let (lifetimes, binders): (FxIndexMap<hir::ParamName, Region>, Vec<_>) =
bound_generic_params
.iter()
- .filter_map(|param| match param.kind {
- GenericParamKind::Lifetime { .. } => Some(param),
- _ => None,
+ .filter(|param| {
+ matches!(param.kind, GenericParamKind::Lifetime { .. })
})
.enumerate()
.map(|(late_bound_idx, param)| {
let binders_iter = trait_ref
.bound_generic_params
.iter()
- .filter_map(|param| match param.kind {
- GenericParamKind::Lifetime { .. } => Some(param),
- _ => None,
- })
+ .filter(|param| matches!(param.kind, GenericParamKind::Lifetime { .. }))
.enumerate()
.map(|(late_bound_idx, param)| {
let pair = Region::late(
break;
}
}
- hir::TyKind::Path(ref qpath) => {
- if let QPath::Resolved(_, path) = qpath {
- let last_segment = &path.segments[path.segments.len() - 1];
- let generics = last_segment.args();
- for arg in generics.args.iter() {
- if let GenericArg::Lifetime(lt) = arg {
- if lt.name.ident() == name {
- elide_use = Some(lt.span);
- break;
- }
+ hir::TyKind::Path(QPath::Resolved(_, path)) => {
+ let last_segment = &path.segments[path.segments.len() - 1];
+ let generics = last_segment.args();
+ for arg in generics.args.iter() {
+ if let GenericArg::Lifetime(lt) = arg {
+ if lt.name.ident() == name {
+ elide_use = Some(lt.span);
+ break;
}
}
- break;
}
+ break;
}
_ => {}
}
let binders: Vec<_> = generics
.params
.iter()
- .filter_map(|param| match param.kind {
- GenericParamKind::Lifetime { .. }
- if self.map.late_bound.contains(¶m.hir_id) =>
- {
- Some(param)
- }
- _ => None,
+ .filter(|param| {
+ matches!(param.kind, GenericParamKind::Lifetime { .. })
+ && self.map.late_bound.contains(¶m.hir_id)
})
.enumerate()
.map(|(late_bound_idx, param)| {
let pair = Region::late(late_bound_idx as u32, &self.tcx.hir(), param);
- let r = late_region_as_bound_region(self.tcx, &pair.1);
- r
+ late_region_as_bound_region(self.tcx, &pair.1)
})
.collect();
self.map.late_bound_vars.insert(hir_id, binders);
pub(super) fn build_target_config(
opts: &Options,
target_override: Option<Target>,
- sysroot: &PathBuf,
+ sysroot: &Path,
) -> Target {
let target_result = target_override.map_or_else(
|| Target::search(&opts.target_triple, sysroot),
match v {
Some(s) => {
if !slot.is_empty() {
- slot.push_str(",");
+ slot.push(',');
}
slot.push_str(s);
true
encoder.emit_enum(|encoder| match *self {
RealFileName::LocalPath(ref local_path) => {
encoder.emit_enum_variant("LocalPath", 0, 1, |encoder| {
- Ok({
- encoder
- .emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
- })
+ encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
+ Ok(())
})
}
// For privacy and build reproducibility, we must not embed host-dependant path in artifacts
// if they have been remapped by --remap-path-prefix
assert!(local_path.is_none());
- Ok({
- encoder
- .emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
- encoder
- .emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
- })
+ encoder.emit_enum_variant_arg(true, |encoder| local_path.encode(encoder))?;
+ encoder.emit_enum_variant_arg(false, |encoder| virtual_name.encode(encoder))?;
+ Ok(())
}),
})
}
__S,
__next,
__try_var,
+ _args,
_d,
_e,
_task_context,
-use crate::spec::{LinkArgs, LinkerFlavor, PanicStrategy, RelocModel, Target, TargetOptions};
+use crate::spec::{LinkArgs, LinkerFlavor, RelocModel, Target, TargetOptions};
/// A base target for Nintendo 3DS devices using the devkitARM toolchain.
///
features: "+vfp2".to_string(),
pre_link_args,
exe_suffix: ".elf".to_string(),
- panic_strategy: PanicStrategy::Abort,
..Default::default()
},
}
/// JSON decoding.
pub fn search(
target_triple: &TargetTriple,
- sysroot: &PathBuf,
+ sysroot: &Path,
) -> Result<(Target, TargetWarnings), String> {
use rustc_serialize::json;
use std::env;
let sized_trait = self.tcx.lang_items().sized_trait();
debug!("maybe_suggest_unsized_generics: generics.params={:?}", generics.params);
debug!("maybe_suggest_unsized_generics: generics.where_clause={:?}", generics.where_clause);
- let param = generics
- .params
- .iter()
- .filter(|param| param.span == span)
- .filter(|param| {
- // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
- // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
- param
- .bounds
- .iter()
- .all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
- })
- .next();
+ let param = generics.params.iter().filter(|param| param.span == span).find(|param| {
+ // Check that none of the explicit trait bounds is `Sized`. Assume that an explicit
+ // `Sized` bound is there intentionally and we don't need to suggest relaxing it.
+ param
+ .bounds
+ .iter()
+ .all(|bound| bound.trait_ref().and_then(|tr| tr.trait_def_id()) != sized_trait)
+ });
let param = match param {
Some(param) => param,
_ => return,
(&ty::Str, &ty::Array(arr, _) | &ty::Slice(arr)) if arr == self.tcx.types.u8 => {
if let hir::ExprKind::Lit(_) = expr.kind {
if let Ok(src) = sm.span_to_snippet(sp) {
- if let Some(_) = replace_prefix(&src, "b\"", "\"") {
+ if replace_prefix(&src, "b\"", "\"").is_some() {
let pos = sp.lo() + BytePos(1);
return Some((
sp.with_hi(pos),
(&ty::Array(arr, _) | &ty::Slice(arr), &ty::Str) if arr == self.tcx.types.u8 => {
if let hir::ExprKind::Lit(_) = expr.kind {
if let Ok(src) = sm.span_to_snippet(sp) {
- if let Some(_) = replace_prefix(&src, "\"", "b\"") {
+ if replace_prefix(&src, "\"", "b\"").is_some() {
return Some((
sp.shrink_to_lo(),
"consider adding a leading `b`",
) -> Option<(&Vec<ty::FieldDef>, SubstsRef<'tcx>)> {
debug!("get_field_candidates(span: {:?}, base_t: {:?}", span, base_t);
- let mut autoderef = self.autoderef(span, base_t);
- while let Some((base_t, _)) = autoderef.next() {
+ for (base_t, _) in self.autoderef(span, base_t) {
match base_t.kind() {
ty::Adt(base_def, substs) if !base_def.is_enum() => {
let fields = &base_def.non_enum_variant().fields;
.type_var_origin(ty)
.map(|origin| origin.span)
.unwrap_or(rustc_span::DUMMY_SP);
- let oty = self.inner.borrow().opaque_types_vars.get(ty).map(|v| *v);
+ let oty = self.inner.borrow().opaque_types_vars.get(ty).copied();
if let Some(opaque_ty) = oty {
debug!(
"fallback_opaque_type_vars(ty={:?}): falling back to opaque type {:?}",
call_expr: &'tcx hir::Expr<'tcx>,
) {
if let hir::ExprKind::Call(path, _) = &call_expr.kind {
- if let hir::ExprKind::Path(qpath) = &path.kind {
- if let hir::QPath::Resolved(_, path) = &qpath {
- for error in errors {
- if let ty::PredicateKind::Trait(predicate) =
- error.obligation.predicate.kind().skip_binder()
+ if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = &path.kind {
+ for error in errors {
+ if let ty::PredicateKind::Trait(predicate) =
+ error.obligation.predicate.kind().skip_binder()
+ {
+ // If any of the type arguments in this path segment caused the
+ // `FulfillmentError`, point at its span (#61860).
+ for arg in path
+ .segments
+ .iter()
+ .filter_map(|seg| seg.args.as_ref())
+ .flat_map(|a| a.args.iter())
{
- // If any of the type arguments in this path segment caused the
- // `FulfillmentError`, point at its span (#61860).
- for arg in path
- .segments
- .iter()
- .filter_map(|seg| seg.args.as_ref())
- .flat_map(|a| a.args.iter())
- {
- if let hir::GenericArg::Type(hir_ty) = &arg {
- if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) =
- &hir_ty.kind
- {
- // Avoid ICE with associated types. As this is best
- // effort only, it's ok to ignore the case. It
- // would trigger in `is_send::<T::AssocType>();`
- // from `typeck-default-trait-impl-assoc-type.rs`.
- } else {
- let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, hir_ty);
- let ty = self.resolve_vars_if_possible(ty);
- if ty == predicate.self_ty() {
- error.obligation.cause.make_mut().span = hir_ty.span;
- }
+ if let hir::GenericArg::Type(hir_ty) = &arg {
+ if let hir::TyKind::Path(hir::QPath::TypeRelative(..)) =
+ &hir_ty.kind
+ {
+ // Avoid ICE with associated types. As this is best
+ // effort only, it's ok to ignore the case. It
+ // would trigger in `is_send::<T::AssocType>();`
+ // from `typeck-default-trait-impl-assoc-type.rs`.
+ } else {
+ let ty = <dyn AstConv<'_>>::ast_ty_to_ty(self, hir_ty);
+ let ty = self.resolve_vars_if_possible(ty);
+ if ty == predicate.self_ty() {
+ error.obligation.cause.make_mut().span = hir_ty.span;
}
}
}
let edition_fix = candidates
.iter()
.find(|did| self.tcx.is_diagnostic_item(sym::TryInto, **did))
- .map(|&d| d);
+ .copied();
err.help("items from traits can only be used if the trait is in scope");
let msg = format!(
}
};
if let Ref(_, rty, _) = lhs_ty.kind() {
- if {
- self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span)
- && self
- .lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign))
- .is_ok()
- } {
+ if self.infcx.type_is_copy_modulo_regions(self.param_env, rty, lhs_expr.span)
+ && self.lookup_op_method(rty, &[rhs_ty], Op::Binary(op, is_assign)).is_ok()
+ {
if let Ok(lstring) = source_map.span_to_snippet(lhs_expr.span) {
let msg = &format!(
"`{}{}` can be used on `{}`, you can dereference `{}`",
let written_predicates: ty::GenericPredicates<'_> =
tcx.explicit_predicates_of(trait_item.def_id);
let mut clauses: Vec<_> = clauses
- .drain_filter(|clause| {
- written_predicates.predicates.iter().find(|p| &p.0 == clause).is_none()
- })
+ .drain_filter(|clause| !written_predicates.predicates.iter().any(|p| &p.0 == clause))
.map(|clause| format!("{}", clause))
.collect();
// We sort so that order is predictable
let coerced_fields = fields
.iter()
- .filter_map(|field| {
+ .filter(|field| {
let ty_a = field.ty(tcx, substs_a);
let ty_b = field.ty(tcx, substs_b);
if let Ok(layout) = tcx.layout_of(param_env.and(ty_a)) {
if layout.is_zst() && layout.align.abi.bytes() == 1 {
// ignore ZST fields with alignment of 1 byte
- return None;
+ return false;
}
}
))
.emit();
- return None;
+ return false;
}
}
- Some(field)
+ return true;
})
.collect::<Vec<_>>();
-Subproject commit 7f14f76c8ba6945c052fab77022e6e768b58e0b4
+Subproject commit b02ed04a7e915659eea6fb1607df469b84a30638
target_os = "solaris",
target_os = "illumos",
))] {
+ #[cfg(any(target_os = "android", target_os = "linux"))]
+ {
+ let mut set: libc::cpu_set_t = unsafe { mem::zeroed() };
+ if unsafe { libc::sched_getaffinity(0, mem::size_of::<libc::cpu_set_t>(), &mut set) } == 0 {
+ let count = unsafe { libc::CPU_COUNT(&set) };
+ return Ok(unsafe { NonZeroUsize::new_unchecked(count as usize) });
+ }
+ }
match unsafe { libc::sysconf(libc::_SC_NPROCESSORS_ONLN) } {
-1 => Err(io::Error::last_os_error()),
0 => Err(io::Error::new_const(io::ErrorKind::NotFound, &"The number of hardware threads is not known for the target platform")),
new_generics
});
- let negative_polarity;
+ let polarity;
let new_generics = match result {
AutoTraitResult::PositiveImpl(new_generics) => {
- negative_polarity = false;
+ polarity = ty::ImplPolarity::Positive;
if discard_positive_impl {
return None;
}
new_generics
}
AutoTraitResult::NegativeImpl => {
- negative_polarity = true;
+ polarity = ty::ImplPolarity::Negative;
// For negative impls, we use the generic params, but *not* the predicates,
// from the original type. Otherwise, the displayed impl appears to be a
visibility: Inherited,
def_id: ItemId::Auto { trait_: trait_def_id, for_: item_def_id },
kind: box ImplItem(Impl {
- span: Span::dummy(),
unsafety: hir::Unsafety::Normal,
generics: new_generics,
trait_: Some(trait_ref.clean(self.cx)),
for_: ty.clean(self.cx),
items: Vec::new(),
- negative_polarity,
- synthetic: true,
- blanket_impl: None,
+ polarity,
+ kind: ImplKind::Auto,
}),
cfg: None,
})
visibility: Inherited,
def_id: ItemId::Blanket { impl_id: impl_def_id, for_: item_def_id },
kind: box ImplItem(Impl {
- span: Span::new(self.cx.tcx.def_span(impl_def_id)),
unsafety: hir::Unsafety::Normal,
generics: (
self.cx.tcx.generics_of(impl_def_id),
.tcx
.associated_items(impl_def_id)
.in_definition_order()
- .collect::<Vec<_>>()
- .clean(self.cx),
- negative_polarity: false,
- synthetic: false,
- blanket_impl: Some(box trait_ref.self_ty().clean(self.cx)),
+ .map(|x| x.clean(self.cx))
+ .collect::<Vec<_>>(),
+ polarity: ty::ImplPolarity::Positive,
+ kind: ImplKind::Blanket(box trait_ref.self_ty().clean(self.cx)),
}),
cfg: None,
});
use rustc_span::hygiene::MacroKind;
use rustc_span::symbol::{kw, sym, Symbol};
-use crate::clean::{self, utils, Attributes, AttributesExt, ItemId, NestedAttributesExt, Type};
+use crate::clean::{
+ self, utils, Attributes, AttributesExt, ImplKind, ItemId, NestedAttributesExt, Type,
+};
use crate::core::DocContext;
use crate::formats::item_type::ItemType;
clean::Enum {
generics: (cx.tcx.generics_of(did), predicates).clean(cx),
variants_stripped: false,
- variants: cx.tcx.adt_def(did).variants.clean(cx),
+ variants: cx.tcx.adt_def(did).variants.iter().map(|v| v.clean(cx)).collect(),
}
}
clean::Struct {
struct_type: variant.ctor_kind,
generics: (cx.tcx.generics_of(did), predicates).clean(cx),
- fields: variant.fields.clean(cx),
+ fields: variant.fields.iter().map(|x| x.clean(cx)).collect(),
fields_stripped: false,
}
}
let predicates = cx.tcx.explicit_predicates_of(did);
let variant = cx.tcx.adt_def(did).non_enum_variant();
- clean::Union {
- generics: (cx.tcx.generics_of(did), predicates).clean(cx),
- fields: variant.fields.clean(cx),
- fields_stripped: false,
- }
+ let generics = (cx.tcx.generics_of(did), predicates).clean(cx);
+ let fields = variant.fields.iter().map(|x| x.clean(cx)).collect();
+ clean::Union { generics, fields, fields_stripped: false }
}
fn build_type_alias(cx: &mut DocContext<'_>, did: DefId) -> clean::Typedef {
),
};
let polarity = tcx.impl_polarity(did);
- let trait_ = associated_trait.clean(cx);
+ let trait_ = associated_trait.map(|t| t.clean(cx));
if trait_.as_ref().map(|t| t.def_id()) == tcx.lang_items().deref_trait() {
super::build_deref_target_impls(cx, &trait_items, ret);
}
did,
None,
clean::ImplItem(clean::Impl {
- span: clean::types::rustc_span(did, cx.tcx),
unsafety: hir::Unsafety::Normal,
generics,
trait_,
for_,
items: trait_items,
- negative_polarity: polarity.clean(cx),
- synthetic: false,
- blanket_impl: None,
+ polarity,
+ kind: ImplKind::Normal,
}),
box merged_attrs,
cx,
use rustc_hir as hir;
use rustc_hir::def::{CtorKind, DefKind, Res};
use rustc_hir::def_id::{DefId, CRATE_DEF_INDEX, LOCAL_CRATE};
-use rustc_index::vec::{Idx, IndexVec};
use rustc_infer::infer::region_constraints::{Constraint, RegionConstraintData};
use rustc_middle::middle::resolve_lifetime as rl;
use rustc_middle::ty::fold::TypeFolder;
use std::collections::hash_map::Entry;
use std::default::Default;
use std::hash::Hash;
-use std::rc::Rc;
use std::{mem, vec};
use crate::core::{self, DocContext, ImplTraitParam};
fn clean(&self, cx: &mut DocContext<'_>) -> T;
}
-impl<T: Clean<U>, U> Clean<Vec<U>> for [T] {
- fn clean(&self, cx: &mut DocContext<'_>) -> Vec<U> {
- self.iter().map(|x| x.clean(cx)).collect()
- }
-}
-
-impl<T: Clean<U>, U, V: Idx> Clean<IndexVec<V, U>> for IndexVec<V, T> {
- fn clean(&self, cx: &mut DocContext<'_>) -> IndexVec<V, U> {
- self.iter().map(|x| x.clean(cx)).collect()
- }
-}
-
-impl<T: Clean<U>, U> Clean<U> for &T {
- fn clean(&self, cx: &mut DocContext<'_>) -> U {
- (**self).clean(cx)
- }
-}
-
-impl<T: Clean<U>, U> Clean<U> for Rc<T> {
- fn clean(&self, cx: &mut DocContext<'_>) -> U {
- (**self).clean(cx)
- }
-}
-
-impl<T: Clean<U>, U> Clean<Option<U>> for Option<T> {
- fn clean(&self, cx: &mut DocContext<'_>) -> Option<U> {
- self.as_ref().map(|v| v.clean(cx))
- }
-}
-
impl Clean<Item> for doctree::Module<'_> {
fn clean(&self, cx: &mut DocContext<'_>) -> Item {
let mut items: Vec<Item> = vec![];
| rl::Region::Free(_, node_id),
) = def
{
- if let Some(lt) = cx.lt_substs.get(&node_id).cloned() {
+ if let Some(lt) = cx.substs.get(&node_id).and_then(|p| p.as_lt()).cloned() {
return lt;
}
}
.collect();
WherePredicate::BoundPredicate {
ty: wbp.bounded_ty.clean(cx),
- bounds: wbp.bounds.clean(cx),
+ bounds: wbp.bounds.iter().map(|x| x.clean(cx)).collect(),
bound_params,
}
}
hir::WherePredicate::RegionPredicate(ref wrp) => WherePredicate::RegionPredicate {
lifetime: wrp.lifetime.clean(cx),
- bounds: wrp.bounds.clean(cx),
+ bounds: wrp.bounds.iter().map(|x| x.clean(cx)).collect(),
},
hir::WherePredicate::EqPredicate(ref wrp) => {
self.name.ident().name,
GenericParamDefKind::Type {
did: cx.tcx.hir().local_def_id(self.hir_id).to_def_id(),
- bounds: self.bounds.clean(cx),
- default: default.clean(cx).map(Box::new),
+ bounds: self.bounds.iter().map(|x| x.clean(cx)).collect(),
+ default: default.map(|t| t.clean(cx)).map(Box::new),
synthetic,
},
),
}
params.extend(impl_trait_params);
- let mut generics =
- Generics { params, where_predicates: self.where_clause.predicates.clean(cx) };
+ let mut generics = Generics {
+ params,
+ where_predicates: self.where_clause.predicates.iter().map(|x| x.clean(cx)).collect(),
+ };
// Some duplicates are generated for ?Sized bounds between type params and where
// predicates. The point in here is to move the bounds definitions from type params
fn clean(&self, cx: &mut DocContext<'_>) -> PolyTrait {
PolyTrait {
trait_: self.trait_ref.clean(cx),
- generic_params: self.bound_generic_params.clean(cx),
+ generic_params: self.bound_generic_params.iter().map(|x| x.clean(cx)).collect(),
}
}
}
TyMethodItem(t)
}
hir::TraitItemKind::Type(bounds, ref default) => {
- AssocTypeItem(bounds.clean(cx), default.clean(cx))
+ let bounds = bounds.iter().map(|x| x.clean(cx)).collect();
+ let default = default.map(|t| t.clean(cx));
+ AssocTypeItem(bounds, default)
}
};
let what_rustc_thinks =
None
};
- AssocTypeItem(bounds, ty.clean(cx))
+ AssocTypeItem(bounds, ty.map(|t| t.clean(cx)))
} else {
// FIXME: when could this happen? Associated items in inherent impls?
let type_ = tcx.type_of(self.def_id).clean(cx);
}
fn clean_qpath(hir_ty: &hir::Ty<'_>, cx: &mut DocContext<'_>) -> Type {
- use rustc_hir::GenericParamCount;
let hir::Ty { hir_id: _, span, ref kind } = *hir_ty;
let qpath = match kind {
hir::TyKind::Path(qpath) => qpath,
match qpath {
hir::QPath::Resolved(None, ref path) => {
if let Res::Def(DefKind::TyParam, did) = path.res {
- if let Some(new_ty) = cx.ty_substs.get(&did).cloned() {
+ if let Some(new_ty) = cx.substs.get(&did).and_then(|p| p.as_ty()).cloned() {
return new_ty;
}
if let Some(bounds) = cx.impl_trait_bounds.remove(&did.into()) {
}
}
- let mut alias = None;
- if let Res::Def(DefKind::TyAlias, def_id) = path.res {
- // Substitute private type aliases
- if let Some(def_id) = def_id.as_local() {
- let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
- if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
- alias = Some(&cx.tcx.hir().expect_item(hir_id).kind);
- }
- }
- };
-
- if let Some(&hir::ItemKind::TyAlias(ref ty, ref generics)) = alias {
- let provided_params = &path.segments.last().expect("segments were empty");
- let mut ty_substs = FxHashMap::default();
- let mut lt_substs = FxHashMap::default();
- let mut ct_substs = FxHashMap::default();
- let generic_args = provided_params.args();
- {
- let mut indices: GenericParamCount = Default::default();
- for param in generics.params.iter() {
- match param.kind {
- hir::GenericParamKind::Lifetime { .. } => {
- let mut j = 0;
- let lifetime = generic_args.args.iter().find_map(|arg| match arg {
- hir::GenericArg::Lifetime(lt) => {
- if indices.lifetimes == j {
- return Some(lt);
- }
- j += 1;
- None
- }
- _ => None,
- });
- if let Some(lt) = lifetime.cloned() {
- let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
- let cleaned = if !lt.is_elided() {
- lt.clean(cx)
- } else {
- self::types::Lifetime::elided()
- };
- lt_substs.insert(lt_def_id.to_def_id(), cleaned);
- }
- indices.lifetimes += 1;
- }
- hir::GenericParamKind::Type { ref default, .. } => {
- let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
- let mut j = 0;
- let type_ = generic_args.args.iter().find_map(|arg| match arg {
- hir::GenericArg::Type(ty) => {
- if indices.types == j {
- return Some(ty);
- }
- j += 1;
- None
- }
- _ => None,
- });
- if let Some(ty) = type_ {
- ty_substs.insert(ty_param_def_id.to_def_id(), ty.clean(cx));
- } else if let Some(default) = *default {
- ty_substs
- .insert(ty_param_def_id.to_def_id(), default.clean(cx));
- }
- indices.types += 1;
- }
- hir::GenericParamKind::Const { .. } => {
- let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
- let mut j = 0;
- let const_ = generic_args.args.iter().find_map(|arg| match arg {
- hir::GenericArg::Const(ct) => {
- if indices.consts == j {
- return Some(ct);
- }
- j += 1;
- None
- }
- _ => None,
- });
- if let Some(ct) = const_ {
- ct_substs.insert(const_param_def_id.to_def_id(), ct.clean(cx));
- }
- // FIXME(const_generics_defaults)
- indices.consts += 1;
- }
- }
- }
- }
- return cx.enter_alias(ty_substs, lt_substs, ct_substs, |cx| ty.clean(cx));
+ if let Some(expanded) = maybe_expand_private_type_alias(cx, path) {
+ expanded
+ } else {
+ let path = path.clean(cx);
+ resolve_type(cx, path)
}
- let path = path.clean(cx);
- resolve_type(cx, path)
}
hir::QPath::Resolved(Some(ref qself), p) => {
// Try to normalize `<X as Y>::T` to a type
let trait_def = cx.tcx.associated_item(p.res.def_id()).container.id();
let trait_ = self::Path {
res: Res::Def(DefKind::Trait, trait_def),
- segments: trait_segments.clean(cx),
+ segments: trait_segments.iter().map(|x| x.clean(cx)).collect(),
};
register_res(cx, trait_.res);
Type::QPath {
}
}
+fn maybe_expand_private_type_alias(cx: &mut DocContext<'_>, path: &hir::Path<'_>) -> Option<Type> {
+ let Res::Def(DefKind::TyAlias, def_id) = path.res else { return None };
+ // Substitute private type aliases
+ let Some(def_id) = def_id.as_local() else { return None };
+ let hir_id = cx.tcx.hir().local_def_id_to_hir_id(def_id);
+ let alias = if !cx.cache.access_levels.is_exported(def_id.to_def_id()) {
+ &cx.tcx.hir().expect_item(hir_id).kind
+ } else {
+ return None;
+ };
+ let hir::ItemKind::TyAlias(ty, generics) = alias else { return None };
+
+ let provided_params = &path.segments.last().expect("segments were empty");
+ let mut substs = FxHashMap::default();
+ let generic_args = provided_params.args();
+
+ let mut indices: hir::GenericParamCount = Default::default();
+ for param in generics.params.iter() {
+ match param.kind {
+ hir::GenericParamKind::Lifetime { .. } => {
+ let mut j = 0;
+ let lifetime = generic_args.args.iter().find_map(|arg| match arg {
+ hir::GenericArg::Lifetime(lt) => {
+ if indices.lifetimes == j {
+ return Some(lt);
+ }
+ j += 1;
+ None
+ }
+ _ => None,
+ });
+ if let Some(lt) = lifetime.cloned() {
+ let lt_def_id = cx.tcx.hir().local_def_id(param.hir_id);
+ let cleaned = if !lt.is_elided() {
+ lt.clean(cx)
+ } else {
+ self::types::Lifetime::elided()
+ };
+ substs.insert(lt_def_id.to_def_id(), SubstParam::Lifetime(cleaned));
+ }
+ indices.lifetimes += 1;
+ }
+ hir::GenericParamKind::Type { ref default, .. } => {
+ let ty_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
+ let mut j = 0;
+ let type_ = generic_args.args.iter().find_map(|arg| match arg {
+ hir::GenericArg::Type(ty) => {
+ if indices.types == j {
+ return Some(ty);
+ }
+ j += 1;
+ None
+ }
+ _ => None,
+ });
+ if let Some(ty) = type_ {
+ substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(ty.clean(cx)));
+ } else if let Some(default) = *default {
+ substs.insert(ty_param_def_id.to_def_id(), SubstParam::Type(default.clean(cx)));
+ }
+ indices.types += 1;
+ }
+ hir::GenericParamKind::Const { .. } => {
+ let const_param_def_id = cx.tcx.hir().local_def_id(param.hir_id);
+ let mut j = 0;
+ let const_ = generic_args.args.iter().find_map(|arg| match arg {
+ hir::GenericArg::Const(ct) => {
+ if indices.consts == j {
+ return Some(ct);
+ }
+ j += 1;
+ None
+ }
+ _ => None,
+ });
+ if let Some(ct) = const_ {
+ substs
+ .insert(const_param_def_id.to_def_id(), SubstParam::Constant(ct.clean(cx)));
+ }
+ // FIXME(const_generics_defaults)
+ indices.consts += 1;
+ }
+ }
+ }
+
+ Some(cx.enter_alias(substs, |cx| ty.clean(cx)))
+}
+
impl Clean<Type> for hir::Ty<'_> {
fn clean(&self, cx: &mut DocContext<'_>) -> Type {
use rustc_hir::*;
let length = print_const(cx, ct.eval(cx.tcx, param_env));
Array(box ty.clean(cx), length)
}
- TyKind::Tup(tys) => Tuple(tys.clean(cx)),
+ TyKind::Tup(tys) => Tuple(tys.iter().map(|x| x.clean(cx)).collect()),
TyKind::OpaqueDef(item_id, _) => {
let item = cx.tcx.hir().item(item_id);
if let hir::ItemKind::OpaqueTy(ref ty) = item.kind {
- ImplTrait(ty.bounds.clean(cx))
+ ImplTrait(ty.bounds.iter().map(|x| x.clean(cx)).collect())
} else {
unreachable!()
}
DynTrait(bounds, lifetime)
}
- ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty()).collect::<Vec<_>>().clean(cx)),
+ ty::Tuple(t) => Tuple(t.iter().map(|t| t.expect_ty().clean(cx)).collect()),
ty::Projection(ref data) => data.clean(cx),
impl Clean<Path> for hir::Path<'_> {
fn clean(&self, cx: &mut DocContext<'_>) -> Path {
- Path { res: self.res, segments: self.segments.clean(cx) }
+ Path { res: self.res, segments: self.segments.iter().map(|x| x.clean(cx)).collect() }
}
}
let output = self.bindings[0].ty().clean(cx);
let output =
if output != Type::Tuple(Vec::new()) { Some(Box::new(output)) } else { None };
- GenericArgs::Parenthesized { inputs: self.inputs().clean(cx), output }
+ let inputs = self.inputs().iter().map(|x| x.clean(cx)).collect();
+ GenericArgs::Parenthesized { inputs, output }
} else {
- GenericArgs::AngleBracketed {
- args: self
- .args
- .iter()
- .map(|arg| match arg {
- hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
- GenericArg::Lifetime(lt.clean(cx))
- }
- hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
- hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
- hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
- hir::GenericArg::Infer(_inf) => GenericArg::Infer,
- })
- .collect(),
- bindings: self.bindings.clean(cx),
- }
+ let args = self
+ .args
+ .iter()
+ .map(|arg| match arg {
+ hir::GenericArg::Lifetime(lt) if !lt.is_elided() => {
+ GenericArg::Lifetime(lt.clean(cx))
+ }
+ hir::GenericArg::Lifetime(_) => GenericArg::Lifetime(Lifetime::elided()),
+ hir::GenericArg::Type(ty) => GenericArg::Type(ty.clean(cx)),
+ hir::GenericArg::Const(ct) => GenericArg::Const(Box::new(ct.clean(cx))),
+ hir::GenericArg::Infer(_inf) => GenericArg::Infer,
+ })
+ .collect();
+ let bindings = self.bindings.iter().map(|x| x.clean(cx)).collect();
+ GenericArgs::AngleBracketed { args, bindings }
}
}
}
impl Clean<BareFunctionDecl> for hir::BareFnTy<'_> {
fn clean(&self, cx: &mut DocContext<'_>) -> BareFunctionDecl {
let (generic_params, decl) = enter_impl_trait(cx, |cx| {
- (self.generic_params.clean(cx), (&*self.decl, self.param_names).clean(cx))
+ let generic_params = self.generic_params.iter().map(|x| x.clean(cx)).collect();
+ let decl = (self.decl, self.param_names).clean(cx);
+ (generic_params, decl)
});
BareFunctionDecl { unsafety: self.unsafety, abi: self.abi, decl, generic_params }
}
kind: ConstantKind::Local { body: body_id, def_id },
}),
ItemKind::OpaqueTy(ref ty) => OpaqueTyItem(OpaqueTy {
- bounds: ty.bounds.clean(cx),
+ bounds: ty.bounds.iter().map(|x| x.clean(cx)).collect(),
generics: ty.generics.clean(cx),
}),
ItemKind::TyAlias(hir_ty, ref generics) => {
}),
ItemKind::TraitAlias(ref generics, bounds) => TraitAliasItem(TraitAlias {
generics: generics.clean(cx),
- bounds: bounds.clean(cx),
+ bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
}),
ItemKind::Union(ref variant_data, ref generics) => UnionItem(Union {
generics: generics.clean(cx),
- fields: variant_data.fields().clean(cx),
+ fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
fields_stripped: false,
}),
ItemKind::Struct(ref variant_data, ref generics) => StructItem(Struct {
struct_type: CtorKind::from_hir(variant_data),
generics: generics.clean(cx),
- fields: variant_data.fields().clean(cx),
+ fields: variant_data.fields().iter().map(|x| x.clean(cx)).collect(),
fields_stripped: false,
}),
ItemKind::Impl(ref impl_) => return clean_impl(impl_, item.hir_id(), cx),
clean_fn_or_proc_macro(item, sig, generics, body_id, &mut name, cx)
}
ItemKind::Macro(ref macro_def) => MacroItem(Macro {
- source: display_macro_source(cx, name, macro_def, def_id, &item.vis),
+ source: display_macro_source(cx, name, macro_def, def_id, item.vis),
}),
ItemKind::Trait(is_auto, unsafety, ref generics, bounds, item_ids) => {
let items = item_ids
unsafety,
items,
generics: generics.clean(cx),
- bounds: bounds.clean(cx),
+ bounds: bounds.iter().map(|x| x.clean(cx)).collect(),
is_auto: is_auto.clean(cx),
})
}
}
}
-impl Clean<bool> for ty::ImplPolarity {
- /// Returns whether the impl has negative polarity.
- fn clean(&self, _: &mut DocContext<'_>) -> bool {
- match self {
- &ty::ImplPolarity::Positive |
- // FIXME: do we want to do something else here?
- &ty::ImplPolarity::Reservation => false,
- &ty::ImplPolarity::Negative => true,
- }
- }
-}
-
fn clean_impl(impl_: &hir::Impl<'_>, hir_id: hir::HirId, cx: &mut DocContext<'_>) -> Vec<Item> {
let tcx = cx.tcx;
let mut ret = Vec::new();
- let trait_ = impl_.of_trait.clean(cx);
+ let trait_ = impl_.of_trait.as_ref().map(|t| t.clean(cx));
let items =
impl_.items.iter().map(|ii| tcx.hir().impl_item(ii.id).clean(cx)).collect::<Vec<_>>();
let def_id = tcx.hir().local_def_id(hir_id);
});
let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
let kind = ImplItem(Impl {
- span: types::rustc_span(tcx.hir().local_def_id(hir_id).to_def_id(), tcx),
unsafety: impl_.unsafety,
generics: impl_.generics.clean(cx),
trait_,
for_,
items,
- negative_polarity: tcx.impl_polarity(def_id).clean(cx),
- synthetic: false,
- blanket_impl: None,
+ polarity: tcx.impl_polarity(def_id),
+ kind: ImplKind::Normal,
});
Item::from_hir_id_and_parts(hir_id, None, kind, cx)
};
ItemKind::StrippedItem(k) => k,
_ => &*self.kind,
};
- if let ItemKind::ModuleItem(Module { span, .. }) | ItemKind::ImplItem(Impl { span, .. }) =
- kind
- {
- *span
- } else {
- self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(Span::dummy)
+ match kind {
+ ItemKind::ModuleItem(Module { span, .. }) => *span,
+ ItemKind::ImplItem(Impl { kind: ImplKind::Auto, .. }) => Span::dummy(),
+ ItemKind::ImplItem(Impl { kind: ImplKind::Blanket(_), .. }) => {
+ if let ItemId::Blanket { impl_id, .. } = self.def_id {
+ rustc_span(impl_id, tcx)
+ } else {
+ panic!("blanket impl item has non-blanket ID")
+ }
+ }
+ _ => {
+ self.def_id.as_def_id().map(|did| rustc_span(did, tcx)).unwrap_or_else(Span::dummy)
+ }
}
}
#[derive(Clone, Debug)]
crate struct Impl {
- crate span: Span,
crate unsafety: hir::Unsafety,
crate generics: Generics,
crate trait_: Option<Path>,
crate for_: Type,
crate items: Vec<Item>,
- crate negative_polarity: bool,
- crate synthetic: bool,
- crate blanket_impl: Option<Box<Type>>,
+ crate polarity: ty::ImplPolarity,
+ crate kind: ImplKind,
}
impl Impl {
}
}
+#[derive(Clone, Debug)]
+crate enum ImplKind {
+ Normal,
+ Auto,
+ Blanket(Box<Type>),
+}
+
+impl ImplKind {
+ crate fn is_auto(&self) -> bool {
+ matches!(self, ImplKind::Auto)
+ }
+
+ crate fn is_blanket(&self) -> bool {
+ matches!(self, ImplKind::Blanket(_))
+ }
+
+ crate fn as_blanket_ty(&self) -> Option<&Type> {
+ match self {
+ ImplKind::Blanket(ty) => Some(ty),
+ _ => None,
+ }
+ }
+}
+
#[derive(Clone, Debug)]
crate struct Import {
crate kind: ImportKind,
}
}
}
+
+/// The type, lifetime, or constant that a private type alias's parameter should be
+/// replaced with when expanding a use of that type alias.
+///
+/// For example:
+///
+/// ```
+/// type PrivAlias<T> = Vec<T>;
+///
+/// pub fn public_fn() -> PrivAlias<i32> { vec![] }
+/// ```
+///
+/// `public_fn`'s docs will show it as returning `Vec<i32>`, since `PrivAlias` is private.
+/// [`SubstParam`] is used to record that `T` should be mapped to `i32`.
+crate enum SubstParam {
+ Type(Type),
+ Lifetime(Lifetime),
+ Constant(Constant),
+}
+
+impl SubstParam {
+ crate fn as_ty(&self) -> Option<&Type> {
+ if let Self::Type(ty) = self { Some(ty) } else { None }
+ }
+
+ crate fn as_lt(&self) -> Option<&Lifetime> {
+ if let Self::Lifetime(lt) = self { Some(lt) } else { None }
+ }
+}
/// Used while populating `external_traits` to ensure we don't process the same trait twice at
/// the same time.
crate active_extern_traits: FxHashSet<DefId>,
- // The current set of type and lifetime substitutions,
+ // The current set of parameter substitutions,
// for expanding type aliases at the HIR level:
- /// Table `DefId` of type parameter -> substituted type
- crate ty_substs: FxHashMap<DefId, clean::Type>,
- /// Table `DefId` of lifetime parameter -> substituted lifetime
- crate lt_substs: FxHashMap<DefId, clean::Lifetime>,
- /// Table `DefId` of const parameter -> substituted const
- crate ct_substs: FxHashMap<DefId, clean::Constant>,
+ /// Table `DefId` of type, lifetime, or const parameter -> substituted type, lifetime, or const
+ crate substs: FxHashMap<DefId, clean::SubstParam>,
/// Table synthetic type parameter for `impl Trait` in argument position -> bounds
crate impl_trait_bounds: FxHashMap<ImplTraitParam, Vec<clean::GenericBound>>,
/// Auto-trait or blanket impls processed so far, as `(self_ty, trait_def_id)`.
/// Call the closure with the given parameters set as
/// the substitutions for a type alias' RHS.
- crate fn enter_alias<F, R>(
- &mut self,
- ty_substs: FxHashMap<DefId, clean::Type>,
- lt_substs: FxHashMap<DefId, clean::Lifetime>,
- ct_substs: FxHashMap<DefId, clean::Constant>,
- f: F,
- ) -> R
+ crate fn enter_alias<F, R>(&mut self, substs: FxHashMap<DefId, clean::SubstParam>, f: F) -> R
where
F: FnOnce(&mut Self) -> R,
{
- let (old_tys, old_lts, old_cts) = (
- mem::replace(&mut self.ty_substs, ty_substs),
- mem::replace(&mut self.lt_substs, lt_substs),
- mem::replace(&mut self.ct_substs, ct_substs),
- );
+ let old_substs = mem::replace(&mut self.substs, substs);
let r = f(self);
- self.ty_substs = old_tys;
- self.lt_substs = old_lts;
- self.ct_substs = old_cts;
+ self.substs = old_substs;
r
}
param_env: ParamEnv::empty(),
external_traits: Default::default(),
active_extern_traits: Default::default(),
- ty_substs: Default::default(),
- lt_substs: Default::default(),
- ct_substs: Default::default(),
+ substs: Default::default(),
impl_trait_bounds: Default::default(),
generated_synthetics: Default::default(),
auto_traits: tcx
// Collect all the implementors of traits.
if let clean::ImplItem(ref i) = *item.kind {
if let Some(trait_) = &i.trait_ {
- if i.blanket_impl.is_none() {
+ if !i.kind.is_blanket() {
self.cache
.implementors
.entry(trait_.def_id())
use rustc_data_structures::fx::FxHashSet;
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
+use rustc_middle::ty;
use rustc_middle::ty::TyCtxt;
use rustc_span::def_id::CRATE_DEF_INDEX;
use rustc_target::spec::abi::Abi;
}
if let Some(ref ty) = self.trait_ {
- if self.negative_polarity {
- write!(f, "!")?;
+ match self.polarity {
+ ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => {}
+ ty::ImplPolarity::Negative => write!(f, "!")?,
}
fmt::Display::fmt(&ty.print(cx), f)?;
write!(f, " for ")?;
}
- if let Some(ref ty) = self.blanket_impl {
+ if let Some(ref ty) = self.kind.as_blanket_ty() {
fmt_type(ty, f, use_absolute, cx)?;
} else {
fmt_type(&self.for_, f, use_absolute, cx)?;
mod templates;
mod write_shared;
-crate use context::*;
-crate use span_map::{collect_spans_and_sources, LinkFromSrc};
+crate use self::context::*;
+crate use self::span_map::{collect_spans_and_sources, LinkFromSrc};
use std::collections::VecDeque;
use std::default::Default;
use rustc_hir::def_id::DefId;
use rustc_hir::Mutability;
use rustc_middle::middle::stability;
+use rustc_middle::ty;
use rustc_middle::ty::TyCtxt;
use rustc_span::{
symbol::{kw, sym, Symbol},
}
let (synthetic, concrete): (Vec<&&Impl>, Vec<&&Impl>) =
- traits.iter().partition(|t| t.inner_impl().synthetic);
+ traits.iter().partition(|t| t.inner_impl().kind.is_auto());
let (blanket_impl, concrete): (Vec<&&Impl>, _) =
- concrete.into_iter().partition(|t| t.inner_impl().blanket_impl.is_some());
+ concrete.into_iter().partition(|t| t.inner_impl().kind.is_blanket());
let mut impls = Buffer::empty_from(w);
render_impls(cx, &mut impls, &concrete, containing_item);
let i_display = format!("{:#}", i.print(cx));
let out = Escape(&i_display);
let encoded = small_url_encode(format!("{:#}", i.print(cx)));
- let generated = format!(
- "<a href=\"#impl-{}\">{}{}</a>",
- encoded,
- if it.inner_impl().negative_polarity { "!" } else { "" },
- out
- );
+ let prefix = match it.inner_impl().polarity {
+ ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => "",
+ ty::ImplPolarity::Negative => "!",
+ };
+ let generated =
+ format!("<a href=\"#impl-{}\">{}{}</a>", encoded, prefix, out);
if links.insert(generated.clone()) { Some(generated) } else { None }
} else {
None
};
let (synthetic, concrete): (Vec<&Impl>, Vec<&Impl>) =
- v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().synthetic);
- let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) = concrete
- .into_iter()
- .partition::<Vec<_>, _>(|i| i.inner_impl().blanket_impl.is_some());
+ v.iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_auto());
+ let (blanket_impl, concrete): (Vec<&Impl>, Vec<&Impl>) =
+ concrete.into_iter().partition::<Vec<_>, _>(|i| i.inner_impl().kind.is_blanket());
let concrete_format = format_impls(concrete);
let synthetic_format = format_impls(synthetic);
});
let (mut synthetic, mut concrete): (Vec<&&Impl>, Vec<&&Impl>) =
- local.iter().partition(|i| i.inner_impl().synthetic);
+ local.iter().partition(|i| i.inner_impl().kind.is_auto());
synthetic.sort_by(|a, b| compare_impl(a, b, cx));
concrete.sort_by(|a, b| compare_impl(a, b, cx));
} else {
Some(Implementor {
text: imp.inner_impl().print(false, cx).to_string(),
- synthetic: imp.inner_impl().synthetic,
+ synthetic: imp.inner_impl().kind.is_auto(),
types: collect_paths_for_type(imp.inner_impl().for_.clone(), cache),
})
}
use rustc_ast::ast;
use rustc_hir::{def::CtorKind, def_id::DefId};
-use rustc_middle::ty::TyCtxt;
+use rustc_middle::ty::{self, TyCtxt};
use rustc_span::def_id::CRATE_DEF_INDEX;
use rustc_span::Pos;
impl FromWithTcx<clean::Impl> for Impl {
fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
let provided_trait_methods = impl_.provided_trait_methods(tcx);
- let clean::Impl {
- unsafety,
- generics,
- trait_,
- for_,
- items,
- negative_polarity,
- synthetic,
- blanket_impl,
- span: _span,
- } = impl_;
+ let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_;
// FIXME: should `trait_` be a clean::Path equivalent in JSON?
let trait_ = trait_.map(|path| {
let did = path.def_id();
clean::ResolvedPath { path, did }.into_tcx(tcx)
});
+ // FIXME: use something like ImplKind in JSON?
+ let (synthetic, blanket_impl) = match kind {
+ clean::ImplKind::Normal => (false, None),
+ clean::ImplKind::Auto => (true, None),
+ clean::ImplKind::Blanket(ty) => (false, Some(*ty)),
+ };
+ let negative_polarity = match polarity {
+ ty::ImplPolarity::Positive | ty::ImplPolarity::Reservation => false,
+ ty::ImplPolarity::Negative => true,
+ };
Impl {
is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe,
generics: generics.into_tcx(tcx),
items: ids(items),
negative: negative_polarity,
synthetic,
- blanket_impl: blanket_impl.map(|x| (*x).into_tcx(tcx)),
+ blanket_impl: blanket_impl.map(|x| x.into_tcx(tcx)),
}
}
}
#![feature(control_flow_enum)]
#![feature(box_syntax)]
#![feature(in_band_lifetimes)]
+#![feature(let_else)]
#![feature(nll)]
#![feature(test)]
#![feature(crate_visibility_modifier)]
}
new_items.retain(|it| {
- if let ImplItem(Impl { ref for_, ref trait_, ref blanket_impl, .. }) = *it.kind {
+ if let ImplItem(Impl { ref for_, ref trait_, ref kind, .. }) = *it.kind {
cleaner.keep_impl(
for_,
trait_.as_ref().map(|t| t.def_id()) == cx.tcx.lang_items().deref_trait(),
) || trait_.as_ref().map_or(false, |t| cleaner.keep_impl_with_def_id(t.def_id().into()))
- || blanket_impl.is_some()
+ || kind.is_blanket()
} else {
true
}
{
::std::io::_print(::core::fmt::Arguments::new_v1(&["rust\n"],
&match () {
- () => [],
+ _args => [],
}));
};
}
as
())
{
- ()
+ _args
=>
([]
as
all:
touch $(TMPDIR)/lib.rmeta
$(AR) crus $(TMPDIR)/libfoo-ffffffff-1.0.rlib $(TMPDIR)/lib.rmeta
- $(RUSTC) foo.rs 2>&1 | $(CGREP) "can't find crate for"
+ $(RUSTC) foo.rs 2>&1 | $(CGREP) "found invalid metadata"
+# needs-llvm-components: x86 arm
+
-include ../tools.mk
all: default
--- /dev/null
+include ../../run-make-fulldeps/tools.mk
+
+DYLIB_NAME := $(shell echo | $(RUSTC) --crate-name foo --crate-type dylib --print file-names -)
+
+all:
+ echo >> $(TMPDIR)/$(DYLIB_NAME)
+ $(RUSTC) --crate-type lib --extern foo=$(TMPDIR)/$(DYLIB_NAME) bar.rs 2>&1 | $(CGREP) 'invalid metadata files for crate `foo`'
--- /dev/null
+extern crate foo;
--- /dev/null
+#![crate_name = "foo"]
+#![no_std]
+
+// @has 'foo/fn.foo.html'
+// @has - '//*[@class="docblock"]' 'inc2 x'
+#[doc = include_str!("short-line.md")]
+pub fn foo() {}
+++ /dev/null
-// run-pass
-
-struct X {
- x: isize
-}
-
-fn f1(a: &mut X, b: &mut isize, c: isize) -> isize {
- let r = a.x + *b + c;
- a.x = 0;
- *b = 10;
- return r;
-}
-
-fn f2<F>(a: isize, f: F) -> isize where F: FnOnce(isize) { f(1); return a; }
-
-pub fn main() {
- let mut a = X {x: 1};
- let mut b = 2;
- let c = 3;
- assert_eq!(f1(&mut a, &mut b, c), 6);
- assert_eq!(a.x, 0);
- assert_eq!(b, 10);
- assert_eq!(f2(a.x, |_| a.x = 50), 0);
- assert_eq!(a.x, 50);
-}
--- /dev/null
+// run-pass
+// pretty-expanded FIXME #23616
+
+pub fn main() {
+ let _x: &mut [isize] = &mut [ 1, 2, 3 ];
+}
--- /dev/null
+// check-pass
+pub trait LineFormatter<'a> {
+ type Iter: Iterator<Item=&'a str> + 'a;
+ fn iter(&'a self, line: &'a str) -> Self::Iter;
+
+ fn dimensions(&'a self, line: &'a str) {
+ let iter: Self::Iter = self.iter(line);
+ <_ as IntoIterator>::into_iter(iter);
+ }
+}
+
+fn main() {}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+// Test transitive analysis for associated types. Collected types
+// should be normalized and new obligations generated.
+
+// pretty-expanded FIXME #23616
+
+trait Foo {
+ type A;
+ fn foo(&self) {}
+}
+
+impl Foo for usize {
+ type A = usize;
+}
+
+struct Bar<T: Foo> { inner: T::A }
+
+fn is_send<T: Send>() {}
+
+fn main() {
+ is_send::<Bar<usize>>();
+}
--- /dev/null
+// check-pass
+// Regression test for #28871. The problem is that rustc encountered
+// two ways to project, one from a where clause and one from the where
+// clauses on the trait definition. (In fact, in this case, the where
+// clauses originated from the trait definition as well.) The true
+// cause of the error is that the trait definition where clauses are
+// not being normalized, and hence the two sources are considered in
+// conflict, and not a duplicate. Hacky solution is to prefer where
+// clauses over the data found in the trait definition.
+
+trait T {
+ type T;
+}
+
+struct S;
+impl T for S {
+ type T = S;
+}
+
+trait T2 {
+ type T: Iterator<Item=<S as T>::T>;
+}
+
+fn main() { }
--- /dev/null
+// run-pass
+// Regression test for issue #47139:
+//
+// Coherence was encountering an (unnecessary) overflow trying to
+// decide if the two impls of dummy overlap.
+//
+// The overflow went something like:
+//
+// - `&'a ?T: Insertable` ?
+// - let ?T = Option<?U> ?
+// - `Option<?U>: Insertable` ?
+// - `Option<&'a ?U>: Insertable` ?
+// - `&'a ?U: Insertable` ?
+//
+// While somewhere in the middle, a projection would occur, which
+// broke cycle detection.
+//
+// It turned out that this cycle was being kicked off due to some
+// extended diagnostic attempts in coherence, so removing those
+// sidestepped the issue for now.
+
+#![allow(dead_code)]
+
+pub trait Insertable {
+ type Values;
+
+ fn values(self) -> Self::Values;
+}
+
+impl<T> Insertable for Option<T>
+ where
+ T: Insertable,
+ T::Values: Default,
+{
+ type Values = T::Values;
+
+ fn values(self) -> Self::Values {
+ self.map(Insertable::values).unwrap_or_default()
+ }
+}
+
+impl<'a, T> Insertable for &'a Option<T>
+ where
+ Option<&'a T>: Insertable,
+{
+ type Values = <Option<&'a T> as Insertable>::Values;
+
+ fn values(self) -> Self::Values {
+ self.as_ref().values()
+ }
+}
+
+impl<'a, T> Insertable for &'a [T]
+{
+ type Values = Self;
+
+ fn values(self) -> Self::Values {
+ self
+ }
+}
+
+trait Unimplemented { }
+
+trait Dummy { }
+
+struct Foo<T> { t: T }
+
+impl<'a, U> Dummy for Foo<&'a U>
+ where &'a U: Insertable
+{
+}
+
+impl<T> Dummy for T
+ where T: Unimplemented
+{ }
+
+fn main() {
+}
--- /dev/null
+// run-pass
+
+pub trait Stream {
+ type Item;
+ type Error;
+}
+
+pub trait ParseError<I> {
+ type Output;
+}
+
+impl ParseError<char> for u32 {
+ type Output = ();
+}
+
+impl Stream for () {
+ type Item = char;
+ type Error = u32;
+}
+
+pub struct Lex<'a, I>
+ where I: Stream,
+ I::Error: ParseError<char>,
+ <<I as Stream>::Error as ParseError<char>>::Output: 'a
+{
+ x: &'a <I::Error as ParseError<char>>::Output
+}
+
+pub struct Reserved<'a, I> where
+ I: Stream<Item=char> + 'a,
+ I::Error: ParseError<I::Item>,
+ <<I as Stream>::Error as ParseError<char>>::Output: 'a
+
+{
+ x: Lex<'a, I>
+}
+
+fn main() {
+ let r: Reserved<()> = Reserved {
+ x: Lex {
+ x: &()
+ }
+ };
+
+ let _v = r.x.x;
+}
--- /dev/null
+// edition:2018
+
+fn main() {
+ 'a: loop {
+ async {
+ loop {
+ continue 'a
+ //~^ ERROR use of unreachable label `'a`
+ }
+ };
+ }
+}
--- /dev/null
+error[E0767]: use of unreachable label `'a`
+ --> $DIR/issue-73541-1.rs:7:26
+ |
+LL | 'a: loop {
+ | -- unreachable label defined here
+...
+LL | continue 'a
+ | ^^ unreachable label `'a`
+ |
+ = note: labels are unreachable through functions, closures, async blocks and modules
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0767`.
--- /dev/null
+// check-pass
+macro_rules! m {
+ ($i:meta) => {
+ #[derive($i)]
+ struct S;
+ }
+}
+
+m!(Clone);
+
+fn main() {}
let res =
::alloc::fmt::format(::core::fmt::Arguments::new_v1(&[""],
&match (&"u8",) {
- (arg0,) =>
- [::core::fmt::ArgumentV1::new(arg0,
+ _args =>
+ [::core::fmt::ArgumentV1::new(_args.0,
::core::fmt::Display::fmt)],
}));
res
--- /dev/null
+// build-pass (FIXME(62277): could be check-pass?)
+
+#![feature(rustc_attrs)]
+
+#[rustc_dummy(a b c d)]
+#[rustc_dummy[a b c d]]
+#[rustc_dummy{a b c d}]
+fn main() {}
+++ /dev/null
-#![crate_name = "a"]
-
-pub fn foo<T>() {}
+++ /dev/null
-#![crate_name = "a"]
-
-pub fn foo<T>() { println!("hello!"); }
+++ /dev/null
-#![crate_name = "b"]
-
-extern crate a;
-
-pub fn foo() { a::foo::<isize>(); }
+++ /dev/null
-#![feature(rustc_attrs)]
-
-#[rustc_legacy_const_generics(1)]
-pub fn foo<const Y: usize>(x: usize, z: usize) -> [usize; 3] {
- [x, Y, z]
-}
+++ /dev/null
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-#[no_mangle]
-pub extern "C" fn foo() {}
+++ /dev/null
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-#[no_mangle]
-pub extern "C" fn foo() {}
+++ /dev/null
-// compile-flags: -Clinker-plugin-lto
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-pub fn foo() {}
+++ /dev/null
-// original problem
-pub fn foo<T>() -> isize {
- {
- static foo: isize = 2;
- foo
- }
-}
-
-// issue 8134
-struct Foo;
-impl Foo {
- pub fn foo<T>(&self) {
- static X: usize = 1;
- }
-}
-
-// issue 8134
-pub struct Parser<T>(T);
-impl<T: std::iter::Iterator<Item=char>> Parser<T> {
- fn in_doctype(&mut self) {
- static DOCTYPEPattern: [char; 6] = ['O', 'C', 'T', 'Y', 'P', 'E'];
- }
-}
-
-struct Bar;
-impl Foo {
- pub fn bar<T>(&self) {
- static X: usize = 1;
- }
-}
+++ /dev/null
-// check-pass
-
-// Bastion of the Turbofish
-// ------------------------
-// Beware travellers, lest you venture into waters callous and unforgiving,
-// where hope must be abandoned, ere it is cruelly torn from you. For here
-// stands the bastion of the Turbofish: an impenetrable fortress holding
-// unshaking against those who would dare suggest the supererogation of the
-// Turbofish.
-//
-// Once I was young and foolish and had the impudence to imagine that I could
-// shake free from the coils by which that creature had us tightly bound. I
-// dared to suggest that there was a better way: a brighter future, in which
-// Rustaceans both new and old could be rid of that vile beast. But alas! In
-// my foolhardiness my ignorance was unveiled and my dreams were dashed
-// unforgivingly against the rock of syntactic ambiguity.
-//
-// This humble program, small and insignificant though it might seem,
-// demonstrates that to which we had previously cast a blind eye: an ambiguity
-// in permitting generic arguments to be provided without the consent of the
-// Great Turbofish. Should you be so naïve as to try to revolt against its
-// mighty clutches, here shall its wrath be indomitably displayed. This
-// program must pass for all eternity: forever watched by the guardian angel
-// which gave this beast its name, and stands fundamentally at odds with the
-// impetuous rebellion against the Turbofish.
-//
-// My heart aches in sorrow, for I know I am defeated. Let this be a warning
-// to all those who come after: for they too must overcome the impassible
-// hurdle of defeating the great beast, championed by a resolute winged
-// guardian.
-//
-// Here stands the Bastion of the Turbofish, a memorial to Anna Harren,
-// Guardian Angel of these Hallowed Grounds. <3
-
-// See https://github.com/rust-lang/rust/pull/53562
-// and https://github.com/rust-lang/rfcs/pull/2527
-// and https://twitter.com/garblefart/status/1393236602856611843
-// for context.
-
-fn main() {
- let (the, guardian, stands, resolute) = ("the", "Turbofish", "remains", "undefeated");
- let _: (bool, bool) = (the<guardian, stands>(resolute));
-}
--- /dev/null
+// run-pass
+
+#![allow(non_camel_case_types)]
+
+
+#[derive(Copy, Clone, Debug)]
+enum foo { large, small, }
+
+impl PartialEq for foo {
+ fn eq(&self, other: &foo) -> bool {
+ ((*self) as usize) == ((*other) as usize)
+ }
+ fn ne(&self, other: &foo) -> bool { !(*self).eq(other) }
+}
+
+pub fn main() {
+ let a = (1, 2, 3);
+ let b = (1, 2, 3);
+ assert_eq!(a, b);
+ assert!((a != (1, 2, 4)));
+ assert!((a < (1, 2, 4)));
+ assert!((a <= (1, 2, 4)));
+ assert!(((1, 2, 4) > a));
+ assert!(((1, 2, 4) >= a));
+ let x = foo::large;
+ let y = foo::small;
+ assert!((x != y));
+ assert_eq!(x, foo::large);
+ assert!((x != foo::small));
+}
--- /dev/null
+// run-pass
+struct A;
+
+impl A {
+ fn take_mutably(&mut self) {}
+}
+
+fn identity<T>(t: T) -> T {
+ t
+}
+
+// Issue 46095
+// Built-in indexing should be used even when the index is not
+// trivially an integer
+// Overloaded indexing would cause wrapped to be borrowed mutably
+
+fn main() {
+ let mut a1 = A;
+ let mut a2 = A;
+
+ let wrapped = [&mut a1, &mut a2];
+
+ {
+ wrapped[0 + 1 - 1].take_mutably();
+ }
+
+ {
+ wrapped[identity(0)].take_mutably();
+ }
+}
--- /dev/null
+// run-pass
+
+fn f(x: Box<isize>) {
+ let y: &isize = &*x;
+ println!("{}", *x);
+ println!("{}", *y);
+}
+
+trait Trait {
+ fn printme(&self);
+}
+
+struct Struct;
+
+impl Trait for Struct {
+ fn printme(&self) {
+ println!("hello world!");
+ }
+}
+
+fn g(x: Box<dyn Trait>) {
+ x.printme();
+ let y: &dyn Trait = &*x;
+ y.printme();
+}
+
+fn main() {
+ f(Box::new(1234));
+ g(Box::new(Struct) as Box<dyn Trait>);
+}
--- /dev/null
+extern "C" {
+ fn foo(a: i32, ...);
+}
+
+fn bar(_: *const u8) {}
+
+fn main() {
+ unsafe {
+ foo(0, bar);
+ //~^ ERROR can't pass `fn(*const u8) {bar}` to variadic function
+ //~| HELP cast the value to `fn(*const u8)`
+ }
+}
--- /dev/null
+error[E0617]: can't pass `fn(*const u8) {bar}` to variadic function
+ --> $DIR/issue-32201.rs:9:16
+ |
+LL | foo(0, bar);
+ | ^^^ help: cast the value to `fn(*const u8)`: `bar as fn(*const u8)`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0617`.
--- /dev/null
+// run-pass
+
+pub fn main() {
+ let f = 1_usize as *const String;
+ println!("{:?}", f as isize);
+ println!("{:?}", f as usize);
+ println!("{:?}", f as i8);
+ println!("{:?}", f as i16);
+ println!("{:?}", f as i32);
+ println!("{:?}", f as i64);
+ println!("{:?}", f as u8);
+ println!("{:?}", f as u16);
+ println!("{:?}", f as u32);
+ println!("{:?}", f as u64);
+
+ println!("{:?}", 1 as isize);
+ println!("{:?}", 1 as usize);
+ println!("{:?}", 1 as *const String);
+ println!("{:?}", 1 as i8);
+ println!("{:?}", 1 as i16);
+ println!("{:?}", 1 as i32);
+ println!("{:?}", 1 as i64);
+ println!("{:?}", 1 as u8);
+ println!("{:?}", 1 as u16);
+ println!("{:?}", 1 as u32);
+ println!("{:?}", 1 as u64);
+ println!("{:?}", 1 as f32);
+ println!("{:?}", 1 as f64);
+
+ println!("{:?}", 1_usize as isize);
+ println!("{:?}", 1_usize as usize);
+ println!("{:?}", 1_usize as *const String);
+ println!("{:?}", 1_usize as i8);
+ println!("{:?}", 1_usize as i16);
+ println!("{:?}", 1_usize as i32);
+ println!("{:?}", 1_usize as i64);
+ println!("{:?}", 1_usize as u8);
+ println!("{:?}", 1_usize as u16);
+ println!("{:?}", 1_usize as u32);
+ println!("{:?}", 1_usize as u64);
+ println!("{:?}", 1_usize as f32);
+ println!("{:?}", 1_usize as f64);
+
+ println!("{:?}", 1i8 as isize);
+ println!("{:?}", 1i8 as usize);
+ println!("{:?}", 1i8 as *const String);
+ println!("{:?}", 1i8 as i8);
+ println!("{:?}", 1i8 as i16);
+ println!("{:?}", 1i8 as i32);
+ println!("{:?}", 1i8 as i64);
+ println!("{:?}", 1i8 as u8);
+ println!("{:?}", 1i8 as u16);
+ println!("{:?}", 1i8 as u32);
+ println!("{:?}", 1i8 as u64);
+ println!("{:?}", 1i8 as f32);
+ println!("{:?}", 1i8 as f64);
+
+ println!("{:?}", 1u8 as isize);
+ println!("{:?}", 1u8 as usize);
+ println!("{:?}", 1u8 as *const String);
+ println!("{:?}", 1u8 as i8);
+ println!("{:?}", 1u8 as i16);
+ println!("{:?}", 1u8 as i32);
+ println!("{:?}", 1u8 as i64);
+ println!("{:?}", 1u8 as u8);
+ println!("{:?}", 1u8 as u16);
+ println!("{:?}", 1u8 as u32);
+ println!("{:?}", 1u8 as u64);
+ println!("{:?}", 1u8 as f32);
+ println!("{:?}", 1u8 as f64);
+
+ println!("{:?}", 1i16 as isize);
+ println!("{:?}", 1i16 as usize);
+ println!("{:?}", 1i16 as *const String);
+ println!("{:?}", 1i16 as i8);
+ println!("{:?}", 1i16 as i16);
+ println!("{:?}", 1i16 as i32);
+ println!("{:?}", 1i16 as i64);
+ println!("{:?}", 1i16 as u8);
+ println!("{:?}", 1i16 as u16);
+ println!("{:?}", 1i16 as u32);
+ println!("{:?}", 1i16 as u64);
+ println!("{:?}", 1i16 as f32);
+ println!("{:?}", 1i16 as f64);
+
+ println!("{:?}", 1u16 as isize);
+ println!("{:?}", 1u16 as usize);
+ println!("{:?}", 1u16 as *const String);
+ println!("{:?}", 1u16 as i8);
+ println!("{:?}", 1u16 as i16);
+ println!("{:?}", 1u16 as i32);
+ println!("{:?}", 1u16 as i64);
+ println!("{:?}", 1u16 as u8);
+ println!("{:?}", 1u16 as u16);
+ println!("{:?}", 1u16 as u32);
+ println!("{:?}", 1u16 as u64);
+ println!("{:?}", 1u16 as f32);
+ println!("{:?}", 1u16 as f64);
+
+ println!("{:?}", 1i32 as isize);
+ println!("{:?}", 1i32 as usize);
+ println!("{:?}", 1i32 as *const String);
+ println!("{:?}", 1i32 as i8);
+ println!("{:?}", 1i32 as i16);
+ println!("{:?}", 1i32 as i32);
+ println!("{:?}", 1i32 as i64);
+ println!("{:?}", 1i32 as u8);
+ println!("{:?}", 1i32 as u16);
+ println!("{:?}", 1i32 as u32);
+ println!("{:?}", 1i32 as u64);
+ println!("{:?}", 1i32 as f32);
+ println!("{:?}", 1i32 as f64);
+
+ println!("{:?}", 1u32 as isize);
+ println!("{:?}", 1u32 as usize);
+ println!("{:?}", 1u32 as *const String);
+ println!("{:?}", 1u32 as i8);
+ println!("{:?}", 1u32 as i16);
+ println!("{:?}", 1u32 as i32);
+ println!("{:?}", 1u32 as i64);
+ println!("{:?}", 1u32 as u8);
+ println!("{:?}", 1u32 as u16);
+ println!("{:?}", 1u32 as u32);
+ println!("{:?}", 1u32 as u64);
+ println!("{:?}", 1u32 as f32);
+ println!("{:?}", 1u32 as f64);
+
+ println!("{:?}", 1i64 as isize);
+ println!("{:?}", 1i64 as usize);
+ println!("{:?}", 1i64 as *const String);
+ println!("{:?}", 1i64 as i8);
+ println!("{:?}", 1i64 as i16);
+ println!("{:?}", 1i64 as i32);
+ println!("{:?}", 1i64 as i64);
+ println!("{:?}", 1i64 as u8);
+ println!("{:?}", 1i64 as u16);
+ println!("{:?}", 1i64 as u32);
+ println!("{:?}", 1i64 as u64);
+ println!("{:?}", 1i64 as f32);
+ println!("{:?}", 1i64 as f64);
+
+ println!("{:?}", 1u64 as isize);
+ println!("{:?}", 1u64 as usize);
+ println!("{:?}", 1u64 as *const String);
+ println!("{:?}", 1u64 as i8);
+ println!("{:?}", 1u64 as i16);
+ println!("{:?}", 1u64 as i32);
+ println!("{:?}", 1u64 as i64);
+ println!("{:?}", 1u64 as u8);
+ println!("{:?}", 1u64 as u16);
+ println!("{:?}", 1u64 as u32);
+ println!("{:?}", 1u64 as u64);
+ println!("{:?}", 1u64 as f32);
+ println!("{:?}", 1u64 as f64);
+
+ println!("{:?}", 1u64 as isize);
+ println!("{:?}", 1u64 as usize);
+ println!("{:?}", 1u64 as *const String);
+ println!("{:?}", 1u64 as i8);
+ println!("{:?}", 1u64 as i16);
+ println!("{:?}", 1u64 as i32);
+ println!("{:?}", 1u64 as i64);
+ println!("{:?}", 1u64 as u8);
+ println!("{:?}", 1u64 as u16);
+ println!("{:?}", 1u64 as u32);
+ println!("{:?}", 1u64 as u64);
+ println!("{:?}", 1u64 as f32);
+ println!("{:?}", 1u64 as f64);
+
+ println!("{:?}", true as isize);
+ println!("{:?}", true as usize);
+ println!("{:?}", true as i8);
+ println!("{:?}", true as i16);
+ println!("{:?}", true as i32);
+ println!("{:?}", true as i64);
+ println!("{:?}", true as u8);
+ println!("{:?}", true as u16);
+ println!("{:?}", true as u32);
+ println!("{:?}", true as u64);
+
+ println!("{:?}", 1f32 as isize);
+ println!("{:?}", 1f32 as usize);
+ println!("{:?}", 1f32 as i8);
+ println!("{:?}", 1f32 as i16);
+ println!("{:?}", 1f32 as i32);
+ println!("{:?}", 1f32 as i64);
+ println!("{:?}", 1f32 as u8);
+ println!("{:?}", 1f32 as u16);
+ println!("{:?}", 1f32 as u32);
+ println!("{:?}", 1f32 as u64);
+ println!("{:?}", 1f32 as f32);
+ println!("{:?}", 1f32 as f64);
+
+ println!("{:?}", 1f64 as isize);
+ println!("{:?}", 1f64 as usize);
+ println!("{:?}", 1f64 as i8);
+ println!("{:?}", 1f64 as i16);
+ println!("{:?}", 1f64 as i32);
+ println!("{:?}", 1f64 as i64);
+ println!("{:?}", 1f64 as u8);
+ println!("{:?}", 1f64 as u16);
+ println!("{:?}", 1f64 as u32);
+ println!("{:?}", 1f64 as u64);
+ println!("{:?}", 1f64 as f32);
+ println!("{:?}", 1f64 as f64);
+}
+++ /dev/null
-// ignore-msvc FIXME #31306
-
-// note that these aux-build directives must be in this order
-// aux-build:changing-crates-a1.rs
-// aux-build:changing-crates-b.rs
-// aux-build:changing-crates-a2.rs
-// normalize-stderr-test: "(crate `(\w+)`:) .*" -> "$1 $$PATH_$2"
-
-extern crate a;
-extern crate b; //~ ERROR: found possibly newer version of crate `a` which `b` depends on
-
-fn main() {}
+++ /dev/null
-error[E0460]: found possibly newer version of crate `a` which `b` depends on
- --> $DIR/changing-crates.rs:10:1
- |
-LL | extern crate b;
- | ^^^^^^^^^^^^^^^
- |
- = note: perhaps that crate needs to be recompiled?
- = note: the following crate versions were found:
- crate `a`: $PATH_a
- crate `b`: $PATH_b
-
-error: aborting due to previous error
-
--- /dev/null
+#![feature(box_syntax)]
+
+fn main() {
+ let x: Box<_> = box 1;
+ let f = move|| {
+ let _a = x;
+ drop(x);
+ //~^ ERROR: use of moved value: `x`
+ };
+ f();
+}
--- /dev/null
+error[E0382]: use of moved value: `x`
+ --> $DIR/issue-10398.rs:7:14
+ |
+LL | let _a = x;
+ | - value moved here
+LL | drop(x);
+ | ^ value used here after move
+ |
+ = note: move occurs because `x` has type `Box<i32>`, which does not implement the `Copy` trait
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0382`.
--- /dev/null
+// run-pass
+use std::ops::{Deref, DerefMut};
+
+struct CheckedDeref<T, F> {
+ value: T,
+ check: F
+}
+
+impl<F: Fn(&T) -> bool, T> Deref for CheckedDeref<T, F> {
+ type Target = T;
+ fn deref(&self) -> &T {
+ assert!((self.check)(&self.value));
+ &self.value
+ }
+}
+
+impl<F: Fn(&T) -> bool, T> DerefMut for CheckedDeref<T, F> {
+ fn deref_mut(&mut self) -> &mut T {
+ assert!((self.check)(&self.value));
+ &mut self.value
+ }
+}
+
+
+fn main() {
+ let mut v = CheckedDeref {
+ value: vec![0],
+ check: |v: &Vec<_>| !v.is_empty()
+ };
+ v.push(1);
+ assert_eq!(*v, vec![0, 1]);
+}
| expected due to this
|
= note: expected unit type `()`
- found closure `[mod1::f<T>::{closure#0} closure_substs=(unavailable) substs=[T, _#25t, extern "rust-call" fn(()), _#26t]]`
+ found closure `[mod1::f<T>::{closure#0} closure_substs=(unavailable) substs=[T, _#22t, extern "rust-call" fn(()), _#23t]]`
help: use parentheses to call this closure
|
LL | let c1 : () = c();
| expected due to this
|
= note: expected unit type `()`
- found closure `[f<T>::{closure#0} closure_substs=(unavailable) substs=[T, _#25t, extern "rust-call" fn(()), _#26t]]`
+ found closure `[f<T>::{closure#0} closure_substs=(unavailable) substs=[T, _#22t, extern "rust-call" fn(()), _#23t]]`
help: use parentheses to call this closure
|
LL | let c1 : () = c();
--- /dev/null
+#![crate_type="rlib"]
+
+#[derive(Debug, PartialEq)]
+pub struct RemoteC(pub u32);
+
+#[derive(Debug, PartialEq)]
+pub struct RemoteG<T>(pub T);
--- /dev/null
+// run-pass
+// All 3 expressions should work in that the argument gets
+// coerced to a trait object
+
+// pretty-expanded FIXME #23616
+
+fn main() {
+ send::<Box<dyn Foo>>(Box::new(Output(0)));
+ Test::<Box<dyn Foo>>::foo(Box::new(Output(0)));
+ Test::<Box<dyn Foo>>::new().send(Box::new(Output(0)));
+}
+
+fn send<T>(_: T) {}
+
+struct Test<T> { marker: std::marker::PhantomData<T> }
+impl<T> Test<T> {
+ fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } }
+ fn foo(_: T) {}
+ fn send(&self, _: T) {}
+}
+
+trait Foo { fn dummy(&self) { }}
+struct Output(isize);
+impl Foo for Output {}
--- /dev/null
+// run-pass
+// aux-build:issue-39823.rs
+
+extern crate issue_39823;
+use issue_39823::{RemoteC, RemoteG};
+
+#[derive(Debug, PartialEq)]
+struct LocalC(u32);
+
+#[derive(Debug, PartialEq)]
+struct LocalG<T>(T);
+
+fn main() {
+ let virtual_localc : &dyn Fn(_) -> LocalC = &LocalC;
+ assert_eq!(virtual_localc(1), LocalC(1));
+
+ let virtual_localg : &dyn Fn(_) -> LocalG<u32> = &LocalG;
+ assert_eq!(virtual_localg(1), LocalG(1));
+
+ let virtual_remotec : &dyn Fn(_) -> RemoteC = &RemoteC;
+ assert_eq!(virtual_remotec(1), RemoteC(1));
+
+ let virtual_remoteg : &dyn Fn(_) -> RemoteG<u32> = &RemoteG;
+ assert_eq!(virtual_remoteg(1), RemoteG(1));
+}
--- /dev/null
+fn main() {
+ let _ = &&[0] as &[_];
+ //~^ ERROR non-primitive cast: `&&[i32; 1]` as `&[_]`
+ let _ = 7u32 as Option<_>;
+ //~^ ERROR non-primitive cast: `u32` as `Option<_>`
+}
--- /dev/null
+error[E0605]: non-primitive cast: `&&[i32; 1]` as `&[_]`
+ --> $DIR/issue-73886.rs:2:13
+ |
+LL | let _ = &&[0] as &[_];
+ | ^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
+
+error[E0605]: non-primitive cast: `u32` as `Option<_>`
+ --> $DIR/issue-73886.rs:4:13
+ |
+LL | let _ = 7u32 as Option<_>;
+ | ^^^^^^^^^^^^^^^^^ help: consider using the `From` trait instead: `Option<_>::from(7u32)`
+ |
+ = note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0605`.
--- /dev/null
+// check-pass
+
+macro_rules! m {
+ () => { #[cfg(any())] fn f() {} }
+}
+
+trait T {}
+impl T for () { m!(); }
+
+fn main() {}
--- /dev/null
+#![feature(rustc_attrs)]
+
+#[rustc_legacy_const_generics(1)]
+pub fn foo<const Y: usize>(x: usize, z: usize) -> [usize; 3] {
+ [x, Y, z]
+}
--- /dev/null
+// aux-build:legacy-const-generics.rs
+
+extern crate legacy_const_generics;
+
+fn foo<const N: usize>() {
+ let a = 1;
+ legacy_const_generics::foo(0, a, 2);
+ //~^ ERROR attempt to use a non-constant value in a constant
+
+ legacy_const_generics::foo(0, N, 2);
+
+ legacy_const_generics::foo(0, N + 1, 2);
+ //~^ ERROR generic parameters may not be used in const operations
+}
+
+fn main() {}
--- /dev/null
+error[E0435]: attempt to use a non-constant value in a constant
+ --> $DIR/legacy-const-generics-bad.rs:7:35
+ |
+LL | let a = 1;
+ | ----- help: consider using `const` instead of `let`: `const a`
+LL | legacy_const_generics::foo(0, a, 2);
+ | ^ non-constant value
+
+error: generic parameters may not be used in const operations
+ --> $DIR/legacy-const-generics-bad.rs:12:35
+ |
+LL | legacy_const_generics::foo(0, N + 1, 2);
+ | ^ cannot perform const operation using `N`
+ |
+ = help: const parameters may only be used as standalone arguments, i.e. `N`
+ = help: use `#![feature(generic_const_exprs)]` to allow generic const expressions
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0435`.
--- /dev/null
+// aux-build:legacy-const-generics.rs
+// run-pass
+
+#![feature(rustc_attrs)]
+
+extern crate legacy_const_generics;
+
+#[rustc_legacy_const_generics(1)]
+pub fn bar<const Y: usize>(x: usize, z: usize) -> [usize; 3] {
+ [x, Y, z]
+}
+
+fn main() {
+ assert_eq!(legacy_const_generics::foo(0 + 0, 1 + 1, 2 + 2), [0, 2, 4]);
+ assert_eq!(legacy_const_generics::foo::<{1 + 1}>(0 + 0, 2 + 2), [0, 2, 4]);
+ // FIXME: Only works cross-crate
+ //assert_eq!(bar(0, 1, 2), [0, 1, 2]);
+}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+#![allow(non_camel_case_types)]
+
+const JSVAL_TAG_CLEAR: u32 = 0xFFFFFF80;
+const JSVAL_TYPE_INT32: u8 = 0x01;
+const JSVAL_TYPE_UNDEFINED: u8 = 0x02;
+#[repr(u32)]
+enum ValueTag {
+ JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | (JSVAL_TYPE_INT32 as u32),
+ JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | (JSVAL_TYPE_UNDEFINED as u32),
+}
+
+fn main() {
+ let _ = ValueTag::JSVAL_TAG_INT32;
+}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+
+static X2: u64 = !0 as u16 as u64;
+static Y2: u64 = !0 as u32 as u64;
+const X: u64 = !0 as u16 as u64;
+const Y: u64 = !0 as u32 as u64;
+
+fn main() {
+ assert_eq!(match 1 {
+ X => unreachable!(),
+ Y => unreachable!(),
+ _ => 1
+ }, 1);
+}
--- /dev/null
+fn main() {
+ const X: u32 = 1;
+ const Y: usize = unsafe { &X as *const u32 as usize }; //~ ERROR pointers cannot be cast to integers
+ println!("{}", Y);
+}
--- /dev/null
+error: pointers cannot be cast to integers during const eval
+ --> $DIR/issue-18294.rs:3:31
+ |
+LL | const Y: usize = unsafe { &X as *const u32 as usize };
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^
+ |
+ = note: at compile-time, pointers do not have an integer value
+ = note: avoiding this restriction via `transmute`, `union`, or raw pointers leads to compile-time undefined behavior
+
+error: aborting due to previous error
+
--- /dev/null
+// run-pass
+const U8_MAX_HALF: u8 = !0u8 / 2;
+const U16_MAX_HALF: u16 = !0u16 / 2;
+const U32_MAX_HALF: u32 = !0u32 / 2;
+const U64_MAX_HALF: u64 = !0u64 / 2;
+
+fn main() {
+ assert_eq!(U8_MAX_HALF, 0x7f);
+ assert_eq!(U16_MAX_HALF, 0x7fff);
+ assert_eq!(U32_MAX_HALF, 0x7fff_ffff);
+ assert_eq!(U64_MAX_HALF, 0x7fff_ffff_ffff_ffff);
+}
--- /dev/null
+const fn x() {
+ let t = true;
+ let x = || t; //~ ERROR function pointer
+}
+
+fn main() {}
--- /dev/null
+error[E0658]: function pointers cannot appear in constant functions
+ --> $DIR/issue-37550-1.rs:3:9
+ |
+LL | let x = || t;
+ | ^
+ |
+ = note: see issue #57563 <https://github.com/rust-lang/rust/issues/57563> for more information
+ = help: add `#![feature(const_fn_fn_ptr_basics)]` to the crate attributes to enable
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0658`.
--- /dev/null
+// run-pass
+
+const fn foo() -> i64 {
+ 3
+}
+
+const fn bar(x: i64) -> i64 {
+ x*2
+}
+
+fn main() {
+ let val = &(foo() % 2);
+ assert_eq!(*val, 1);
+
+ let val2 = &(bar(1+1) % 3);
+ assert_eq!(*val2, 1);
+}
--- /dev/null
+// compile-flags: --crate-type lib --extern foo={{src-base}}/crate-loading/auxiliary/libfoo.rlib
+// normalize-stderr-test: "failed to mmap file '.*auxiliary/libfoo.rlib':.*" -> "failed to mmap file 'auxiliary/libfoo.rlib'"
+// don't emit warn logging, it's basically the same as the errors and it's annoying to normalize
+// rustc-env:RUSTC_LOG=error
+// edition:2018
+#![no_std]
+use ::foo; //~ ERROR invalid metadata files for crate `foo`
+//~| NOTE failed to mmap file
--- /dev/null
+error[E0786]: found invalid metadata files for crate `foo`
+ --> $DIR/invalid-rlib.rs:7:7
+ |
+LL | use ::foo;
+ | ^^^
+ |
+ = note: failed to mmap file 'auxiliary/libfoo.rlib'
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0786`.
--- /dev/null
+// compile-flags: --edition 2018
+fn foo() -> Result<(), ()> {
+ Ok(try!()); //~ ERROR use of deprecated `try` macro
+ Ok(try!(Ok(()))) //~ ERROR use of deprecated `try` macro
+}
+
+fn main() {
+ let _ = foo();
+}
--- /dev/null
+error: use of deprecated `try` macro
+ --> $DIR/try-macro-suggestion.rs:3:8
+ |
+LL | Ok(try!());
+ | ^^^^^^
+ |
+ = note: in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated
+help: you can still access the deprecated `try!()` macro using the "raw identifier" syntax
+ |
+LL | Ok(r#try!());
+ | ++
+
+error: use of deprecated `try` macro
+ --> $DIR/try-macro-suggestion.rs:4:8
+ |
+LL | Ok(try!(Ok(())))
+ | ^^^^^^^^^^^^
+ |
+ = note: in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated
+help: you can use the `?` operator instead
+ |
+LL - Ok(try!(Ok(())))
+LL + Ok(Ok(())?)
+ |
+help: alternatively, you can still access the deprecated `try!()` macro using the "raw identifier" syntax
+ |
+LL | Ok(r#try!(Ok(())))
+ | ++
+
+error: aborting due to 2 previous errors
+
--- /dev/null
+// run-pass
+
+#![allow(dead_code)]
+
+trait Trait { fn dummy(&self) { } }
+
+#[derive(Debug)]
+struct Foo<T: Trait> {
+ foo: T,
+}
+
+#[derive(Debug)]
+struct Bar<T> where T: Trait {
+ bar: T,
+}
+
+impl Trait for isize {}
+
+fn main() {
+ let a = Foo { foo: 12 };
+ let b = Bar { bar: 12 };
+ println!("{:?} {:?}", a, b);
+}
--- /dev/null
+// run-pass
+fn main() {}
+#[derive(Clone)]
+pub struct Little;
+#[derive(Clone)]
+pub struct Big(
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+ Little,
+);
+++ /dev/null
-// After #39485, this test used to pass, but that change was reverted
-// due to numerous inference failures like #39808, so it now fails
-// again. #39485 made it so that diverging types never propagate
-// upward; but we now do propagate such types upward in many more
-// cases.
-
-fn g() {
- &panic!() //~ ERROR mismatched types
-}
-
-fn f() -> isize {
- (return 1, return 2) //~ ERROR mismatched types
-}
-
-fn main() {}
+++ /dev/null
-error[E0308]: mismatched types
- --> $DIR/diverging-tuple-parts-39485.rs:8:5
- |
-LL | &panic!()
- | ^^^^^^^^^ expected `()`, found reference
- |
- = note: expected unit type `()`
- found reference `&_`
-help: try adding a return type
- |
-LL | fn g() -> &_ {
- | +++++
-help: consider removing the borrow
- |
-LL - &panic!()
-LL + panic!()
- |
-
-error[E0308]: mismatched types
- --> $DIR/diverging-tuple-parts-39485.rs:12:5
- |
-LL | fn f() -> isize {
- | ----- expected `isize` because of return type
-LL | (return 1, return 2)
- | ^^^^^^^^^^^^^^^^^^^^ expected `isize`, found tuple
- |
- = note: expected type `isize`
- found tuple `(!, !)`
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0308`.
--- /dev/null
+// build-pass
+#![allow(dead_code)]
+// Regression test for #35546. Check that we are able to codegen
+// this. Before we had problems because of the drop glue signature
+// around dropping a trait object (specifically, when dropping the
+// `value` field of `Node<Send>`).
+
+struct Node<T: ?Sized + Send> {
+ next: Option<Box<Node<dyn Send>>>,
+ value: T,
+}
+
+fn clear(head: &mut Option<Box<Node<dyn Send>>>) {
+ match head.take() {
+ Some(node) => *head = node.next,
+ None => (),
+ }
+}
+
+fn main() {}
--- /dev/null
+// run-pass
+// ignore-emscripten no threads support
+
+// Issue #787
+// Don't try to clean up uninitialized locals
+
+
+use std::thread;
+
+fn test_break() { loop { let _x: Box<isize> = break; } }
+
+fn test_cont() { let mut i = 0; while i < 1 { i += 1; let _x: Box<isize> = continue; } }
+
+fn test_ret() { let _x: Box<isize> = return; }
+
+fn test_panic() {
+ fn f() { let _x: Box<isize> = panic!(); }
+ thread::spawn(move|| f() ).join().unwrap_err();
+}
+
+fn test_panic_indirect() {
+ fn f() -> ! { panic!(); }
+ fn g() { let _x: Box<isize> = f(); }
+ thread::spawn(move|| g() ).join().unwrap_err();
+}
+
+pub fn main() {
+ test_break();
+ test_cont();
+ test_ret();
+ test_panic();
+ test_panic_indirect();
+}
--- /dev/null
+// run-pass
+
+// Demonstrate the use of the unguarded escape hatch with a type param in negative position
+// to assert that destructor will not access any dead data.
+//
+// Compare with ui/span/issue28498-reject-lifetime-param.rs
+
+// Demonstrate that a type param in negative position causes dropck to reject code
+// that might indirectly access previously dropped value.
+//
+// Compare with run-pass/issue28498-ugeh-with-passed-to-fn.rs
+
+#![feature(dropck_eyepatch)]
+
+#[derive(Debug)]
+struct ScribbleOnDrop(String);
+
+impl Drop for ScribbleOnDrop {
+ fn drop(&mut self) {
+ self.0 = format!("DROPPED");
+ }
+}
+
+struct Foo<T>(u32, T, Box<for <'r> fn(&'r T) -> String>);
+
+unsafe impl<#[may_dangle] T> Drop for Foo<T> {
+ fn drop(&mut self) {
+ // Use of `may_dangle` is sound, because destructor never passes a `self.1`
+ // to the callback (in `self.2`) despite having it available.
+ println!("Dropping Foo({}, _)", self.0);
+ }
+}
+
+fn callback(s: & &ScribbleOnDrop) -> String { format!("{:?}", s) }
+
+fn main() {
+ let (last_dropped, foo0);
+ let (foo1, first_dropped);
+
+ last_dropped = ScribbleOnDrop(format!("last"));
+ first_dropped = ScribbleOnDrop(format!("first"));
+ foo0 = Foo(0, &last_dropped, Box::new(callback));
+ foo1 = Foo(1, &first_dropped, Box::new(callback));
+
+ println!("foo0.1: {:?} foo1.1: {:?}", foo0.1, foo1.1);
+}
+++ /dev/null
-// edition:2015
-
-mod inner {
- fn global_inner(_: ::nonexistant::Foo) {
- //~^ ERROR failed to resolve: maybe a missing crate `nonexistant`?
- }
- fn crate_inner(_: crate::nonexistant::Foo) {
- //~^ ERROR failed to resolve: maybe a missing crate `nonexistant`?
- }
-
- fn bare_global(_: ::nonexistant) {
- //~^ ERROR cannot find type `nonexistant` in the crate root
- }
- fn bare_crate(_: crate::nonexistant) {
- //~^ ERROR cannot find type `nonexistant` in the crate root
- }
-}
-
-fn main() {
-
-}
+++ /dev/null
-error[E0433]: failed to resolve: maybe a missing crate `nonexistant`?
- --> $DIR/editions-crate-root-2015.rs:4:26
- |
-LL | fn global_inner(_: ::nonexistant::Foo) {
- | ^^^^^^^^^^^ maybe a missing crate `nonexistant`?
-
-error[E0433]: failed to resolve: maybe a missing crate `nonexistant`?
- --> $DIR/editions-crate-root-2015.rs:7:30
- |
-LL | fn crate_inner(_: crate::nonexistant::Foo) {
- | ^^^^^^^^^^^ maybe a missing crate `nonexistant`?
-
-error[E0412]: cannot find type `nonexistant` in the crate root
- --> $DIR/editions-crate-root-2015.rs:11:25
- |
-LL | fn bare_global(_: ::nonexistant) {
- | ^^^^^^^^^^^ not found in the crate root
-
-error[E0412]: cannot find type `nonexistant` in the crate root
- --> $DIR/editions-crate-root-2015.rs:14:29
- |
-LL | fn bare_crate(_: crate::nonexistant) {
- | ^^^^^^^^^^^ not found in the crate root
-
-error: aborting due to 4 previous errors
-
-Some errors have detailed explanations: E0412, E0433.
-For more information about an error, try `rustc --explain E0412`.
--- /dev/null
+// run-pass
+
+#![allow(dead_code)]
+#![allow(unused_variables)]
+// Checks if the correct registers are being used to pass arguments
+// when the sysv64 ABI is specified.
+
+#![feature(rust_2018_preview)]
+
+pub trait Foo {}
+
+// should compile without the dyn trait feature flag
+fn foo(x: &dyn Foo) {}
+
+pub fn main() {}
--- /dev/null
+// run-pass
+#![feature(core_intrinsics)]
+
+#[repr(i8)]
+pub enum Enum {
+ VariantA,
+ VariantB,
+}
+
+fn make_b() -> Enum { Enum::VariantB }
+
+fn main() {
+ assert_eq!(1, make_b() as i8);
+ assert_eq!(1, make_b() as u8);
+ assert_eq!(1, make_b() as i32);
+ assert_eq!(1, make_b() as u32);
+ assert_eq!(1, std::intrinsics::discriminant_value(&make_b()));
+}
--- /dev/null
+// run-pass
+macro_rules! fooN {
+ ($cur:ident $prev:ty) => {
+ #[allow(dead_code)]
+ enum $cur {
+ Empty,
+ First($prev),
+ Second($prev),
+ Third($prev),
+ Fourth($prev),
+ }
+ }
+}
+
+fooN!(Foo0 ());
+fooN!(Foo1 Foo0);
+fooN!(Foo2 Foo1);
+fooN!(Foo3 Foo2);
+fooN!(Foo4 Foo3);
+fooN!(Foo5 Foo4);
+fooN!(Foo6 Foo5);
+fooN!(Foo7 Foo6);
+fooN!(Foo8 Foo7);
+fooN!(Foo9 Foo8);
+fooN!(Foo10 Foo9);
+fooN!(Foo11 Foo10);
+fooN!(Foo12 Foo11);
+fooN!(Foo13 Foo12);
+fooN!(Foo14 Foo13);
+fooN!(Foo15 Foo14);
+fooN!(Foo16 Foo15);
+fooN!(Foo17 Foo16);
+fooN!(Foo18 Foo17);
+fooN!(Foo19 Foo18);
+fooN!(Foo20 Foo19);
+fooN!(Foo21 Foo20);
+fooN!(Foo22 Foo21);
+fooN!(Foo23 Foo22);
+fooN!(Foo24 Foo23);
+fooN!(Foo25 Foo24);
+fooN!(Foo26 Foo25);
+fooN!(Foo27 Foo26);
+
+fn main() {
+ let _foo = Foo27::Empty;
+}
+++ /dev/null
-// run-pass
-
-#![allow(dead_code)]
-#![allow(unused_variables)]
-// Checks if the correct registers are being used to pass arguments
-// when the sysv64 ABI is specified.
-
-#![feature(rust_2018_preview)]
-
-pub trait Foo {}
-
-// should compile without the dyn trait feature flag
-fn foo(x: &dyn Foo) {}
-
-pub fn main() {}
--- /dev/null
+error[E0133]: use of extern static is unsafe and requires unsafe function or block
+ --> $DIR/issue-28324.rs:8:24
+ |
+LL | pub static BAZ: u32 = *&error_message_count;
+ | ^^^^^^^^^^^^^^^^^^^^ use of extern static
+ |
+ = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0133`.
--- /dev/null
+// revisions: mir thir
+// [thir]compile-flags: -Z thir-unsafeck
+
+extern "C" {
+ static error_message_count: u32;
+}
+
+pub static BAZ: u32 = *&error_message_count;
+//~^ ERROR use of extern static is unsafe and requires
+
+fn main() {}
--- /dev/null
+error[E0133]: use of extern static is unsafe and requires unsafe function or block
+ --> $DIR/issue-28324.rs:8:25
+ |
+LL | pub static BAZ: u32 = *&error_message_count;
+ | ^^^^^^^^^^^^^^^^^^^ use of extern static
+ |
+ = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0133`.
--- /dev/null
+// run-pass
+#![allow(unreachable_code)]
+
+fn main() {
+ let mut v = Vec::new();
+
+ loop { v.push(break) }
+}
--- /dev/null
+// run-pass
+// pretty-expanded FIXME #23616
+
+#![allow(unused_variables)]
+
+pub fn main() {
+ let mut i: isize = 0;
+ while i < 1000000 {
+ i += 1;
+ let x = 3;
+ }
+}
--- /dev/null
+// run-pass
+
+#![allow(improper_ctypes)]
+#![allow(dead_code)]
+// Issue #901
+// pretty-expanded FIXME #23616
+
+mod libc {
+ extern "C" {
+ pub fn printf(x: ());
+ }
+}
+
+pub fn main() {}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+// Issue #1112
+// Alignment of interior pointers to dynamic-size types
+
+
+struct X<T> {
+ a: T,
+ b: u8,
+ c: bool,
+ d: u8,
+ e: u16,
+ f: u8,
+ g: u8
+}
+
+pub fn main() {
+ let x: X<isize> = X {
+ a: 12345678,
+ b: 9,
+ c: true,
+ d: 10,
+ e: 11,
+ f: 12,
+ g: 13
+ };
+ bar(x);
+}
+
+fn bar<T>(x: X<T>) {
+ assert_eq!(x.b, 9);
+ assert_eq!(x.c, true);
+ assert_eq!(x.d, 10);
+ assert_eq!(x.e, 11);
+ assert_eq!(x.f, 12);
+ assert_eq!(x.g, 13);
+}
--- /dev/null
+// run-pass
+
+fn quux<T>(x: T) -> T { let f = id::<T>; return f(x); }
+
+fn id<T>(x: T) -> T { return x; }
+
+pub fn main() { assert_eq!(quux(10), 10); }
--- /dev/null
+#![allow(dead_code)]
+#![feature(const_generics_defaults)]
+
+// This test checks that generic parameter re-ordering diagnostic suggestions mention that
+// consts come after types and lifetimes when the `const_generics_defaults` feature is enabled.
+// We cannot run rustfix on this test because of the above const generics warning.
+
+struct A;
+
+impl A {
+ pub fn do_things<T, 'a, 'b: 'a>() {
+ //~^ ERROR lifetime parameters must be declared prior to type parameters
+ println!("panic");
+ }
+}
+
+fn main() {}
--- /dev/null
+error: lifetime parameters must be declared prior to type parameters
+ --> $DIR/issue-59508-1.rs:11:25
+ |
+LL | pub fn do_things<T, 'a, 'b: 'a>() {
+ | ----^^--^^----- help: reorder the parameters: lifetimes, then consts and types: `<'a, 'b: 'a, T>`
+
+error: aborting due to previous error
+
--- /dev/null
+// run-rustfix
+
+#![allow(dead_code)]
+
+// This test checks that generic parameter re-ordering diagnostic suggestions contain bounds.
+
+struct A;
+
+impl A {
+ pub fn do_things<'a, 'b: 'a, T>() {
+ //~^ ERROR lifetime parameters must be declared prior to type parameters
+ println!("panic");
+ }
+}
+
+fn main() {}
--- /dev/null
+// run-rustfix
+
+#![allow(dead_code)]
+
+// This test checks that generic parameter re-ordering diagnostic suggestions contain bounds.
+
+struct A;
+
+impl A {
+ pub fn do_things<T, 'a, 'b: 'a>() {
+ //~^ ERROR lifetime parameters must be declared prior to type parameters
+ println!("panic");
+ }
+}
+
+fn main() {}
--- /dev/null
+error: lifetime parameters must be declared prior to type parameters
+ --> $DIR/issue-59508.rs:10:25
+ |
+LL | pub fn do_things<T, 'a, 'b: 'a>() {
+ | ----^^--^^----- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b: 'a, T>`
+
+error: aborting due to previous error
+
--- /dev/null
+pub trait Trait<'a> {
+ type Item;
+}
+
+impl<'a> Trait<'a> for () {
+ type Item = ();
+}
+
+pub fn foo<T, F>(_: T, _: F)
+where
+ T: for<'a> Trait<'a>,
+ F: for<'a> FnMut(<T as Trait<'a>>::Item),
+{
+}
+
+fn main() {
+ foo((), drop)
+ //~^ ERROR type mismatch in function arguments
+ //~| ERROR size for values of type `<() as Trait<'_>>::Item` cannot be known at compilation time
+}
--- /dev/null
+error[E0631]: type mismatch in function arguments
+ --> $DIR/issue-60283.rs:17:13
+ |
+LL | foo((), drop)
+ | --- ^^^^
+ | | |
+ | | expected signature of `for<'a> fn(<() as Trait<'a>>::Item) -> _`
+ | | found signature of `fn(()) -> _`
+ | required by a bound introduced by this call
+ |
+note: required by a bound in `foo`
+ --> $DIR/issue-60283.rs:12:16
+ |
+LL | pub fn foo<T, F>(_: T, _: F)
+ | --- required by a bound in this
+...
+LL | F: for<'a> FnMut(<T as Trait<'a>>::Item),
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `foo`
+
+error[E0277]: the size for values of type `<() as Trait<'_>>::Item` cannot be known at compilation time
+ --> $DIR/issue-60283.rs:17:13
+ |
+LL | foo((), drop)
+ | --- ^^^^ doesn't have a size known at compile-time
+ | |
+ | required by a bound introduced by this call
+ |
+ = help: the trait `Sized` is not implemented for `<() as Trait<'_>>::Item`
+note: required by a bound in `std::mem::drop`
+ --> $SRC_DIR/core/src/mem/mod.rs:LL:COL
+ |
+LL | pub fn drop<T>(_x: T) {}
+ | ^ required by this bound in `std::mem::drop`
+help: consider further restricting the associated type
+ |
+LL | fn main() where <() as Trait<'_>>::Item: Sized {
+ | ++++++++++++++++++++++++++++++++++++
+
+error: aborting due to 2 previous errors
+
+Some errors have detailed explanations: E0277, E0631.
+For more information about an error, try `rustc --explain E0277`.
--- /dev/null
+// run-pass
+// shouldn't affect evaluation of $ex:
+macro_rules! bad_macro {
+ ($ex:expr) => ({(|_x| { $ex }) (9) })
+}
+
+fn takes_x(_x : isize) {
+ assert_eq!(bad_macro!(_x),8);
+}
+fn main() {
+ takes_x(8);
+}
--- /dev/null
+// check-pass
+
+fn fibs(n: u32) -> impl Iterator<Item=u128> {
+ (0 .. n)
+ .scan((0, 1), |st, _| {
+ *st = (st.1, st.0 + st.1);
+ Some(*st)
+ })
+ .map(&|(f, _)| f)
+}
+
+fn main() {
+ println!("{:?}", fibs(10).collect::<Vec<_>>());
+}
--- /dev/null
+// run-pass
+// Regression test for #49685: drop elaboration was not revealing the
+// value of `impl Trait` returns, leading to an ICE.
+
+fn main() {
+ let _ = Some(())
+ .into_iter()
+ .flat_map(|_| Some(()).into_iter().flat_map(func));
+}
+
+fn func(_: ()) -> impl Iterator<Item = ()> {
+ Some(()).into_iter().flat_map(|_| vec![])
+}
--- /dev/null
+// run-pass
+fn foo() -> impl Into<for<'a> fn(&'a ())> {
+ (|_| {}) as for<'a> fn(&'a ())
+}
+
+fn main() {
+ foo().into()(&());
+}
+++ /dev/null
-// run-pass
-
-#![allow(warnings)]
-#![feature(in_band_lifetimes)]
-
-fn foo(x: &'x u8) -> &'x u8 { x }
-fn foo2(x: &'a u8, y: &u8) -> &'a u8 { x }
-
-fn check_in_band_can_be_late_bound() {
- let _: for<'x> fn(&'x u8, &u8) -> &'x u8 = foo2;
-}
-
-struct ForInherentNoParams;
-
-impl ForInherentNoParams {
- fn foo(x: &'a u32, y: &u32) -> &'a u32 { x }
-}
-
-struct X<'a>(&'a u8);
-
-impl<'a> X<'a> {
- fn inner(&self) -> &'a u8 {
- self.0
- }
-
- fn same_lifetime_as_parameter(&mut self, x: &'a u8) {
- self.0 = x;
- }
-}
-
-impl X<'b> {
- fn inner_2(&self) -> &'b u8 {
- self.0
- }
-
- fn reference_already_introduced_in_band_from_method_with_explicit_binders<'a>(
- &'b self, x: &'a u32
- ) {}
-}
-
-struct Y<T>(T);
-
-impl Y<&'a u8> {
- fn inner(&self) -> &'a u8 {
- self.0
- }
-}
-
-trait MyTrait<'a> {
- fn my_lifetime(&self) -> &'a u8;
- fn any_lifetime() -> &'b u8;
- fn borrowed_lifetime(&'b self) -> &'b u8;
- fn default_impl(&self, x: &'b u32, y: &u32) -> &'b u32 { x }
- fn in_band_def_explicit_impl(&self, x: &'b u8);
-}
-
-impl MyTrait<'a> for Y<&'a u8> {
- fn my_lifetime(&self) -> &'a u8 { self.0 }
- fn any_lifetime() -> &'b u8 { &0 }
- fn borrowed_lifetime(&'b self) -> &'b u8 { &*self.0 }
- fn in_band_def_explicit_impl<'b>(&self, x: &'b u8) {}
-}
-
-fn test_hrtb_defined_lifetime_where<F>(_: F) where for<'a> F: Fn(&'a u8) {}
-fn test_hrtb_defined_lifetime_polytraitref<F>(_: F) where F: for<'a> Fn(&'a u8) {}
-
-fn reference_in_band_from_locals(x: &'test u32) -> &'test u32 {
- let y: &'test u32 = x;
- y
-}
-
-fn in_generics_in_band<T: MyTrait<'a>>(x: &T) {}
-fn where_clause_in_band<T>(x: &T) where T: MyTrait<'a> {}
-fn impl_trait_in_band(x: &impl MyTrait<'a>) {}
-
-// Tests around using in-band lifetimes within existential traits.
-
-trait FunkyTrait<'a> { }
-impl<'a, T> FunkyTrait<'a> for T { }
-fn ret_pos_impl_trait_in_band_outlives(x: &'a u32) -> impl ::std::fmt::Debug + 'a {
- x
-}
-fn ret_pos_impl_trait_in_band_param(x: &'a u32) -> impl FunkyTrait<'a> {
- x
-}
-fn ret_pos_impl_trait_in_band_param_static(x: &'a u32) -> impl FunkyTrait<'static> + 'a {
- x
-}
-fn ret_pos_impl_trait_in_band_param_outlives(x: &'a u32) -> impl FunkyTrait<'a> + 'a {
- x
-}
-fn ret_pos_impl_trait_in_band_higher_ranked(x: &'a u32) -> impl for<'b> FunkyTrait<'b> + 'a {
- x
-}
-
-fn main() {}
--- /dev/null
+// run-pass
+
+#![allow(warnings)]
+#![feature(in_band_lifetimes)]
+
+fn foo(x: &'x u8) -> &'x u8 { x }
+fn foo2(x: &'a u8, y: &u8) -> &'a u8 { x }
+
+fn check_in_band_can_be_late_bound() {
+ let _: for<'x> fn(&'x u8, &u8) -> &'x u8 = foo2;
+}
+
+struct ForInherentNoParams;
+
+impl ForInherentNoParams {
+ fn foo(x: &'a u32, y: &u32) -> &'a u32 { x }
+}
+
+struct X<'a>(&'a u8);
+
+impl<'a> X<'a> {
+ fn inner(&self) -> &'a u8 {
+ self.0
+ }
+
+ fn same_lifetime_as_parameter(&mut self, x: &'a u8) {
+ self.0 = x;
+ }
+}
+
+impl X<'b> {
+ fn inner_2(&self) -> &'b u8 {
+ self.0
+ }
+
+ fn reference_already_introduced_in_band_from_method_with_explicit_binders<'a>(
+ &'b self, x: &'a u32
+ ) {}
+}
+
+struct Y<T>(T);
+
+impl Y<&'a u8> {
+ fn inner(&self) -> &'a u8 {
+ self.0
+ }
+}
+
+trait MyTrait<'a> {
+ fn my_lifetime(&self) -> &'a u8;
+ fn any_lifetime() -> &'b u8;
+ fn borrowed_lifetime(&'b self) -> &'b u8;
+ fn default_impl(&self, x: &'b u32, y: &u32) -> &'b u32 { x }
+ fn in_band_def_explicit_impl(&self, x: &'b u8);
+}
+
+impl MyTrait<'a> for Y<&'a u8> {
+ fn my_lifetime(&self) -> &'a u8 { self.0 }
+ fn any_lifetime() -> &'b u8 { &0 }
+ fn borrowed_lifetime(&'b self) -> &'b u8 { &*self.0 }
+ fn in_band_def_explicit_impl<'b>(&self, x: &'b u8) {}
+}
+
+fn test_hrtb_defined_lifetime_where<F>(_: F) where for<'a> F: Fn(&'a u8) {}
+fn test_hrtb_defined_lifetime_polytraitref<F>(_: F) where F: for<'a> Fn(&'a u8) {}
+
+fn reference_in_band_from_locals(x: &'test u32) -> &'test u32 {
+ let y: &'test u32 = x;
+ y
+}
+
+fn in_generics_in_band<T: MyTrait<'a>>(x: &T) {}
+fn where_clause_in_band<T>(x: &T) where T: MyTrait<'a> {}
+fn impl_trait_in_band(x: &impl MyTrait<'a>) {}
+
+// Tests around using in-band lifetimes within existential traits.
+
+trait FunkyTrait<'a> { }
+impl<'a, T> FunkyTrait<'a> for T { }
+fn ret_pos_impl_trait_in_band_outlives(x: &'a u32) -> impl ::std::fmt::Debug + 'a {
+ x
+}
+fn ret_pos_impl_trait_in_band_param(x: &'a u32) -> impl FunkyTrait<'a> {
+ x
+}
+fn ret_pos_impl_trait_in_band_param_static(x: &'a u32) -> impl FunkyTrait<'static> + 'a {
+ x
+}
+fn ret_pos_impl_trait_in_band_param_outlives(x: &'a u32) -> impl FunkyTrait<'a> + 'a {
+ x
+}
+fn ret_pos_impl_trait_in_band_higher_ranked(x: &'a u32) -> impl for<'b> FunkyTrait<'b> + 'a {
+ x
+}
+
+fn main() {}
--- /dev/null
+// run-pass
+// Test for a specific corner case: when we compute the LUB of two fn
+// types and their parameters have unbound variables. In that case, we
+// wind up relating those two variables. This was causing an ICE in an
+// in-progress PR.
+
+fn main() {
+ let a_f: fn(_) = |_| ();
+ let b_f: fn(_) = |_| ();
+ let c_f = match 22 {
+ 0 => a_f,
+ _ => b_f,
+ };
+ c_f(4);
+}
+++ /dev/null
-#![crate_type = "lib"]
-
-#[macro_export]
-macro_rules! mywrite {
- ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
-}
+++ /dev/null
-#![crate_type="rlib"]
-
-#[derive(Debug, PartialEq)]
-pub struct RemoteC(pub u32);
-
-#[derive(Debug, PartialEq)]
-pub struct RemoteG<T>(pub T);
+++ /dev/null
-#![crate_type="lib"]
-
-
-pub trait A {
- fn a(&self) {}
-}
-impl A for () {}
+++ /dev/null
-#![crate_type="lib"]
-
-pub extern crate xcrate_issue_43189_a;
+++ /dev/null
-#![crate_type="lib"]
-
-pub extern crate core;
+++ /dev/null
-// edition:2018
-#![crate_type="lib"]
-#![crate_name="xcrate_issue_61711_b"]
-pub struct Struct;
-pub use crate as alias;
+++ /dev/null
-#![feature(box_syntax)]
-
-fn main() {
- let x: Box<_> = box 1;
- let f = move|| {
- let _a = x;
- drop(x);
- //~^ ERROR: use of moved value: `x`
- };
- f();
-}
+++ /dev/null
-error[E0382]: use of moved value: `x`
- --> $DIR/issue-10398.rs:7:14
- |
-LL | let _a = x;
- | - value moved here
-LL | drop(x);
- | ^ value used here after move
- |
- = note: move occurs because `x` has type `Box<i32>`, which does not implement the `Copy` trait
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0382`.
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-// Issue #1112
-// Alignment of interior pointers to dynamic-size types
-
-
-struct X<T> {
- a: T,
- b: u8,
- c: bool,
- d: u8,
- e: u16,
- f: u8,
- g: u8
-}
-
-pub fn main() {
- let x: X<isize> = X {
- a: 12345678,
- b: 9,
- c: true,
- d: 10,
- e: 11,
- f: 12,
- g: 13
- };
- bar(x);
-}
-
-fn bar<T>(x: X<T>) {
- assert_eq!(x.b, 9);
- assert_eq!(x.c, true);
- assert_eq!(x.d, 10);
- assert_eq!(x.e, 11);
- assert_eq!(x.f, 12);
- assert_eq!(x.g, 13);
-}
+++ /dev/null
-// run-pass
-// Destructuring struct variants would ICE where regular structs wouldn't
-
-enum Foo {
- VBar { num: isize }
-}
-
-struct SBar { num: isize }
-
-pub fn main() {
- let vbar = Foo::VBar { num: 1 };
- let Foo::VBar { num } = vbar;
- assert_eq!(num, 1);
-
- let sbar = SBar { num: 2 };
- let SBar { num } = sbar;
- assert_eq!(num, 2);
-}
+++ /dev/null
-// run-pass
-
-const TEST_STR: &'static str = "abcd";
-
-fn main() {
- let s = "abcd";
- match s {
- TEST_STR => (),
- _ => unreachable!()
- }
-}
+++ /dev/null
-trait Trait {
- fn outer(&self) {
- fn inner(_: &Self) {
- //~^ ERROR can't use generic parameters from outer function
- }
- }
-}
-
-fn main() { }
+++ /dev/null
-error[E0401]: can't use generic parameters from outer function
- --> $DIR/issue-12796.rs:3:22
- |
-LL | fn inner(_: &Self) {
- | ^^^^
- | |
- | use of generic parameter from outer function
- | can't use `Self` here
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0401`.
+++ /dev/null
-fn main() {
- if true {
- } else if { //~ ERROR missing condition
- //~^ ERROR mismatched types
- } else {
- }
-}
-
-fn foo() {
- if true {
- } else if { //~ ERROR missing condition
- //~^ ERROR mismatched types
- }
- bar();
-}
-
-fn bar() {}
+++ /dev/null
-error: missing condition for `if` expression
- --> $DIR/issue-13483.rs:3:14
- |
-LL | } else if {
- | ^ expected if condition here
-
-error: missing condition for `if` expression
- --> $DIR/issue-13483.rs:11:14
- |
-LL | } else if {
- | ^ expected if condition here
-
-error[E0308]: mismatched types
- --> $DIR/issue-13483.rs:3:15
- |
-LL | } else if {
- | _______________^
-LL | |
-LL | | } else {
- | |_____^ expected `bool`, found `()`
-
-error[E0308]: mismatched types
- --> $DIR/issue-13483.rs:11:15
- |
-LL | } else if {
- | _______________^
-LL | |
-LL | | }
- | |_____^ expected `bool`, found `()`
-
-error: aborting due to 4 previous errors
-
-For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-#![allow(non_camel_case_types)]
-
-const JSVAL_TAG_CLEAR: u32 = 0xFFFFFF80;
-const JSVAL_TYPE_INT32: u8 = 0x01;
-const JSVAL_TYPE_UNDEFINED: u8 = 0x02;
-#[repr(u32)]
-enum ValueTag {
- JSVAL_TAG_INT32 = JSVAL_TAG_CLEAR | (JSVAL_TYPE_INT32 as u32),
- JSVAL_TAG_UNDEFINED = JSVAL_TAG_CLEAR | (JSVAL_TYPE_UNDEFINED as u32),
-}
-
-fn main() {
- let _ = ValueTag::JSVAL_TAG_INT32;
-}
+++ /dev/null
-error[E0133]: use of extern static is unsafe and requires unsafe function or block
- --> $DIR/issue-14227.rs:7:21
- |
-LL | static CRASH: u32 = symbol;
- | ^^^^^^ use of extern static
- |
- = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0133`.
+++ /dev/null
-// revisions: mir thir
-// [thir]compile-flags: -Z thir-unsafeck
-
-extern "C" {
- pub static symbol: u32;
-}
-static CRASH: u32 = symbol;
-//~^ ERROR use of extern static is unsafe and requires
-
-fn main() {}
+++ /dev/null
-error[E0133]: use of extern static is unsafe and requires unsafe function or block
- --> $DIR/issue-14227.rs:7:21
- |
-LL | static CRASH: u32 = symbol;
- | ^^^^^^ use of extern static
- |
- = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0133`.
+++ /dev/null
-// run-pass
-#![allow(unused_mut)]
-// ignore-emscripten no processes
-// ignore-sgx no processes
-
-use std::env;
-use std::io::prelude::*;
-use std::io;
-use std::process::{Command, Stdio};
-
-fn main() {
- let args: Vec<String> = env::args().collect();
- if args.len() > 1 && args[1] == "child" {
- return child()
- }
-
- test();
-}
-
-fn child() {
- writeln!(&mut io::stdout(), "foo").unwrap();
- writeln!(&mut io::stderr(), "bar").unwrap();
- let mut stdin = io::stdin();
- let mut s = String::new();
- stdin.lock().read_line(&mut s).unwrap();
- assert_eq!(s.len(), 0);
-}
-
-fn test() {
- let args: Vec<String> = env::args().collect();
- let mut p = Command::new(&args[0]).arg("child")
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn().unwrap();
- assert!(p.wait().unwrap().success());
-}
+++ /dev/null
-// run-pass
-// All 3 expressions should work in that the argument gets
-// coerced to a trait object
-
-// pretty-expanded FIXME #23616
-
-fn main() {
- send::<Box<dyn Foo>>(Box::new(Output(0)));
- Test::<Box<dyn Foo>>::foo(Box::new(Output(0)));
- Test::<Box<dyn Foo>>::new().send(Box::new(Output(0)));
-}
-
-fn send<T>(_: T) {}
-
-struct Test<T> { marker: std::marker::PhantomData<T> }
-impl<T> Test<T> {
- fn new() -> Test<T> { Test { marker: ::std::marker::PhantomData } }
- fn foo(_: T) {}
- fn send(&self, _: T) {}
-}
-
-trait Foo { fn dummy(&self) { }}
-struct Output(isize);
-impl Foo for Output {}
+++ /dev/null
-// check-pass
-// pretty-expanded FIXME #23616
-
-#[deny(dead_code)]
-pub enum Foo {
- Bar {
- baz: isize
- }
-}
-
-fn main() { }
+++ /dev/null
-// run-pass
-
-fn main() {
- let mut x: &[_] = &[1, 2, 3, 4];
-
- let mut result = vec![];
- loop {
- x = match *x {
- [1, n, 3, ref rest @ ..] => {
- result.push(n);
- rest
- }
- [n, ref rest @ ..] => {
- result.push(n);
- rest
- }
- [] =>
- break
- }
- }
- assert_eq!(result, [2, 4]);
-}
+++ /dev/null
-macro_rules! prob1 {
- (0) => {
- 0
- };
- ($n:expr) => {
- if ($n % 3 == 0) || ($n % 5 == 0) {
- $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding `prob1!`
- } else {
- prob1!($n - 1);
- }
- };
-}
-
-fn main() {
- println!("Problem 1: {}", prob1!(1000));
-}
+++ /dev/null
-error: recursion limit reached while expanding `prob1!`
- --> $DIR/issue-16098.rs:7:18
- |
-LL | $n + prob1!($n - 1);
- | ^^^^^^^^^^^^^^
-...
-LL | println!("Problem 1: {}", prob1!(1000));
- | ------------ in this macro invocation
- |
- = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`issue_16098`)
- = note: this error originates in the macro `prob1` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-pass
-// ignore-emscripten no processes
-// ignore-sgx no processes
-
-use std::process::Command;
-use std::env;
-
-fn main() {
- let len = env::args().len();
-
- if len == 1 {
- test();
- } else {
- assert_eq!(len, 3);
- }
-}
-
-fn test() {
- let status = Command::new(&env::current_exe().unwrap())
- .arg("foo").arg("")
- .status().unwrap();
- assert!(status.success());
-}
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-
-static X2: u64 = !0 as u16 as u64;
-static Y2: u64 = !0 as u32 as u64;
-const X: u64 = !0 as u16 as u64;
-const Y: u64 = !0 as u32 as u64;
-
-fn main() {
- assert_eq!(match 1 {
- X => unreachable!(),
- Y => unreachable!(),
- _ => 1
- }, 1);
-}
+++ /dev/null
-// run-pass
-// Regression test for #18060: match arms were matching in the wrong order.
-
-fn main() {
- assert_eq!(2, match (1, 3) { (0, 2..=5) => 1, (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
- assert_eq!(2, match (1, 3) { (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
- assert_eq!(2, match (1, 7) { (0, 2..=5) => 1, (1, 7) => 2, (_, 2..=5) => 3, (_, _) => 4 });
-}
+++ /dev/null
-fn main() {
- const X: u32 = 1;
- const Y: usize = unsafe { &X as *const u32 as usize }; //~ ERROR pointers cannot be cast to integers
- println!("{}", Y);
-}
+++ /dev/null
-error: pointers cannot be cast to integers during const eval
- --> $DIR/issue-18294.rs:3:31
- |
-LL | const Y: usize = unsafe { &X as *const u32 as usize };
- | ^^^^^^^^^^^^^^^^^^^^^^^^^
- |
- = note: at compile-time, pointers do not have an integer value
- = note: avoiding this restriction via `transmute`, `union`, or raw pointers leads to compile-time undefined behavior
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-pass
-// Tests multiple free variables being passed by value into an unboxed
-// once closure as an optimization by codegen. This used to hit an
-// incorrect assert.
-
-fn main() {
- let x = 2u8;
- let y = 3u8;
- assert_eq!((move || x + y)(), 5);
-}
+++ /dev/null
-// aux-build:issue-19163.rs
-
-#[macro_use] extern crate issue_19163;
-
-use std::io::Write;
-
-fn main() {
- let mut v = vec![];
- mywrite!(&v, "Hello world");
- //~^ ERROR cannot borrow data in a `&` reference as mutable
-}
+++ /dev/null
-error[E0596]: cannot borrow data in a `&` reference as mutable
- --> $DIR/issue-19163.rs:9:5
- |
-LL | mywrite!(&v, "Hello world");
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
- |
- = note: this error originates in the macro `mywrite` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0596`.
+++ /dev/null
-// run-pass
-
-#![allow(dead_code)]
-
-trait Trait { fn dummy(&self) { } }
-
-#[derive(Debug)]
-struct Foo<T: Trait> {
- foo: T,
-}
-
-#[derive(Debug)]
-struct Bar<T> where T: Trait {
- bar: T,
-}
-
-impl Trait for isize {}
-
-fn main() {
- let a = Foo { foo: 12 };
- let b = Bar { bar: 12 };
- println!("{:?} {:?}", a, b);
-}
+++ /dev/null
-// error-pattern: requires `copy` lang_item
-
-#![feature(lang_items, start, no_core)]
-#![no_core]
-
-#[lang = "sized"]
-trait Sized { }
-
-struct S;
-
-#[start]
-fn main(_: isize, _: *const *const u8) -> isize {
- let _ = S;
- 0
-}
+++ /dev/null
-error: requires `copy` lang_item
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-pass
-#![allow(stable_features)]
-
-// ignore-emscripten no processes
-// ignore-sgx no processes
-
-#![feature(os)]
-
-#[cfg(unix)]
-fn main() {
- use std::process::Command;
- use std::env;
- use std::os::unix::prelude::*;
- use std::ffi::OsStr;
-
- if env::args().len() == 1 {
- assert!(Command::new(&env::current_exe().unwrap())
- .arg(<OsStr as OsStrExt>::from_bytes(b"\xff"))
- .status().unwrap().success())
- }
-}
-
-#[cfg(windows)]
-fn main() {}
+++ /dev/null
-// We need all these 9 issue-20616-N.rs files
-// because we can only catch one parsing error at a time
-
-type Type_1_<'a, T> = &'a T;
-
-
-//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
-
-
-//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
-
-
-//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
-
-
-type Type_4<T> = Type_1_<'static,, T>;
-//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
-
-
-type Type_5_<'a> = Type_1_<'a, ()>;
-
-
-//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
-
-
-//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
-
-
-//type Type_7 = Box<(),,>; // error: expected type, found `,`
-
-
-//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
-
-
-//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
+++ /dev/null
-error: expected one of `>`, a const expression, lifetime, or type, found `,`
- --> $DIR/issue-20616-4.rs:16:34
- |
-LL | type Type_4<T> = Type_1_<'static,, T>;
- | ^ expected one of `>`, a const expression, lifetime, or type
-
-error: aborting due to previous error
-
+++ /dev/null
-// We need all these 9 issue-20616-N.rs files
-// because we can only catch one parsing error at a time
-
-type Type_1_<'a, T> = &'a T;
-
-
-//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
-
-
-//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
-
-
-//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
-
-
-//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
-
-
-type Type_5_<'a> = Type_1_<'a, ()>;
-
-
-type Type_5<'a> = Type_1_<'a, (),,>;
-//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
-
-
-//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
-
-
-//type Type_7 = Box<(),,>; // error: expected type, found `,`
-
-
-//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
-
-
-//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
+++ /dev/null
-error: expected one of `>`, a const expression, lifetime, or type, found `,`
- --> $DIR/issue-20616-5.rs:22:34
- |
-LL | type Type_5<'a> = Type_1_<'a, (),,>;
- | ^ expected one of `>`, a const expression, lifetime, or type
-
-error: aborting due to previous error
-
+++ /dev/null
-// We need all these 9 issue-20616-N.rs files
-// because we can only catch one parsing error at a time
-
-type Type_1_<'a, T> = &'a T;
-
-
-//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
-
-
-//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
-
-
-//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
-
-
-//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
-
-
-type Type_5_<'a> = Type_1_<'a, ()>;
-
-
-//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
-
-
-type Type_6 = Type_5_<'a,,>;
-//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
-
-
-//type Type_7 = Box<(),,>; // error: expected type, found `,`
-
-
-//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
-
-
-//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
+++ /dev/null
-error: expected one of `>`, a const expression, lifetime, or type, found `,`
- --> $DIR/issue-20616-6.rs:25:26
- |
-LL | type Type_6 = Type_5_<'a,,>;
- | ^ expected one of `>`, a const expression, lifetime, or type
-
-error: aborting due to previous error
-
+++ /dev/null
-// We need all these 9 issue-20616-N.rs files
-// because we can only catch one parsing error at a time
-
-type Type_1_<'a, T> = &'a T;
-
-
-//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
-
-
-//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
-
-
-//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
-
-
-//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
-
-
-type Type_5_<'a> = Type_1_<'a, ()>;
-
-
-//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
-
-
-//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
-
-
-type Type_7 = Box<(),,>;
-//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
-
-
-//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
-
-
-//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
+++ /dev/null
-error: expected one of `>`, a const expression, lifetime, or type, found `,`
- --> $DIR/issue-20616-7.rs:28:22
- |
-LL | type Type_7 = Box<(),,>;
- | ^ expected one of `>`, a const expression, lifetime, or type
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-pass
-// compile-flags: --test
-
-#[test]
-pub fn foo() {}
+++ /dev/null
-#![allow(unused_macros)]
-
-macro_rules! test { ($wrong:t_ty ..) => () }
- //~^ ERROR: invalid fragment specifier `t_ty`
-
-fn main() {}
+++ /dev/null
-error: invalid fragment specifier `t_ty`
- --> $DIR/issue-21356.rs:3:22
- |
-LL | macro_rules! test { ($wrong:t_ty ..) => () }
- | ^^^^^^^^^^^
- |
- = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, `item` and `vis`
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-pass
-#![allow(unused_imports, overlapping_range_endpoints)]
-// pretty-expanded FIXME #23616
-
-use m::{START, END};
-
-fn main() {
- match 42 {
- m::START..=m::END => {},
- 0..=m::END => {},
- m::START..=59 => {},
- _ => {},
- }
-}
-
-mod m {
- pub const START: u32 = 4;
- pub const END: u32 = 14;
-}
+++ /dev/null
-// check-pass
-#![allow(dead_code)]
-// Test that the requirement (in `Bar`) that `T::Bar : 'static` does
-// not wind up propagating to `T`.
-
-// pretty-expanded FIXME #23616
-
-pub trait Foo {
- type Bar;
-
- fn foo(&self) -> Self;
-}
-
-pub struct Static<T:'static>(T);
-
-struct Bar<T:Foo>
- where T::Bar : 'static
-{
- x: Static<Option<T::Bar>>
-}
-
-fn main() { }
+++ /dev/null
-// check-pass
-pub trait LineFormatter<'a> {
- type Iter: Iterator<Item=&'a str> + 'a;
- fn iter(&'a self, line: &'a str) -> Self::Iter;
-
- fn dimensions(&'a self, line: &'a str) {
- let iter: Self::Iter = self.iter(line);
- <_ as IntoIterator>::into_iter(iter);
- }
-}
-
-fn main() {}
+++ /dev/null
-// run-pass
-macro_rules! items {
- () => {
- type A = ();
- fn a() {}
- }
-}
-
-trait Foo {
- type A;
- fn a();
-}
-
-impl Foo for () {
- items!();
-}
-
-fn main() {
-
-}
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-// Test transitive analysis for associated types. Collected types
-// should be normalized and new obligations generated.
-
-// pretty-expanded FIXME #23616
-
-trait Foo {
- type A;
- fn foo(&self) {}
-}
-
-impl Foo for usize {
- type A = usize;
-}
-
-struct Bar<T: Foo> { inner: T::A }
-
-fn is_send<T: Send>() {}
-
-fn main() {
- is_send::<Bar<usize>>();
-}
+++ /dev/null
-#![feature(llvm_asm)]
-#![allow(deprecated)] // llvm_asm!
-// compile-flags: -Ccodegen-units=1
-// build-fail
-// only-x86_64
-
-fn main() {
- unsafe {
- llvm_asm!("int $3"); //~ ERROR too few operands for instruction
- //~| ERROR invalid operand in inline asm
- }
-}
+++ /dev/null
-error: invalid operand in inline asm: 'int $3'
- --> $DIR/issue-23458.rs:9:9
- |
-LL | llvm_asm!("int $3");
- | ^
-
-error: too few operands for instruction
- --> $DIR/issue-23458.rs:9:9
- |
-LL | llvm_asm!("int $3");
- | ^
- |
-note: instantiated into assembly here
- --> <inline asm>:1:2
- |
-LL | int
- | ^
-
-error: aborting due to 2 previous errors
-
+++ /dev/null
-static foo: i32 = 0;
-
-fn bar(foo: i32) {}
-//~^ ERROR function parameters cannot shadow statics
-//~| cannot be named the same as a static
-
-mod submod {
- pub static answer: i32 = 42;
-}
-
-use self::submod::answer;
-
-fn question(answer: i32) {}
-//~^ ERROR function parameters cannot shadow statics
-//~| cannot be named the same as a static
-fn main() {
-}
+++ /dev/null
-error[E0530]: function parameters cannot shadow statics
- --> $DIR/issue-23716.rs:3:8
- |
-LL | static foo: i32 = 0;
- | -------------------- the static `foo` is defined here
-LL |
-LL | fn bar(foo: i32) {}
- | ^^^ cannot be named the same as a static
-
-error[E0530]: function parameters cannot shadow statics
- --> $DIR/issue-23716.rs:13:13
- |
-LL | use self::submod::answer;
- | -------------------- the static `answer` is imported here
-LL |
-LL | fn question(answer: i32) {}
- | ^^^^^^ cannot be named the same as a static
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0530`.
+++ /dev/null
-// run-pass
-const U8_MAX_HALF: u8 = !0u8 / 2;
-const U16_MAX_HALF: u16 = !0u16 / 2;
-const U32_MAX_HALF: u32 = !0u32 / 2;
-const U64_MAX_HALF: u64 = !0u64 / 2;
-
-fn main() {
- assert_eq!(U8_MAX_HALF, 0x7f);
- assert_eq!(U16_MAX_HALF, 0x7fff);
- assert_eq!(U32_MAX_HALF, 0x7fff_ffff);
- assert_eq!(U64_MAX_HALF, 0x7fff_ffff_ffff_ffff);
-}
+++ /dev/null
-// run-pass
-
-trait Foo: Fn(i32) -> i32 + Send {}
-
-impl<T: ?Sized + Fn(i32) -> i32 + Send> Foo for T {}
-
-fn wants_foo(f: Box<dyn Foo>) -> i32 {
- f(42)
-}
-
-fn main() {
- let f = Box::new(|x| x);
- assert_eq!(wants_foo(f), 42);
-}
+++ /dev/null
-// run-pass
-// ignore-emscripten no threads
-// ignore-sgx no processes
-
-use std::thread;
-use std::env;
-use std::process::Command;
-
-struct Handle(i32);
-
-impl Drop for Handle {
- fn drop(&mut self) { panic!(); }
-}
-
-thread_local!(static HANDLE: Handle = Handle(0));
-
-fn main() {
- let args = env::args().collect::<Vec<_>>();
- if args.len() == 1 {
- let out = Command::new(&args[0]).arg("test").output().unwrap();
- let stderr = std::str::from_utf8(&out.stderr).unwrap();
- assert!(stderr.contains("panicked at 'explicit panic'"),
- "bad failure message:\n{}\n", stderr);
- } else {
- // TLS dtors are not always run on process exit
- thread::spawn(|| {
- HANDLE.with(|h| {
- println!("{}", h.0);
- });
- }).join().unwrap();
- }
-}
+++ /dev/null
-// run-fail
-// error-pattern:explicit panic
-// ignore-emscripten no processes
-
-use std::sync::Arc;
-
-enum Err<T> {
- Errr(Arc<T>),
-}
-
-fn foo() -> Err<isize> {
- panic!();
-}
-
-fn main() {
- let _f = foo();
-}
+++ /dev/null
-// run-pass
-#![allow(overlapping_range_endpoints)]
-
-fn main() {
- let x = 'a';
-
- let y = match x {
- 'a'..='b' if false => "one",
- 'a' => "two",
- 'a'..='b' => "three",
- _ => panic!("what?"),
- };
-
- assert_eq!(y, "two");
-}
+++ /dev/null
-// run-pass
-
-pub trait Foo<T> {
- fn foo(self) -> T;
-}
-
-impl<'a, T> Foo<T> for &'a str where &'a str: Into<T> {
- fn foo(self) -> T {
- panic!();
- }
-}
-
-fn main() {}
+++ /dev/null
-// check-pass
-
-pub struct Bar<T> {
- items: Vec<&'static str>,
- inner: T,
-}
-
-pub trait IntoBar<T> {
- fn into_bar(self) -> Bar<T>;
-}
-
-impl<'a, T> IntoBar<T> for &'a str where &'a str: Into<T> {
- fn into_bar(self) -> Bar<T> {
- Bar {
- items: Vec::new(),
- inner: self.into(),
- }
- }
-}
-
-fn main() {}
+++ /dev/null
-// check-pass
-
-pub struct Item {
- _inner: &'static str,
-}
-
-pub struct Bar<T> {
- items: Vec<Item>,
- inner: T,
-}
-
-pub trait IntoBar<T> {
- fn into_bar(self) -> Bar<T>;
-}
-
-impl<'a, T> IntoBar<T> for &'a str where &'a str: Into<T> {
- fn into_bar(self) -> Bar<T> {
- Bar {
- items: Vec::new(),
- inner: self.into(),
- }
- }
-}
-
-fn main() {}
+++ /dev/null
-fn parse_type(iter: Box<dyn Iterator<Item=&str>+'static>) -> &str { iter.next() }
-//~^ ERROR missing lifetime specifier [E0106]
-
-fn parse_type_2(iter: fn(&u8)->&u8) -> &str { iter() }
-//~^ ERROR missing lifetime specifier [E0106]
-
-fn parse_type_3() -> &str { unimplemented!() }
-//~^ ERROR missing lifetime specifier [E0106]
-
-fn main() {}
+++ /dev/null
-error[E0106]: missing lifetime specifier
- --> $DIR/issue-26638.rs:1:62
- |
-LL | fn parse_type(iter: Box<dyn Iterator<Item=&str>+'static>) -> &str { iter.next() }
- | ------------------------------------ ^ expected named lifetime parameter
- |
- = help: this function's return type contains a borrowed value, but the signature does not say which one of `iter`'s 2 lifetimes it is borrowed from
-help: consider introducing a named lifetime parameter
- |
-LL | fn parse_type<'a>(iter: Box<dyn Iterator<Item=&str>+'static>) -> &'a str { iter.next() }
- | ++++ ++
-
-error[E0106]: missing lifetime specifier
- --> $DIR/issue-26638.rs:4:40
- |
-LL | fn parse_type_2(iter: fn(&u8)->&u8) -> &str { iter() }
- | ^ expected named lifetime parameter
- |
- = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
-help: consider using the `'static` lifetime
- |
-LL | fn parse_type_2(iter: fn(&u8)->&u8) -> &'static str { iter() }
- | ~~~~~~~~
-
-error[E0106]: missing lifetime specifier
- --> $DIR/issue-26638.rs:7:22
- |
-LL | fn parse_type_3() -> &str { unimplemented!() }
- | ^ expected named lifetime parameter
- |
- = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
-help: consider using the `'static` lifetime
- |
-LL | fn parse_type_3() -> &'static str { unimplemented!() }
- | ~~~~~~~~
-
-error: aborting due to 3 previous errors
-
-For more information about this error, try `rustc --explain E0106`.
+++ /dev/null
-// run-pass
-
-// This test is bogus (i.e., should be check-fail) during the period
-// where #54986 is implemented and #54987 is *not* implemented. For
-// now: just ignore it
-//
-// ignore-test
-
-// This test is checking that the write to `c.0` (which has been moved out of)
-// won't overwrite the state in `c2`.
-//
-// That's a fine thing to test when this code is accepted by the
-// compiler, and this code is being transcribed accordingly into
-// the ui test issue-21232-partial-init-and-use.rs
-
-fn main() {
- let mut c = (1, "".to_owned());
- match c {
- c2 => {
- c.0 = 2;
- assert_eq!(c2.0, 1);
- }
- }
-}
+++ /dev/null
-// run-pass
-
-fn thing<'r>(x: &'r [isize]) -> &'r [isize] { x }
-
-pub fn main() {
- let x = &[1,2,3];
- let y = x;
- let z = thing(x);
- assert_eq!(z[2], x[2]);
- assert_eq!(z[1], y[1]);
-}
+++ /dev/null
-error[E0133]: use of extern static is unsafe and requires unsafe function or block
- --> $DIR/issue-28324.rs:8:24
- |
-LL | pub static BAZ: u32 = *&error_message_count;
- | ^^^^^^^^^^^^^^^^^^^^ use of extern static
- |
- = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0133`.
+++ /dev/null
-// revisions: mir thir
-// [thir]compile-flags: -Z thir-unsafeck
-
-extern "C" {
- static error_message_count: u32;
-}
-
-pub static BAZ: u32 = *&error_message_count;
-//~^ ERROR use of extern static is unsafe and requires
-
-fn main() {}
+++ /dev/null
-error[E0133]: use of extern static is unsafe and requires unsafe function or block
- --> $DIR/issue-28324.rs:8:25
- |
-LL | pub static BAZ: u32 = *&error_message_count;
- | ^^^^^^^^^^^^^^^^^^^ use of extern static
- |
- = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0133`.
+++ /dev/null
-// run-pass
-
-// Demonstrate the use of the unguarded escape hatch with a type param in negative position
-// to assert that destructor will not access any dead data.
-//
-// Compare with ui/span/issue28498-reject-lifetime-param.rs
-
-// Demonstrate that a type param in negative position causes dropck to reject code
-// that might indirectly access previously dropped value.
-//
-// Compare with run-pass/issue28498-ugeh-with-passed-to-fn.rs
-
-#![feature(dropck_eyepatch)]
-
-#[derive(Debug)]
-struct ScribbleOnDrop(String);
-
-impl Drop for ScribbleOnDrop {
- fn drop(&mut self) {
- self.0 = format!("DROPPED");
- }
-}
-
-struct Foo<T>(u32, T, Box<for <'r> fn(&'r T) -> String>);
-
-unsafe impl<#[may_dangle] T> Drop for Foo<T> {
- fn drop(&mut self) {
- // Use of `may_dangle` is sound, because destructor never passes a `self.1`
- // to the callback (in `self.2`) despite having it available.
- println!("Dropping Foo({}, _)", self.0);
- }
-}
-
-fn callback(s: & &ScribbleOnDrop) -> String { format!("{:?}", s) }
-
-fn main() {
- let (last_dropped, foo0);
- let (foo1, first_dropped);
-
- last_dropped = ScribbleOnDrop(format!("last"));
- first_dropped = ScribbleOnDrop(format!("first"));
- foo0 = Foo(0, &last_dropped, Box::new(callback));
- foo1 = Foo(1, &first_dropped, Box::new(callback));
-
- println!("foo0.1: {:?} foo1.1: {:?}", foo0.1, foo1.1);
-}
+++ /dev/null
-// check-pass
-// Regression test for #28871. The problem is that rustc encountered
-// two ways to project, one from a where clause and one from the where
-// clauses on the trait definition. (In fact, in this case, the where
-// clauses originated from the trait definition as well.) The true
-// cause of the error is that the trait definition where clauses are
-// not being normalized, and hence the two sources are considered in
-// conflict, and not a duplicate. Hacky solution is to prefer where
-// clauses over the data found in the trait definition.
-
-trait T {
- type T;
-}
-
-struct S;
-impl T for S {
- type T = S;
-}
-
-trait T2 {
- type T: Iterator<Item=<S as T>::T>;
-}
-
-fn main() { }
+++ /dev/null
-macro_rules! foo {
- ($d:expr) => {{
- fn bar(d: u8) { }
- bar(&mut $d);
- //~^ ERROR mismatched types
- //~| expected `u8`, found `&mut u8`
- }}
-}
-
-fn main() {
- foo!(0u8);
- //~^ in this expansion of foo!
-}
+++ /dev/null
-error[E0308]: mismatched types
- --> $DIR/issue-29084.rs:4:13
- |
-LL | bar(&mut $d);
- | ^^^^^^^ expected `u8`, found `&mut u8`
-...
-LL | foo!(0u8);
- | --------- in this macro invocation
- |
- = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-fn siphash<T>() {
-
- trait U {
- fn g(&self, x: T) -> T; //~ ERROR can't use generic parameters from outer function
- //~^ ERROR can't use generic parameters from outer function
- }
-}
-
-fn main() {}
+++ /dev/null
-error[E0401]: can't use generic parameters from outer function
- --> $DIR/issue-3021-c.rs:4:24
- |
-LL | fn siphash<T>() {
- | - type parameter from outer function
-...
-LL | fn g(&self, x: T) -> T;
- | - ^ use of generic parameter from outer function
- | |
- | help: try using a local generic parameter instead: `g<T>`
-
-error[E0401]: can't use generic parameters from outer function
- --> $DIR/issue-3021-c.rs:4:30
- |
-LL | fn siphash<T>() {
- | - type parameter from outer function
-...
-LL | fn g(&self, x: T) -> T;
- | - ^ use of generic parameter from outer function
- | |
- | help: try using a local generic parameter instead: `g<T>`
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0401`.
+++ /dev/null
-trait SipHash {
- fn reset(&self);
-}
-
-fn siphash(k0 : u64) {
- struct SipState {
- v0: u64,
- }
-
- impl SipHash for SipState {
- fn reset(&self) {
- self.v0 = k0 ^ 0x736f6d6570736575; //~ ERROR can't capture dynamic environment
- }
- }
- panic!();
-}
-
-fn main() {}
+++ /dev/null
-error[E0434]: can't capture dynamic environment in a fn item
- --> $DIR/issue-3021.rs:12:22
- |
-LL | self.v0 = k0 ^ 0x736f6d6570736575;
- | ^^
- |
- = help: use the `|| { ... }` closure form instead
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0434`.
+++ /dev/null
-// Regression test for #30225, which was an ICE that would trigger as
-// a result of a poor interaction between trait result caching and
-// type inference. Specifically, at that time, unification could cause
-// unrelated type variables to become instantiated, if subtyping
-// relationships existed. These relationships are now propagated
-// through obligations and hence everything works out fine.
-
-trait Foo<U,V> : Sized {
- fn foo(self, u: Option<U>, v: Option<V>) {}
-}
-
-struct A;
-struct B;
-
-impl Foo<A, B> for () {} // impl A
-impl Foo<u32, u32> for u32 {} // impl B, creating ambiguity
-
-fn toxic() {
- // cache the resolution <() as Foo<$0,$1>> = impl A
- let u = None;
- let v = None;
- Foo::foo((), u, v);
-}
-
-fn bomb() {
- let mut u = None; // type is Option<$0>
- let mut v = None; // type is Option<$1>
- let mut x = None; // type is Option<$2>
-
- Foo::foo(x.unwrap(),u,v); // register <$2 as Foo<$0, $1>>
- u = v; // mark $0 and $1 in a subtype relationship
- //~^ ERROR mismatched types
- x = Some(()); // set $2 = (), allowing impl selection
- // to proceed for <() as Foo<$0, $1>> = impl A.
- // kaboom, this *used* to trigge an ICE
-}
-
-fn main() {}
+++ /dev/null
-error[E0308]: mismatched types
- --> $DIR/issue-30225.rs:31:9
- |
-LL | u = v; // mark $0 and $1 in a subtype relationship
- | ^ expected struct `A`, found struct `B`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-pub struct X([u8]);
-
-pub static Y: &'static X = {
- const Y: &'static [u8] = b"";
- &X(*Y)
- //~^ ERROR E0277
-};
-
-fn main() {}
+++ /dev/null
-error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
- --> $DIR/issue-30355.rs:5:8
- |
-LL | &X(*Y)
- | ^^ doesn't have a size known at compile-time
- |
- = help: the trait `Sized` is not implemented for `[u8]`
- = note: all function arguments must have a statically known size
- = help: unsized fn params are gated as an unstable feature
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0277`.
+++ /dev/null
-#![feature(no_core, lang_items)]
-#![no_core]
-
-#[lang="sized"]
-trait Sized {}
-
-#[lang="add"]
-trait Add<T> {}
-
-impl Add<i32> for i32 {}
-
-fn main() {
- let x = 5 + 6;
- //~^ ERROR cannot add `i32` to `{integer}`
- let y = 5i32 + 6i32;
- //~^ ERROR cannot add `i32` to `i32`
-}
+++ /dev/null
-error[E0369]: cannot add `i32` to `{integer}`
- --> $DIR/issue-31076.rs:13:15
- |
-LL | let x = 5 + 6;
- | - ^ - i32
- | |
- | {integer}
-
-error[E0369]: cannot add `i32` to `i32`
- --> $DIR/issue-31076.rs:15:18
- |
-LL | let y = 5i32 + 6i32;
- | ---- ^ ---- i32
- | |
- | i32
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0369`.
+++ /dev/null
-// Test that error recovery in the parser to an EOF does not give an infinite
-// spew of errors.
-
-fn main() {
- let
-} //~ ERROR expected pattern, found `}`
+++ /dev/null
-error: expected pattern, found `}`
- --> $DIR/issue-31804.rs:6:1
- |
-LL | }
- | ^ expected pattern
-
-error: aborting due to previous error
-
+++ /dev/null
-// Checks lexical scopes cannot see through normal module boundaries
-
-fn f() {
- fn g() {}
- mod foo {
- fn h() {
- g(); //~ ERROR cannot find function `g` in this scope
- }
- }
-}
-
-fn main() {}
+++ /dev/null
-error[E0425]: cannot find function `g` in this scope
- --> $DIR/issue-31845.rs:7:12
- |
-LL | g();
- | ^ not found in this scope
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0425`.
+++ /dev/null
-// run-pass
-pub fn main() {
- let mut x = 0;
- for _ in 0..4096 { x += 1; }
- assert_eq!(x, 4096);
- println!("x = {}", x);
-}
+++ /dev/null
-extern "C" {
- fn foo(a: i32, ...);
-}
-
-fn bar(_: *const u8) {}
-
-fn main() {
- unsafe {
- foo(0, bar);
- //~^ ERROR can't pass `fn(*const u8) {bar}` to variadic function
- //~| HELP cast the value to `fn(*const u8)`
- }
-}
+++ /dev/null
-error[E0617]: can't pass `fn(*const u8) {bar}` to variadic function
- --> $DIR/issue-32201.rs:9:16
- |
-LL | foo(0, bar);
- | ^^^ help: cast the value to `fn(*const u8)`: `bar as fn(*const u8)`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0617`.
+++ /dev/null
-// run-pass
-
-fn quux<T>(x: T) -> T { let f = id::<T>; return f(x); }
-
-fn id<T>(x: T) -> T { return x; }
-
-pub fn main() { assert_eq!(quux(10), 10); }
+++ /dev/null
-// check-pass
-
-macro_rules! m {
- () => { #[cfg(any())] fn f() {} }
-}
-
-trait T {}
-impl T for () { m!(); }
-
-fn main() {}
+++ /dev/null
-// check-pass
-
-macro_rules! null { ($i:tt) => {} }
-macro_rules! apply_null {
- ($i:item) => { null! { $i } }
-}
-
-fn main() {
- apply_null!(#[cfg(all())] fn f() {});
-}
+++ /dev/null
-enum Test {
- Drill {
- field: i32,
- }
-}
-
-fn main() {
- Test::Drill(field: 42);
- //~^ ERROR invalid `struct` delimiters or `fn` call arguments
-}
+++ /dev/null
-error: invalid `struct` delimiters or `fn` call arguments
- --> $DIR/issue-34255-1.rs:8:5
- |
-LL | Test::Drill(field: 42);
- | ^^^^^^^^^^^^^^^^^^^^^^
- |
-help: if `Test::Drill` is a struct, use braces as delimiters
- |
-LL | Test::Drill { field: 42 };
- | ~ ~
-help: if `Test::Drill` is a function, use the arguments directly
- |
-LL - Test::Drill(field: 42);
-LL + Test::Drill(42);
- |
-
-error: aborting due to previous error
-
+++ /dev/null
-// build-pass
-#![allow(dead_code)]
-// Regression test for #35546. Check that we are able to codegen
-// this. Before we had problems because of the drop glue signature
-// around dropping a trait object (specifically, when dropping the
-// `value` field of `Node<Send>`).
-
-struct Node<T: ?Sized + Send> {
- next: Option<Box<Node<dyn Send>>>,
- value: T,
-}
-
-fn clear(head: &mut Option<Box<Node<dyn Send>>>) {
- match head.take() {
- Some(node) => *head = node.next,
- None => (),
- }
-}
-
-fn main() {}
+++ /dev/null
-// run-pass
-macro_rules! m { (<$t:ty>) => { stringify!($t) } }
-fn main() {
- println!("{}", m!(<Vec<i32>>));
-}
+++ /dev/null
-// check-pass
-// ignore-emscripten
-
-#![feature(llvm_asm)]
-#![allow(deprecated)] // llvm_asm!
-
-macro_rules! interrupt_handler {
- () => {
- unsafe fn _interrupt_handler() {
- llvm_asm!("pop eax" :::: "intel");
- }
- }
-}
-interrupt_handler!{}
-
-fn main() {}
+++ /dev/null
-const fn x() {
- let t = true;
- let x = || t; //~ ERROR function pointer
-}
-
-fn main() {}
+++ /dev/null
-error[E0658]: function pointers cannot appear in constant functions
- --> $DIR/issue-37550.rs:3:9
- |
-LL | let x = || t;
- | ^
- |
- = note: see issue #57563 <https://github.com/rust-lang/rust/issues/57563> for more information
- = help: add `#![feature(const_fn_fn_ptr_basics)]` to the crate attributes to enable
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0658`.
+++ /dev/null
-// run-pass
-
-const fn foo() -> i64 {
- 3
-}
-
-const fn bar(x: i64) -> i64 {
- x*2
-}
-
-fn main() {
- let val = &(foo() % 2);
- assert_eq!(*val, 1);
-
- let val2 = &(bar(1+1) % 3);
- assert_eq!(*val2, 1);
-}
+++ /dev/null
-trait Q<T:?Sized> {}
-trait Foo where u32: Q<Self> {
- fn foo(&self);
-}
-
-impl Q<()> for u32 {}
-impl Foo for () {
- fn foo(&self) {
- println!("foo!");
- }
-}
-
-fn main() {
- let _f: Box<dyn Foo> = //~ ERROR `Foo` cannot be made into an object
- Box::new(()); //~ ERROR `Foo` cannot be made into an object
-}
+++ /dev/null
-error[E0038]: the trait `Foo` cannot be made into an object
- --> $DIR/issue-38604.rs:14:13
- |
-LL | let _f: Box<dyn Foo> =
- | ^^^^^^^^^^^^ `Foo` cannot be made into an object
- |
-note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
- --> $DIR/issue-38604.rs:2:22
- |
-LL | trait Foo where u32: Q<Self> {
- | --- ^^^^^^^ ...because it uses `Self` as a type parameter
- | |
- | this trait cannot be made into an object...
-
-error[E0038]: the trait `Foo` cannot be made into an object
- --> $DIR/issue-38604.rs:15:9
- |
-LL | Box::new(());
- | ^^^^^^^^^^^^ `Foo` cannot be made into an object
- |
-note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
- --> $DIR/issue-38604.rs:2:22
- |
-LL | trait Foo where u32: Q<Self> {
- | --- ^^^^^^^ ...because it uses `Self` as a type parameter
- | |
- | this trait cannot be made into an object...
- = note: required because of the requirements on the impl of `CoerceUnsized<Box<dyn Foo>>` for `Box<()>`
- = note: required by cast to type `Box<dyn Foo>`
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0038`.
+++ /dev/null
-#![allow(unused_macros)]
-
-macro_rules! assign {
- (($($a:tt)*) = ($($b:tt))*) => { //~ ERROR expected one of: `*`, `+`, or `?`
- $($a)* = $($b)*
- }
-}
-
-fn main() {}
+++ /dev/null
-error: expected one of: `*`, `+`, or `?`
- --> $DIR/issue-39388.rs:4:22
- |
-LL | (($($a:tt)*) = ($($b:tt))*) => {
- | ^^^^^^^
-
-error: aborting due to previous error
-
+++ /dev/null
-struct Point {
- x: f64,
- y: f64,
-}
-
-trait ToString_ {
- fn to_string(&self) -> String;
-}
-
-impl ToString_ for Point {
- fn new(x: f64, y: f64) -> Point {
- //~^ ERROR method `new` is not a member of trait `ToString_`
- Point { x: x, y: y }
- }
-
- fn to_string(&self) -> String {
- format!("({}, {})", self.x, self.y)
- }
-}
-
-fn main() {
- let p = Point::new(0.0, 0.0);
- //~^ ERROR no function or associated item named `new` found for struct `Point`
- println!("{}", p.to_string());
-}
+++ /dev/null
-error[E0407]: method `new` is not a member of trait `ToString_`
- --> $DIR/issue-3973.rs:11:5
- |
-LL | / fn new(x: f64, y: f64) -> Point {
-LL | |
-LL | | Point { x: x, y: y }
-LL | | }
- | |_____^ not a member of trait `ToString_`
-
-error[E0599]: no function or associated item named `new` found for struct `Point` in the current scope
- --> $DIR/issue-3973.rs:22:20
- |
-LL | struct Point {
- | ------------ function or associated item `new` not found for this
-...
-LL | let p = Point::new(0.0, 0.0);
- | ^^^ function or associated item not found in `Point`
-
-error: aborting due to 2 previous errors
-
-Some errors have detailed explanations: E0407, E0599.
-For more information about an error, try `rustc --explain E0407`.
+++ /dev/null
-// run-pass
-// aux-build:issue-39823.rs
-
-extern crate issue_39823;
-use issue_39823::{RemoteC, RemoteG};
-
-#[derive(Debug, PartialEq)]
-struct LocalC(u32);
-
-#[derive(Debug, PartialEq)]
-struct LocalG<T>(T);
-
-fn main() {
- let virtual_localc : &dyn Fn(_) -> LocalC = &LocalC;
- assert_eq!(virtual_localc(1), LocalC(1));
-
- let virtual_localg : &dyn Fn(_) -> LocalG<u32> = &LocalG;
- assert_eq!(virtual_localg(1), LocalG(1));
-
- let virtual_remotec : &dyn Fn(_) -> RemoteC = &RemoteC;
- assert_eq!(virtual_remotec(1), RemoteC(1));
-
- let virtual_remoteg : &dyn Fn(_) -> RemoteG<u32> = &RemoteG;
- assert_eq!(virtual_remoteg(1), RemoteG(1));
-}
+++ /dev/null
-// run-pass
-#![allow(unused_macros)]
-macro_rules! m {
- ($e:expr) => {
- macro_rules! n { () => { $e } }
- }
-}
-
-fn main() {
- m!(foo!());
-}
+++ /dev/null
-// check-pass
-macro_rules! m {
- ($i:meta) => {
- #[derive($i)]
- struct S;
- }
-}
-
-m!(Clone);
-
-fn main() {}
+++ /dev/null
-// run-pass
-use std::ops::{Deref, DerefMut};
-
-struct CheckedDeref<T, F> {
- value: T,
- check: F
-}
-
-impl<F: Fn(&T) -> bool, T> Deref for CheckedDeref<T, F> {
- type Target = T;
- fn deref(&self) -> &T {
- assert!((self.check)(&self.value));
- &self.value
- }
-}
-
-impl<F: Fn(&T) -> bool, T> DerefMut for CheckedDeref<T, F> {
- fn deref_mut(&mut self) -> &mut T {
- assert!((self.check)(&self.value));
- &mut self.value
- }
-}
-
-
-fn main() {
- let mut v = CheckedDeref {
- value: vec![0],
- check: |v: &Vec<_>| !v.is_empty()
- };
- v.push(1);
- assert_eq!(*v, vec![0, 1]);
-}
+++ /dev/null
-// run-pass
-#![feature(box_syntax)]
-#![feature(box_patterns)]
-
-#[derive(Debug, PartialEq)]
-enum Test {
- Foo(usize),
- Bar(isize),
-}
-
-fn main() {
- let a = box Test::Foo(10);
- let b = box Test::Bar(-20);
- match (a, b) {
- (_, box Test::Foo(_)) => unreachable!(),
- (box Test::Foo(x), b) => {
- assert_eq!(x, 10);
- assert_eq!(b, box Test::Bar(-20));
- },
- _ => unreachable!(),
- }
-}
+++ /dev/null
-// run-pass
-macro_rules! fooN {
- ($cur:ident $prev:ty) => {
- #[allow(dead_code)]
- enum $cur {
- Empty,
- First($prev),
- Second($prev),
- Third($prev),
- Fourth($prev),
- }
- }
-}
-
-fooN!(Foo0 ());
-fooN!(Foo1 Foo0);
-fooN!(Foo2 Foo1);
-fooN!(Foo3 Foo2);
-fooN!(Foo4 Foo3);
-fooN!(Foo5 Foo4);
-fooN!(Foo6 Foo5);
-fooN!(Foo7 Foo6);
-fooN!(Foo8 Foo7);
-fooN!(Foo9 Foo8);
-fooN!(Foo10 Foo9);
-fooN!(Foo11 Foo10);
-fooN!(Foo12 Foo11);
-fooN!(Foo13 Foo12);
-fooN!(Foo14 Foo13);
-fooN!(Foo15 Foo14);
-fooN!(Foo16 Foo15);
-fooN!(Foo17 Foo16);
-fooN!(Foo18 Foo17);
-fooN!(Foo19 Foo18);
-fooN!(Foo20 Foo19);
-fooN!(Foo21 Foo20);
-fooN!(Foo22 Foo21);
-fooN!(Foo23 Foo22);
-fooN!(Foo24 Foo23);
-fooN!(Foo25 Foo24);
-fooN!(Foo26 Foo25);
-fooN!(Foo27 Foo26);
-
-fn main() {
- let _foo = Foo27::Empty;
-}
+++ /dev/null
-// Issue 46112: An extern crate pub re-exporting libcore was causing
-// paths rooted from `std` to be misrendered in the diagnostic output.
-
-// ignore-windows
-// aux-build:xcrate-issue-43189-a.rs
-// aux-build:xcrate-issue-43189-b.rs
-
-extern crate xcrate_issue_43189_b;
-fn main() {
- ().a();
- //~^ ERROR no method named `a` found
-}
+++ /dev/null
-error[E0599]: no method named `a` found for unit type `()` in the current scope
- --> $DIR/issue-43189.rs:10:8
- |
-LL | ().a();
- | ^ method not found in `()`
- |
- ::: $DIR/auxiliary/xcrate-issue-43189-a.rs:5:8
- |
-LL | fn a(&self) {}
- | - the method is available for `()` here
- |
- = help: items from traits can only be used if the trait is in scope
-help: the following trait is implemented but not in scope; perhaps add a `use` for it:
- |
-LL | use xcrate_issue_43189_b::xcrate_issue_43189_a::A;
- |
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0599`.
+++ /dev/null
-// run-pass
-pub fn main() {
- let mut count = 0;
- for _ in 0..999_999 { count += 1; }
- assert_eq!(count, 999_999);
- println!("{}", count);
-}
+++ /dev/null
-// run-pass
-// ignore-emscripten no threads support
-
-use std::sync::mpsc::channel;
-use std::thread;
-
-pub fn main() {
- let (tx, rx) = channel::<&'static str>();
-
- let t = thread::spawn(move|| {
- assert_eq!(rx.recv().unwrap(), "hello, world");
- });
-
- tx.send("hello, world").unwrap();
- t.join().ok().unwrap();
-}
+++ /dev/null
-// run-pass
-#![allow(unreachable_code)]
-// compile-flags: --edition 2018
-
-#![feature(try_blocks)]
-
-fn main() {
- let mut a = 0;
- let () = {
- let _: Result<(), ()> = try {
- let _ = Err(())?;
- return
- };
- a += 1;
- };
- a += 2;
- assert_eq!(a, 3);
-}
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-#![allow(unused_variables)]
-#![feature(unsize, coerce_unsized)]
-
-#[repr(packed)]
-struct UnalignedPtr<'a, T: ?Sized>
- where T: 'a,
-{
- data: &'a T,
-}
-
-fn main() {
-
- impl<'a, T, U> std::ops::CoerceUnsized<UnalignedPtr<'a, U>> for UnalignedPtr<'a, T>
- where
- T: std::marker::Unsize<U> + ?Sized,
- U: ?Sized,
- { }
-
- let arr = [1, 2, 3];
- let arr_unaligned: UnalignedPtr<[i32; 3]> = UnalignedPtr { data: &arr };
- let arr_unaligned: UnalignedPtr<[i32]> = arr_unaligned;
-}
+++ /dev/null
-// run-pass
-struct A;
-
-impl A {
- fn take_mutably(&mut self) {}
-}
-
-fn identity<T>(t: T) -> T {
- t
-}
-
-// Issue 46095
-// Built-in indexing should be used even when the index is not
-// trivially an integer
-// Overloaded indexing would cause wrapped to be borrowed mutably
-
-fn main() {
- let mut a1 = A;
- let mut a2 = A;
-
- let wrapped = [&mut a1, &mut a2];
-
- {
- wrapped[0 + 1 - 1].take_mutably();
- }
-
- {
- wrapped[identity(0)].take_mutably();
- }
-}
+++ /dev/null
-// Issue 46112: An extern crate pub re-exporting libcore was causing
-// paths rooted from `std` to be misrendered in the diagnostic output.
-
-// ignore-windows
-// aux-build:xcrate-issue-46112-rexport-core.rs
-
-extern crate xcrate_issue_46112_rexport_core;
-fn test(r: Result<Option<()>, &'static str>) { }
-fn main() { test(Ok(())); }
-//~^ mismatched types
+++ /dev/null
-error[E0308]: mismatched types
- --> $DIR/issue-46112.rs:9:21
- |
-LL | fn main() { test(Ok(())); }
- | ^^
- | |
- | expected enum `Option`, found `()`
- | help: try using a variant of the expected enum: `Some(())`
- |
- = note: expected enum `Option<()>`
- found unit type `()`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-// run-pass
-// Regression test for issue #47139:
-//
-// Coherence was encountering an (unnecessary) overflow trying to
-// decide if the two impls of dummy overlap.
-//
-// The overflow went something like:
-//
-// - `&'a ?T: Insertable` ?
-// - let ?T = Option<?U> ?
-// - `Option<?U>: Insertable` ?
-// - `Option<&'a ?U>: Insertable` ?
-// - `&'a ?U: Insertable` ?
-//
-// While somewhere in the middle, a projection would occur, which
-// broke cycle detection.
-//
-// It turned out that this cycle was being kicked off due to some
-// extended diagnostic attempts in coherence, so removing those
-// sidestepped the issue for now.
-
-#![allow(dead_code)]
-
-pub trait Insertable {
- type Values;
-
- fn values(self) -> Self::Values;
-}
-
-impl<T> Insertable for Option<T>
- where
- T: Insertable,
- T::Values: Default,
-{
- type Values = T::Values;
-
- fn values(self) -> Self::Values {
- self.map(Insertable::values).unwrap_or_default()
- }
-}
-
-impl<'a, T> Insertable for &'a Option<T>
- where
- Option<&'a T>: Insertable,
-{
- type Values = <Option<&'a T> as Insertable>::Values;
-
- fn values(self) -> Self::Values {
- self.as_ref().values()
- }
-}
-
-impl<'a, T> Insertable for &'a [T]
-{
- type Values = Self;
-
- fn values(self) -> Self::Values {
- self
- }
-}
-
-trait Unimplemented { }
-
-trait Dummy { }
-
-struct Foo<T> { t: T }
-
-impl<'a, U> Dummy for Foo<&'a U>
- where &'a U: Insertable
-{
-}
-
-impl<T> Dummy for T
- where T: Unimplemented
-{ }
-
-fn main() {
-}
+++ /dev/null
-#![allow(unused_variables)]; //~ ERROR expected item, found `;`
-//~^ ERROR `main` function
-fn foo() {}
+++ /dev/null
-error: expected item, found `;`
- --> $DIR/issue-49040.rs:1:28
- |
-LL | #![allow(unused_variables)];
- | ^ help: remove this semicolon
-
-error[E0601]: `main` function not found in crate `issue_49040`
- --> $DIR/issue-49040.rs:1:1
- |
-LL | #![allow(unused_variables)];
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ consider adding a `main` function to `$DIR/issue-49040.rs`
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0601`.
+++ /dev/null
-// check-pass
-
-fn fibs(n: u32) -> impl Iterator<Item=u128> {
- (0 .. n)
- .scan((0, 1), |st, _| {
- *st = (st.1, st.0 + st.1);
- Some(*st)
- })
- .map(&|(f, _)| f)
-}
-
-fn main() {
- println!("{:?}", fibs(10).collect::<Vec<_>>());
-}
+++ /dev/null
-// run-pass
-// Regression test for #49685: drop elaboration was not revealing the
-// value of `impl Trait` returns, leading to an ICE.
-
-fn main() {
- let _ = Some(())
- .into_iter()
- .flat_map(|_| Some(()).into_iter().flat_map(func));
-}
-
-fn func(_: ()) -> impl Iterator<Item = ()> {
- Some(()).into_iter().flat_map(|_| vec![])
-}
+++ /dev/null
-// run-pass
-enum Void {}
-fn foo(_: Result<(Void, u32), (Void, String)>) {}
-fn main() {
- let _: fn(_) = foo;
-}
+++ /dev/null
-trait B <A> {
- fn a() -> A {
- this.a //~ ERROR cannot find value `this` in this scope
- }
- fn b(x: i32) {
- this.b(x); //~ ERROR cannot find value `this` in this scope
- }
- fn c() {
- let _ = || this.a; //~ ERROR cannot find value `this` in this scope
- }
-}
-
-fn main() {}
+++ /dev/null
-error[E0425]: cannot find value `this` in this scope
- --> $DIR/issue-5099.rs:3:9
- |
-LL | this.a
- | ^^^^ not found in this scope
- |
-help: you might have meant to use `self` here instead
- |
-LL | self.a
- | ~~~~
-help: if you meant to use `self`, you are also missing a `self` receiver argument
- |
-LL | fn a(&self) -> A {
- | +++++
-
-error[E0425]: cannot find value `this` in this scope
- --> $DIR/issue-5099.rs:6:9
- |
-LL | this.b(x);
- | ^^^^ not found in this scope
- |
-help: you might have meant to use `self` here instead
- |
-LL | self.b(x);
- | ~~~~
-help: if you meant to use `self`, you are also missing a `self` receiver argument
- |
-LL | fn b(&self, x: i32) {
- | ++++++
-
-error[E0425]: cannot find value `this` in this scope
- --> $DIR/issue-5099.rs:9:20
- |
-LL | let _ = || this.a;
- | ^^^^ not found in this scope
- |
-help: you might have meant to use `self` here instead
- |
-LL | let _ = || self.a;
- | ~~~~
-help: if you meant to use `self`, you are also missing a `self` receiver argument
- |
-LL | fn c(&self) {
- | +++++
-
-error: aborting due to 3 previous errors
-
-For more information about this error, try `rustc --explain E0425`.
+++ /dev/null
-// compile-flags: --crate-type dylib --target thumbv7em-none-eabihf
-// needs-llvm-components: arm
-// build-pass
-// error-pattern: dropping unsupported crate type `dylib` for target `thumbv7em-none-eabihf`
-
-#![feature(no_core)]
-
-#![no_std]
-#![no_core]
+++ /dev/null
-warning: dropping unsupported crate type `dylib` for target `thumbv7em-none-eabihf`
-
-warning: 1 warning emitted
-
+++ /dev/null
-// run-pass
-fn foo() -> impl Into<for<'a> fn(&'a ())> {
- (|_| {}) as for<'a> fn(&'a ())
-}
-
-fn main() {
- foo().into()(&());
-}
+++ /dev/null
-// run-pass
-#![allow(unreachable_code)]
-
-fn main() {
- let mut v = Vec::new();
-
- loop { v.push(break) }
-}
+++ /dev/null
-// run-pass
-#![feature(core_intrinsics)]
-
-#[repr(i8)]
-pub enum Enum {
- VariantA,
- VariantB,
-}
-
-fn make_b() -> Enum { Enum::VariantB }
-
-fn main() {
- assert_eq!(1, make_b() as i8);
- assert_eq!(1, make_b() as u8);
- assert_eq!(1, make_b() as i32);
- assert_eq!(1, make_b() as u32);
- assert_eq!(1, std::intrinsics::discriminant_value(&make_b()));
-}
+++ /dev/null
-// Regression test for Issue #53787: Fix ICE when creating a label in inline assembler with macros.
-
-// build-fail
-// ignore-emscripten
-
-#![feature(llvm_asm)]
-#![allow(deprecated)] // llvm_asm!
-
-macro_rules! fake_jump {
- ($id:expr) => {
- unsafe {
- llvm_asm!(
- "
- jmp $0
- lea eax, [ebx]
- xor eax, 0xDEADBEEF
- retn
- $0:
- "::"0"($id)::"volatile", "intel");
- }
- };
-}
-
-fn main() {
- fake_jump!("FirstFunc"); //~ ERROR invalid value for constraint in inline assembly
- println!("Hello, world!");
-}
+++ /dev/null
-error[E0669]: invalid value for constraint in inline assembly
- --> $DIR/issue-53787-inline-assembler-macro.rs:25:16
- |
-LL | fake_jump!("FirstFunc");
- | ^^^^^^^^^^^
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0669`.
+++ /dev/null
-// run-pass
-
-pub trait Stream {
- type Item;
- type Error;
-}
-
-pub trait ParseError<I> {
- type Output;
-}
-
-impl ParseError<char> for u32 {
- type Output = ();
-}
-
-impl Stream for () {
- type Item = char;
- type Error = u32;
-}
-
-pub struct Lex<'a, I>
- where I: Stream,
- I::Error: ParseError<char>,
- <<I as Stream>::Error as ParseError<char>>::Output: 'a
-{
- x: &'a <I::Error as ParseError<char>>::Output
-}
-
-pub struct Reserved<'a, I> where
- I: Stream<Item=char> + 'a,
- I::Error: ParseError<I::Item>,
- <<I as Stream>::Error as ParseError<char>>::Output: 'a
-
-{
- x: Lex<'a, I>
-}
-
-fn main() {
- let r: Reserved<()> = Reserved {
- x: Lex {
- x: &()
- }
- };
-
- let _v = r.x.x;
-}
+++ /dev/null
-struct T;
-
-impl for T {}
-//~^ ERROR missing trait in a trait impl
-
-fn main() {}
+++ /dev/null
-error: missing trait in a trait impl
- --> $DIR/issue-56031.rs:3:5
- |
-LL | impl for T {}
- | ^
- |
-help: add a trait here
- |
-LL | impl Trait for T {}
- | +++++
-help: for an inherent impl, drop this `for`
- |
-LL - impl for T {}
-LL + impl T {}
- |
-
-error: aborting due to previous error
-
+++ /dev/null
-// check-pass
-
-// Originally from #53925.
-// Tests that the `unreachable_pub` lint doesn't fire for `pub self::bar::Bar`.
-
-#![deny(unreachable_pub)]
-
-mod foo {
- mod bar {
- pub struct Bar;
- }
-
- pub use self::bar::Bar;
-}
-
-pub use foo::Bar;
-
-fn main() {}
+++ /dev/null
-// Regression test for #57597.
-//
-// Make sure that nested matchers work correctly rather than causing an infinite loop or crash.
-
-// edition:2018
-
-macro_rules! foo1 {
- ($($($i:ident)?)+) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo2 {
- ($($($i:ident)?)*) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo3 {
- ($($($i:ident)?)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo4 {
- ($($($($i:ident)?)?)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo5 {
- ($($($($i:ident)*)?)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo6 {
- ($($($($i:ident)?)*)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo7 {
- ($($($($i:ident)?)?)*) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo8 {
- ($($($($i:ident)*)*)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo9 {
- ($($($($i:ident)?)*)*) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo10 {
- ($($($($i:ident)?)*)+) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo11 {
- ($($($($i:ident)+)?)*) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-macro_rules! foo12 {
- ($($($($i:ident)+)*)?) => {};
- //~^ ERROR repetition matches empty token tree
-}
-
-fn main() {
- foo1!();
- foo2!();
- foo3!();
- foo4!();
- foo5!();
- foo6!();
- foo7!();
- foo8!();
- foo9!();
- foo10!();
- foo11!();
- foo12!();
-}
+++ /dev/null
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:8:7
- |
-LL | ($($($i:ident)?)+) => {};
- | ^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:13:7
- |
-LL | ($($($i:ident)?)*) => {};
- | ^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:18:7
- |
-LL | ($($($i:ident)?)?) => {};
- | ^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:23:7
- |
-LL | ($($($($i:ident)?)?)?) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:28:7
- |
-LL | ($($($($i:ident)*)?)?) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:33:7
- |
-LL | ($($($($i:ident)?)*)?) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:38:7
- |
-LL | ($($($($i:ident)?)?)*) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:43:7
- |
-LL | ($($($($i:ident)*)*)?) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:48:7
- |
-LL | ($($($($i:ident)?)*)*) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:53:7
- |
-LL | ($($($($i:ident)?)*)+) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:58:7
- |
-LL | ($($($($i:ident)+)?)*) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: repetition matches empty token tree
- --> $DIR/issue-57597.rs:63:7
- |
-LL | ($($($($i:ident)+)*)?) => {};
- | ^^^^^^^^^^^^^^^^^^
-
-error: aborting due to 12 previous errors
-
+++ /dev/null
-// run-pass
-fn main() {}
-#[derive(Clone)]
-pub struct Little;
-#[derive(Clone)]
-pub struct Big(
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
- Little,
-);
+++ /dev/null
-#![feature(trait_alias)]
-
-trait Svc<Req> { type Res; }
-
-trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
-//~^ ERROR associated type `Res` not found for `Self`
-//~| ERROR associated type `Res` not found for `Self`
-
-fn main() {}
+++ /dev/null
-error[E0220]: associated type `Res` not found for `Self`
- --> $DIR/issue-59029-1.rs:5:52
- |
-LL | trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
- | ^^^ associated type `Res` not found
-
-error[E0220]: associated type `Res` not found for `Self`
- --> $DIR/issue-59029-1.rs:5:52
- |
-LL | trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
- | ^^^ associated type `Res` not found
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0220`.
+++ /dev/null
-#![allow(dead_code)]
-#![feature(const_generics_defaults)]
-
-// This test checks that generic parameter re-ordering diagnostic suggestions mention that
-// consts come after types and lifetimes when the `const_generics_defaults` feature is enabled.
-// We cannot run rustfix on this test because of the above const generics warning.
-
-struct A;
-
-impl A {
- pub fn do_things<T, 'a, 'b: 'a>() {
- //~^ ERROR lifetime parameters must be declared prior to type parameters
- println!("panic");
- }
-}
-
-fn main() {}
+++ /dev/null
-error: lifetime parameters must be declared prior to type parameters
- --> $DIR/issue-59508-1.rs:11:25
- |
-LL | pub fn do_things<T, 'a, 'b: 'a>() {
- | ----^^--^^----- help: reorder the parameters: lifetimes, then consts and types: `<'a, 'b: 'a, T>`
-
-error: aborting due to previous error
-
+++ /dev/null
-// run-rustfix
-
-#![allow(dead_code)]
-
-// This test checks that generic parameter re-ordering diagnostic suggestions contain bounds.
-
-struct A;
-
-impl A {
- pub fn do_things<'a, 'b: 'a, T>() {
- //~^ ERROR lifetime parameters must be declared prior to type parameters
- println!("panic");
- }
-}
-
-fn main() {}
+++ /dev/null
-// run-rustfix
-
-#![allow(dead_code)]
-
-// This test checks that generic parameter re-ordering diagnostic suggestions contain bounds.
-
-struct A;
-
-impl A {
- pub fn do_things<T, 'a, 'b: 'a>() {
- //~^ ERROR lifetime parameters must be declared prior to type parameters
- println!("panic");
- }
-}
-
-fn main() {}
+++ /dev/null
-error: lifetime parameters must be declared prior to type parameters
- --> $DIR/issue-59508.rs:10:25
- |
-LL | pub fn do_things<T, 'a, 'b: 'a>() {
- | ----^^--^^----- help: reorder the parameters: lifetimes, then types, then consts: `<'a, 'b: 'a, T>`
-
-error: aborting due to previous error
-
+++ /dev/null
-pub trait Trait<'a> {
- type Item;
-}
-
-impl<'a> Trait<'a> for () {
- type Item = ();
-}
-
-pub fn foo<T, F>(_: T, _: F)
-where
- T: for<'a> Trait<'a>,
- F: for<'a> FnMut(<T as Trait<'a>>::Item),
-{
-}
-
-fn main() {
- foo((), drop)
- //~^ ERROR type mismatch in function arguments
- //~| ERROR size for values of type `<() as Trait<'_>>::Item` cannot be known at compilation time
-}
+++ /dev/null
-error[E0631]: type mismatch in function arguments
- --> $DIR/issue-60283.rs:17:13
- |
-LL | foo((), drop)
- | --- ^^^^
- | | |
- | | expected signature of `for<'a> fn(<() as Trait<'a>>::Item) -> _`
- | | found signature of `fn(()) -> _`
- | required by a bound introduced by this call
- |
-note: required by a bound in `foo`
- --> $DIR/issue-60283.rs:12:16
- |
-LL | pub fn foo<T, F>(_: T, _: F)
- | --- required by a bound in this
-...
-LL | F: for<'a> FnMut(<T as Trait<'a>>::Item),
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `foo`
-
-error[E0277]: the size for values of type `<() as Trait<'_>>::Item` cannot be known at compilation time
- --> $DIR/issue-60283.rs:17:13
- |
-LL | foo((), drop)
- | --- ^^^^ doesn't have a size known at compile-time
- | |
- | required by a bound introduced by this call
- |
- = help: the trait `Sized` is not implemented for `<() as Trait<'_>>::Item`
-note: required by a bound in `std::mem::drop`
- --> $SRC_DIR/core/src/mem/mod.rs:LL:COL
- |
-LL | pub fn drop<T>(_x: T) {}
- | ^ required by this bound in `std::mem::drop`
-help: consider further restricting the associated type
- |
-LL | fn main() where <() as Trait<'_>>::Item: Sized {
- | ++++++++++++++++++++++++++++++++++++
-
-error: aborting due to 2 previous errors
-
-Some errors have detailed explanations: E0277, E0631.
-For more information about an error, try `rustc --explain E0277`.
+++ /dev/null
-// check-pass
-// compile-flags: -Z unpretty=hir
-
-#![feature(type_alias_impl_trait)]
-
-trait Animal {}
-
-fn main() {
- pub type ServeFut = impl Animal;
-}
+++ /dev/null
-// check-pass
-// compile-flags: -Z unpretty=hir
-
-#![feature(type_alias_impl_trait)]
-#[prelude_import]
-use ::std::prelude::rust_2015::*;
-#[macro_use]
-extern crate std;
-
-trait Animal { }
-
-fn main() {
- pub type ServeFut = /*impl Trait*/;
- }
+++ /dev/null
-// Issue 61711: A crate pub re-exporting `crate` was causing an
-// infinite loop.
-
-// edition:2018
-// aux-build:xcrate-issue-61711-b.rs
-// compile-flags:--extern xcrate_issue_61711_b
-
-// build-pass
-
-fn f<F: Fn(xcrate_issue_61711_b::Struct)>(_: F) { }
-fn main() { }
+++ /dev/null
-struct A<T>(T);
-
-impl A<&'static u8> {
- fn f() {
- let x = 0;
- Self(&x);
- //~^ ERROR `x` does not live long enough
- }
-}
-
-fn main() {}
+++ /dev/null
-error[E0597]: `x` does not live long enough
- --> $DIR/issue-61882-2.rs:6:14
- |
-LL | Self(&x);
- | ^^
- | |
- | borrowed value does not live long enough
- | this usage requires that `x` is borrowed for `'static`
-LL |
-LL | }
- | - `x` dropped here while still borrowed
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0597`.
+++ /dev/null
-struct A<T>(T);
-
-impl A<bool> {
- const B: A<u8> = Self(0);
- //~^ ERROR mismatched types
- //~| ERROR mismatched types
-}
-
-fn main() {}
+++ /dev/null
-error[E0308]: mismatched types
- --> $DIR/issue-61882.rs:4:27
- |
-LL | const B: A<u8> = Self(0);
- | ^ expected `bool`, found integer
-
-error[E0308]: mismatched types
- --> $DIR/issue-61882.rs:4:22
- |
-LL | const B: A<u8> = Self(0);
- | ^^^^^^^ expected `u8`, found `bool`
- |
- = note: expected struct `A<u8>`
- found struct `A<bool>`
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-fn part(_: u16) -> u32 {
- 1
-}
-
-fn main() {
- for n in 100_000.. {
- //~^ ERROR: literal out of range for `u16`
- let _ = part(n);
- }
-}
+++ /dev/null
-error: literal out of range for `u16`
- --> $DIR/issue-63364.rs:6:14
- |
-LL | for n in 100_000.. {
- | ^^^^^^^
- |
- = note: `#[deny(overflowing_literals)]` on by default
- = note: the literal `100_000` does not fit into the type `u16` whose range is `0..=65535`
-
-error: aborting due to previous error
-
+++ /dev/null
-macro_rules! e {
- ($inp:ident) => (
- $nonexistent
- //~^ ERROR expected expression, found `$`
- );
-}
-
-fn main() {
- e!(foo);
-}
+++ /dev/null
-error: expected expression, found `$`
- --> $DIR/issue-6596-1.rs:3:9
- |
-LL | $nonexistent
- | ^^^^^^^^^^^^ expected expression
-...
-LL | e!(foo);
- | ------- in this macro invocation
- |
- = note: this error originates in the macro `e` (in Nightly builds, run with -Z macro-backtrace for more info)
-
-error: aborting due to previous error
-
+++ /dev/null
-// Matching against NaN should result in a warning
-
-#![allow(unused)]
-#![deny(illegal_floating_point_literal_pattern)]
-
-const NAN: f64 = f64::NAN;
-
-fn main() {
- let x = NAN;
- match x {
- NAN => {}, //~ ERROR floating-point types cannot be used
- //~| WARN this was previously accepted by the compiler but is being phased out
- _ => {},
- };
-
- match [x, 1.0] {
- [NAN, _] => {}, //~ ERROR floating-point types cannot be used
- //~| WARN this was previously accepted by the compiler but is being phased out
- _ => {},
- };
-}
+++ /dev/null
-error: floating-point types cannot be used in patterns
- --> $DIR/issue-6804.rs:11:9
- |
-LL | NAN => {},
- | ^^^
- |
-note: the lint level is defined here
- --> $DIR/issue-6804.rs:4:9
- |
-LL | #![deny(illegal_floating_point_literal_pattern)]
- | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
- = note: for more information, see issue #41620 <https://github.com/rust-lang/rust/issues/41620>
-
-error: floating-point types cannot be used in patterns
- --> $DIR/issue-6804.rs:17:10
- |
-LL | [NAN, _] => {},
- | ^^^
- |
- = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
- = note: for more information, see issue #41620 <https://github.com/rust-lang/rust/issues/41620>
-
-error: aborting due to 2 previous errors
-
+++ /dev/null
-// check-pass
-
-pub trait ResultExt {
- type Ok;
- fn err_eprint_and_ignore(self) -> Option<Self::Ok>;
-}
-
-impl<O, E> ResultExt for std::result::Result<O, E>
-where
- E: std::error::Error,
-{
- type Ok = O;
- fn err_eprint_and_ignore(self) -> Option<O>
- where
- Self: ,
- {
- match self {
- Err(e) => {
- eprintln!("{}", e);
- None
- }
- Ok(o) => Some(o),
- }
- }
-}
-
-fn main() {}
+++ /dev/null
-struct Binder(i32, i32, i32);
-
-fn main() {
- let x = Binder(1, 2, 3);
- match x {
- Binder(_a, _x @ ..) => {}
- _ => {}
- }
-}
-//~^^^^ ERROR `_x @` is not allowed in a tuple struct
-//~| ERROR: `..` patterns are not allowed here
-//~| ERROR: this pattern has 2 fields, but the corresponding tuple struct has 3 fields
+++ /dev/null
-error: `_x @` is not allowed in a tuple struct
- --> $DIR/issue-72574-2.rs:6:20
- |
-LL | Binder(_a, _x @ ..) => {}
- | ^^^^^^^ this is only allowed in slice patterns
- |
- = help: remove this and bind each tuple field independently
-help: if you don't need to use the contents of _x, discard the tuple's remaining fields
- |
-LL | Binder(_a, ..) => {}
- | ~~
-
-error: `..` patterns are not allowed here
- --> $DIR/issue-72574-2.rs:6:25
- |
-LL | Binder(_a, _x @ ..) => {}
- | ^^
- |
- = note: only allowed in tuple, tuple struct, and slice patterns
-
-error[E0023]: this pattern has 2 fields, but the corresponding tuple struct has 3 fields
- --> $DIR/issue-72574-2.rs:6:16
- |
-LL | struct Binder(i32, i32, i32);
- | --- --- --- tuple struct has 3 fields
-...
-LL | Binder(_a, _x @ ..) => {}
- | ^^ ^^^^^^^ expected 3 fields, found 2
- |
-help: use `_` to explicitly ignore each field
- |
-LL | Binder(_a, _x @ .., _) => {}
- | +++
-
-error: aborting due to 3 previous errors
-
-For more information about this error, try `rustc --explain E0023`.
+++ /dev/null
-// edition:2018
-
-fn main() {
- 'a: loop {
- async {
- loop {
- continue 'a
- //~^ ERROR use of unreachable label `'a`
- }
- };
- }
-}
+++ /dev/null
-error[E0767]: use of unreachable label `'a`
- --> $DIR/issue-73541-1.rs:7:26
- |
-LL | 'a: loop {
- | -- unreachable label defined here
-...
-LL | continue 'a
- | ^^ unreachable label `'a`
- |
- = note: labels are unreachable through functions, closures, async blocks and modules
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0767`.
+++ /dev/null
-fn main() {
- let _ = &&[0] as &[_];
- //~^ ERROR non-primitive cast: `&&[i32; 1]` as `&[_]`
- let _ = 7u32 as Option<_>;
- //~^ ERROR non-primitive cast: `u32` as `Option<_>`
-}
+++ /dev/null
-error[E0605]: non-primitive cast: `&&[i32; 1]` as `&[_]`
- --> $DIR/issue-73886.rs:2:13
- |
-LL | let _ = &&[0] as &[_];
- | ^^^^^^^^^^^^^ an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
-
-error[E0605]: non-primitive cast: `u32` as `Option<_>`
- --> $DIR/issue-73886.rs:4:13
- |
-LL | let _ = 7u32 as Option<_>;
- | ^^^^^^^^^^^^^^^^^ help: consider using the `From` trait instead: `Option<_>::from(7u32)`
- |
- = note: an `as` expression can only be used to convert between primitive types or to coerce to a specific trait object
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0605`.
+++ /dev/null
-// compile-flags: -O
-// run-pass
-
-struct Foo {
- x: i32,
-}
-
-pub fn main() {
- let mut foo = Foo { x: 42 };
- let x = &mut foo.x;
- *x = 13;
- let y = foo;
- assert_eq!(y.x, 13); // used to print 42 due to mir-opt bug
-}
+++ /dev/null
-// run-fail
-// error-pattern:quux
-// ignore-emscripten no processes
-
-use std::marker::PhantomData;
-
-fn test00_start(ch: Chan<isize>, message: isize) {
- send(ch, message);
-}
-
-type TaskId = isize;
-type PortId = isize;
-
-struct Chan<T> {
- task: TaskId,
- port: PortId,
- marker: PhantomData<*mut T>,
-}
-
-fn send<T: Send>(_ch: Chan<T>, _data: T) {
- panic!();
-}
-
-fn main() {
- panic!("quux");
-}
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-
-enum E {
- Foo{f: isize},
- Bar,
-}
-
-pub fn main() {
- let e = E::Foo{f: 0};
- match e {
- E::Foo{f: 1} => panic!(),
- E::Foo{..} => (),
- _ => panic!(),
- }
-}
+++ /dev/null
-// run-pass
-#![allow(dead_code)]
-
-enum E {
- Foo{f: isize, b: bool},
- Bar,
-}
-
-pub fn main() {
- let e = E::Foo{f: 0, b: false};
- match e {
- E::Foo{f: 1, b: true} => panic!(),
- E::Foo{b: false, f: 0} => (),
- _ => panic!(),
- }
-}
+++ /dev/null
-use std::fmt::Write;
-
-fn main() {
- println!(b"foo");
- //~^ ERROR format argument must be a string literal
- //~| HELP consider removing the leading `b`
- let mut s = String::new();
- write!(s, b"foo{}", "bar");
- //~^ ERROR format argument must be a string literal
- //~| HELP consider removing the leading `b`
-}
+++ /dev/null
-error: format argument must be a string literal
- --> $DIR/issue-86865.rs:4:14
- |
-LL | println!(b"foo");
- | -^^^^^
- | |
- | help: consider removing the leading `b`
-
-error: format argument must be a string literal
- --> $DIR/issue-86865.rs:8:15
- |
-LL | write!(s, b"foo{}", "bar");
- | -^^^^^^^
- | |
- | help: consider removing the leading `b`
-
-error: aborting due to 2 previous errors
-
+++ /dev/null
-// run-pass
-// ignore-emscripten no threads support
-
-use std::thread;
-use std::sync::mpsc::{channel, Receiver};
-
-fn periodical(n: isize) -> Receiver<bool> {
- let (chan, port) = channel();
- thread::spawn(move|| {
- loop {
- for _ in 1..n {
- match chan.send(false) {
- Ok(()) => {}
- Err(..) => break,
- }
- }
- match chan.send(true) {
- Ok(()) => {}
- Err(..) => break
- }
- }
- });
- return port;
-}
-
-fn integers() -> Receiver<isize> {
- let (chan, port) = channel();
- thread::spawn(move|| {
- let mut i = 1;
- loop {
- match chan.send(i) {
- Ok(()) => {}
- Err(..) => break,
- }
- i = i + 1;
- }
- });
- return port;
-}
-
-fn main() {
- let ints = integers();
- let threes = periodical(3);
- let fives = periodical(5);
- for _ in 1..100 {
- match (ints.recv().unwrap(), threes.recv().unwrap(), fives.recv().unwrap()) {
- (_, true, true) => println!("FizzBuzz"),
- (_, true, false) => println!("Fizz"),
- (_, false, true) => println!("Buzz"),
- (i, false, false) => println!("{}", i)
- }
- }
-}
+++ /dev/null
-// run-pass
-#![allow(unused_must_use)]
-#![allow(deprecated)]
-// ignore-emscripten no threads support
-
-use std::sync::mpsc::{TryRecvError, channel};
-use std::thread;
-
-pub fn main() {
- let (tx, rx) = channel();
- let t = thread::spawn(move||{
- thread::sleep_ms(10);
- tx.send(()).unwrap();
- });
- loop {
- match rx.try_recv() {
- Ok(()) => break,
- Err(TryRecvError::Empty) => {}
- Err(TryRecvError::Disconnected) => unreachable!()
- }
- }
- t.join();
-}
+++ /dev/null
-// run-pass
-// shouldn't affect evaluation of $ex:
-macro_rules! bad_macro {
- ($ex:expr) => ({(|_x| { $ex }) (9) })
-}
-
-fn takes_x(_x : isize) {
- assert_eq!(bad_macro!(_x),8);
-}
-fn main() {
- takes_x(8);
-}
--- /dev/null
+// error-pattern: requires `copy` lang_item
+
+#![feature(lang_items, start, no_core)]
+#![no_core]
+
+#[lang = "sized"]
+trait Sized { }
+
+struct S;
+
+#[start]
+fn main(_: isize, _: *const *const u8) -> isize {
+ let _ = S;
+ 0
+}
--- /dev/null
+error: requires `copy` lang_item
+
+error: aborting due to previous error
+
--- /dev/null
+#![feature(no_core, lang_items)]
+#![no_core]
+
+#[lang="sized"]
+trait Sized {}
+
+#[lang="add"]
+trait Add<T> {}
+
+impl Add<i32> for i32 {}
+
+fn main() {
+ let x = 5 + 6;
+ //~^ ERROR cannot add `i32` to `{integer}`
+ let y = 5i32 + 6i32;
+ //~^ ERROR cannot add `i32` to `i32`
+}
--- /dev/null
+error[E0369]: cannot add `i32` to `{integer}`
+ --> $DIR/issue-31076.rs:13:15
+ |
+LL | let x = 5 + 6;
+ | - ^ - i32
+ | |
+ | {integer}
+
+error[E0369]: cannot add `i32` to `i32`
+ --> $DIR/issue-31076.rs:15:18
+ |
+LL | let y = 5i32 + 6i32;
+ | ---- ^ ---- i32
+ | |
+ | i32
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0369`.
--- /dev/null
+// build-fail
+
+#![feature(lang_items, no_core)]
+#![no_core]
+
+#[lang="copy"] pub trait Copy { }
+#[lang="sized"] pub trait Sized { }
+
+// error-pattern:requires `start` lang_item
+
+fn main() {}
--- /dev/null
+error: requires `start` lang_item
+
+error: aborting due to previous error
+
+++ /dev/null
-// aux-build:legacy-const-generics.rs
-
-extern crate legacy_const_generics;
-
-fn foo<const N: usize>() {
- let a = 1;
- legacy_const_generics::foo(0, a, 2);
- //~^ ERROR attempt to use a non-constant value in a constant
-
- legacy_const_generics::foo(0, N, 2);
-
- legacy_const_generics::foo(0, N + 1, 2);
- //~^ ERROR generic parameters may not be used in const operations
-}
-
-fn main() {}
+++ /dev/null
-error[E0435]: attempt to use a non-constant value in a constant
- --> $DIR/legacy-const-generics-bad.rs:7:35
- |
-LL | let a = 1;
- | ----- help: consider using `const` instead of `let`: `const a`
-LL | legacy_const_generics::foo(0, a, 2);
- | ^ non-constant value
-
-error: generic parameters may not be used in const operations
- --> $DIR/legacy-const-generics-bad.rs:12:35
- |
-LL | legacy_const_generics::foo(0, N + 1, 2);
- | ^ cannot perform const operation using `N`
- |
- = help: const parameters may only be used as standalone arguments, i.e. `N`
- = help: use `#![feature(generic_const_exprs)]` to allow generic const expressions
-
-error: aborting due to 2 previous errors
-
-For more information about this error, try `rustc --explain E0435`.
+++ /dev/null
-// aux-build:legacy-const-generics.rs
-// run-pass
-
-#![feature(rustc_attrs)]
-
-extern crate legacy_const_generics;
-
-#[rustc_legacy_const_generics(1)]
-pub fn bar<const Y: usize>(x: usize, z: usize) -> [usize; 3] {
- [x, Y, z]
-}
-
-fn main() {
- assert_eq!(legacy_const_generics::foo(0 + 0, 1 + 1, 2 + 2), [0, 2, 4]);
- assert_eq!(legacy_const_generics::foo::<{1 + 1}>(0 + 0, 2 + 2), [0, 2, 4]);
- // FIXME: Only works cross-crate
- //assert_eq!(bar(0, 1, 2), [0, 1, 2]);
-}
--- /dev/null
+fn parse_type(iter: Box<dyn Iterator<Item=&str>+'static>) -> &str { iter.next() }
+//~^ ERROR missing lifetime specifier [E0106]
+
+fn parse_type_2(iter: fn(&u8)->&u8) -> &str { iter() }
+//~^ ERROR missing lifetime specifier [E0106]
+
+fn parse_type_3() -> &str { unimplemented!() }
+//~^ ERROR missing lifetime specifier [E0106]
+
+fn main() {}
--- /dev/null
+error[E0106]: missing lifetime specifier
+ --> $DIR/issue-26638.rs:1:62
+ |
+LL | fn parse_type(iter: Box<dyn Iterator<Item=&str>+'static>) -> &str { iter.next() }
+ | ------------------------------------ ^ expected named lifetime parameter
+ |
+ = help: this function's return type contains a borrowed value, but the signature does not say which one of `iter`'s 2 lifetimes it is borrowed from
+help: consider introducing a named lifetime parameter
+ |
+LL | fn parse_type<'a>(iter: Box<dyn Iterator<Item=&str>+'static>) -> &'a str { iter.next() }
+ | ++++ ++
+
+error[E0106]: missing lifetime specifier
+ --> $DIR/issue-26638.rs:4:40
+ |
+LL | fn parse_type_2(iter: fn(&u8)->&u8) -> &str { iter() }
+ | ^ expected named lifetime parameter
+ |
+ = help: this function's return type contains a borrowed value with an elided lifetime, but the lifetime cannot be derived from the arguments
+help: consider using the `'static` lifetime
+ |
+LL | fn parse_type_2(iter: fn(&u8)->&u8) -> &'static str { iter() }
+ | ~~~~~~~~
+
+error[E0106]: missing lifetime specifier
+ --> $DIR/issue-26638.rs:7:22
+ |
+LL | fn parse_type_3() -> &str { unimplemented!() }
+ | ^ expected named lifetime parameter
+ |
+ = help: this function's return type contains a borrowed value, but there is no value for it to be borrowed from
+help: consider using the `'static` lifetime
+ |
+LL | fn parse_type_3() -> &'static str { unimplemented!() }
+ | ~~~~~~~~
+
+error: aborting due to 3 previous errors
+
+For more information about this error, try `rustc --explain E0106`.
--- /dev/null
+// check-pass
+// pretty-expanded FIXME #23616
+
+#[deny(dead_code)]
+pub enum Foo {
+ Bar {
+ baz: isize
+ }
+}
+
+fn main() { }
--- /dev/null
+// check-pass
+
+// Originally from #53925.
+// Tests that the `unreachable_pub` lint doesn't fire for `pub self::bar::Bar`.
+
+#![deny(unreachable_pub)]
+
+mod foo {
+ mod bar {
+ pub struct Bar;
+ }
+
+ pub use self::bar::Bar;
+}
+
+pub use foo::Bar;
+
+fn main() {}
--- /dev/null
+fn part(_: u16) -> u32 {
+ 1
+}
+
+fn main() {
+ for n in 100_000.. {
+ //~^ ERROR: literal out of range for `u16`
+ let _ = part(n);
+ }
+}
--- /dev/null
+error: literal out of range for `u16`
+ --> $DIR/issue-63364.rs:6:14
+ |
+LL | for n in 100_000.. {
+ | ^^^^^^^
+ |
+ = note: `#[deny(overflowing_literals)]` on by default
+ = note: the literal `100_000` does not fit into the type `u16` whose range is `0..=65535`
+
+error: aborting due to previous error
+
--- /dev/null
+// edition:2018
+
+#![deny(unused_extern_crates)]
+#![feature(test, rustc_private, crate_visibility_modifier)]
+
+extern crate libc;
+//~^ ERROR unused extern crate
+//~| HELP remove
+extern crate libc as x;
+//~^ ERROR unused extern crate
+//~| HELP remove
+
+extern crate proc_macro;
+
+#[macro_use]
+extern crate test;
+
+pub extern crate test as y;
+
+pub extern crate alloc;
+
+pub(crate) extern crate alloc as a;
+
+crate extern crate alloc as b;
+
+mod foo {
+ pub(in crate::foo) extern crate alloc as c;
+
+ pub(super) extern crate alloc as d;
+
+ extern crate libc;
+ //~^ ERROR unused extern crate
+ //~| HELP remove
+
+ extern crate libc as x;
+ //~^ ERROR unused extern crate
+ //~| HELP remove
+
+ pub extern crate test;
+
+ pub extern crate test as y;
+
+ mod bar {
+ extern crate libc;
+ //~^ ERROR unused extern crate
+ //~| HELP remove
+
+ extern crate libc as x;
+ //~^ ERROR unused extern crate
+ //~| HELP remove
+
+ pub(in crate::foo::bar) extern crate alloc as e;
+
+ fn dummy() {
+ e::string::String::new();
+ }
+ }
+
+ fn dummy() {
+ c::string::String::new();
+ d::string::String::new();
+ }
+}
+
+
+fn main() {
+ a::string::String::new();
+ b::string::String::new();
+
+ proc_macro::TokenStream::new();
+}
--- /dev/null
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:6:1
+ |
+LL | extern crate libc;
+ | ^^^^^^^^^^^^^^^^^^ help: remove it
+ |
+note: the lint level is defined here
+ --> $DIR/unnecessary-extern-crate.rs:3:9
+ |
+LL | #![deny(unused_extern_crates)]
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:9:1
+ |
+LL | extern crate libc as x;
+ | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
+
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:31:5
+ |
+LL | extern crate libc;
+ | ^^^^^^^^^^^^^^^^^^ help: remove it
+
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:35:5
+ |
+LL | extern crate libc as x;
+ | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
+
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:44:9
+ |
+LL | extern crate libc;
+ | ^^^^^^^^^^^^^^^^^^ help: remove it
+
+error: unused extern crate
+ --> $DIR/unnecessary-extern-crate.rs:48:9
+ |
+LL | extern crate libc as x;
+ | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
+
+error: aborting due to 6 previous errors
+
--- /dev/null
+// run-pass
+
+#![allow(dead_code)]
+// compile-flags:-D improper-ctypes
+
+// pretty-expanded FIXME #23616
+#![allow(improper_ctypes)]
+
+mod libc {
+ extern "C" {
+ pub fn malloc(size: isize) -> *const u8;
+ }
+}
+
+pub fn main() {}
--- /dev/null
+#![feature(llvm_asm)]
+#![allow(deprecated)] // llvm_asm!
+// compile-flags: -Ccodegen-units=1
+// build-fail
+// only-x86_64
+
+fn main() {
+ unsafe {
+ llvm_asm!("int $3"); //~ ERROR too few operands for instruction
+ //~| ERROR invalid operand in inline asm
+ }
+}
--- /dev/null
+error: invalid operand in inline asm: 'int $3'
+ --> $DIR/issue-23458.rs:9:9
+ |
+LL | llvm_asm!("int $3");
+ | ^
+
+error: too few operands for instruction
+ --> $DIR/issue-23458.rs:9:9
+ |
+LL | llvm_asm!("int $3");
+ | ^
+ |
+note: instantiated into assembly here
+ --> <inline asm>:1:2
+ |
+LL | int
+ | ^
+
+error: aborting due to 2 previous errors
+
--- /dev/null
+// check-pass
+// ignore-emscripten
+
+#![feature(llvm_asm)]
+#![allow(deprecated)] // llvm_asm!
+
+macro_rules! interrupt_handler {
+ () => {
+ unsafe fn _interrupt_handler() {
+ llvm_asm!("pop eax" :::: "intel");
+ }
+ }
+}
+interrupt_handler!{}
+
+fn main() {}
--- /dev/null
+// Regression test for Issue #53787: Fix ICE when creating a label in inline assembler with macros.
+
+// build-fail
+// ignore-emscripten
+
+#![feature(llvm_asm)]
+#![allow(deprecated)] // llvm_asm!
+
+macro_rules! fake_jump {
+ ($id:expr) => {
+ unsafe {
+ llvm_asm!(
+ "
+ jmp $0
+ lea eax, [ebx]
+ xor eax, 0xDEADBEEF
+ retn
+ $0:
+ "::"0"($id)::"volatile", "intel");
+ }
+ };
+}
+
+fn main() {
+ fake_jump!("FirstFunc"); //~ ERROR invalid value for constraint in inline assembly
+ println!("Hello, world!");
+}
--- /dev/null
+error[E0669]: invalid value for constraint in inline assembly
+ --> $DIR/issue-53787-inline-assembler-macro.rs:25:16
+ |
+LL | fake_jump!("FirstFunc");
+ | ^^^^^^^^^^^
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0669`.
+++ /dev/null
-// run-pass
-// pretty-expanded FIXME #23616
-
-#![allow(unused_variables)]
-
-pub fn main() {
- let mut i: isize = 0;
- while i < 1000000 {
- i += 1;
- let x = 3;
- }
-}
+++ /dev/null
-// compile-flags: -C lto -C embed-bitcode=no
-
-fn main() {}
+++ /dev/null
-error: options `-C embed-bitcode=no` and `-C lto` are incompatible
-
+++ /dev/null
-// build-fail
-// aux-build:lto-duplicate-symbols1.rs
-// aux-build:lto-duplicate-symbols2.rs
-// error-pattern:Linking globals named 'foo': symbol multiply defined!
-// compile-flags: -C lto
-// no-prefer-dynamic
-
-extern crate lto_duplicate_symbols1;
-extern crate lto_duplicate_symbols2;
-
-fn main() {}
+++ /dev/null
-warning: Linking globals named 'foo': symbol multiply defined!
-
-error: failed to load bc of "lto-duplicate-symbols2.lto_duplicate_symbols2.693a75b4-cgu.0.rcgu.o":
-
-error: aborting due to previous error; 1 warning emitted
-
+++ /dev/null
-// run-pass
-// compile-flags: -C lto -C codegen-units=8
-// no-prefer-dynamic
-
-fn main() {
-}
+++ /dev/null
-// compile-flags: -Clinker-plugin-lto -Copt-level=s
-// build-pass
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-pub fn foo() {}
+++ /dev/null
-// compile-flags: -Clinker-plugin-lto -Copt-level=z
-// build-pass
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-pub fn foo() {}
+++ /dev/null
-// compile-flags: -C lto
-// aux-build:lto-rustc-loads-linker-plugin.rs
-// run-pass
-// no-prefer-dynamic
-
-// This test ensures that if a dependency was compiled with
-// `-Clinker-plugin-lto` then we can compile with `-Clto` and still link against
-// that upstream rlib. This should work because LTO implies we're not actually
-// linking against upstream rlibs since we're generating the object code
-// locally. This test will fail if rustc can't find bytecode in rlibs compiled
-// with `-Clinker-plugin-lto`.
-
-extern crate lto_rustc_loads_linker_plugin;
-
-fn main() {
- lto_rustc_loads_linker_plugin::foo();
-}
+++ /dev/null
-// run-pass
-// compile-flags: -C lto
-// no-prefer-dynamic
-// ignore-emscripten no threads support
-// revisions: mir thir
-// [thir]compile-flags: -Zthir-unsafeck
-
-use std::thread;
-
-static mut HIT: usize = 0;
-
-thread_local!(static A: Foo = Foo);
-
-struct Foo;
-
-impl Drop for Foo {
- fn drop(&mut self) {
- unsafe {
- HIT += 1;
- }
- }
-}
-
-fn main() {
- unsafe {
- assert_eq!(HIT, 0);
- thread::spawn(|| {
- assert_eq!(HIT, 0);
- A.with(|_| ());
- assert_eq!(HIT, 0);
- }).join().unwrap();
- assert_eq!(HIT, 1);
- }
-}
+++ /dev/null
-// compile-flags: -C lto=thin
-// aux-build:lto-rustc-loads-linker-plugin.rs
-// run-pass
-// no-prefer-dynamic
-
-// Same as the adjacent `lto-thin-rustc-loads-linker-plugin.rs` test, only with
-// ThinLTO.
-
-extern crate lto_rustc_loads_linker_plugin;
-
-fn main() {
- lto_rustc_loads_linker_plugin::foo();
-}
--- /dev/null
+// run-pass
+
+// compile-flags: -Clto=thin
+// no-prefer-dynamic
+
+fn main() {
+ println!("hello!");
+}
--- /dev/null
+// compile-flags: -Z thinlto -C codegen-units=8
+
+#[inline]
+pub fn foo(b: u8) {
+ b.to_string();
+}
--- /dev/null
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+#[no_mangle]
+pub extern "C" fn foo() {}
--- /dev/null
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+#[no_mangle]
+pub extern "C" fn foo() {}
--- /dev/null
+// compile-flags: -Clinker-plugin-lto
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+pub fn foo() {}
--- /dev/null
+// no-prefer-dynamic
+// compile-flags: -Z thinlto -C codegen-units=8 -C prefer-dynamic
+
+#![crate_type = "rlib"]
+#![crate_type = "dylib"]
+
+pub static A: u32 = 43;
+
+pub mod a {
+ pub static A: u32 = 43;
+}
--- /dev/null
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+pub fn bar() -> u32 {
+ 3
+}
--- /dev/null
+// run-pass
+
+// aux-build:dylib.rs
+
+extern crate dylib;
+
+fn main() {
+ dylib::foo(1);
+}
--- /dev/null
+// compile-flags: -C lto -C embed-bitcode=no
+
+fn main() {}
--- /dev/null
+error: options `-C embed-bitcode=no` and `-C lto` are incompatible
+
--- /dev/null
+// build-fail
+// aux-build:lto-duplicate-symbols1.rs
+// aux-build:lto-duplicate-symbols2.rs
+// error-pattern:Linking globals named 'foo': symbol multiply defined!
+// compile-flags: -C lto
+// no-prefer-dynamic
+
+extern crate lto_duplicate_symbols1;
+extern crate lto_duplicate_symbols2;
+
+fn main() {}
--- /dev/null
+warning: Linking globals named 'foo': symbol multiply defined!
+
+error: failed to load bc of "lto-duplicate-symbols2.lto_duplicate_symbols2.693a75b4-cgu.0.rcgu.o":
+
+error: aborting due to previous error; 1 warning emitted
+
--- /dev/null
+// run-pass
+// compile-flags: -C lto -C codegen-units=8
+// no-prefer-dynamic
+
+fn main() {
+}
--- /dev/null
+// compile-flags: -Clinker-plugin-lto -Copt-level=s
+// build-pass
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+pub fn foo() {}
--- /dev/null
+// compile-flags: -Clinker-plugin-lto -Copt-level=z
+// build-pass
+// no-prefer-dynamic
+
+#![crate_type = "rlib"]
+
+pub fn foo() {}
--- /dev/null
+// compile-flags: -C lto
+// aux-build:lto-rustc-loads-linker-plugin.rs
+// run-pass
+// no-prefer-dynamic
+
+// This test ensures that if a dependency was compiled with
+// `-Clinker-plugin-lto` then we can compile with `-Clto` and still link against
+// that upstream rlib. This should work because LTO implies we're not actually
+// linking against upstream rlibs since we're generating the object code
+// locally. This test will fail if rustc can't find bytecode in rlibs compiled
+// with `-Clinker-plugin-lto`.
+
+extern crate lto_rustc_loads_linker_plugin;
+
+fn main() {
+ lto_rustc_loads_linker_plugin::foo();
+}
--- /dev/null
+// run-pass
+// compile-flags: -C lto
+// no-prefer-dynamic
+// ignore-emscripten no threads support
+// revisions: mir thir
+// [thir]compile-flags: -Zthir-unsafeck
+
+use std::thread;
+
+static mut HIT: usize = 0;
+
+thread_local!(static A: Foo = Foo);
+
+struct Foo;
+
+impl Drop for Foo {
+ fn drop(&mut self) {
+ unsafe {
+ HIT += 1;
+ }
+ }
+}
+
+fn main() {
+ unsafe {
+ assert_eq!(HIT, 0);
+ thread::spawn(|| {
+ assert_eq!(HIT, 0);
+ A.with(|_| ());
+ assert_eq!(HIT, 0);
+ }).join().unwrap();
+ assert_eq!(HIT, 1);
+ }
+}
--- /dev/null
+// compile-flags: -C lto=thin
+// aux-build:lto-rustc-loads-linker-plugin.rs
+// run-pass
+// no-prefer-dynamic
+
+// Same as the adjacent `lto-thin-rustc-loads-linker-plugin.rs` test, only with
+// ThinLTO.
+
+extern crate lto_rustc_loads_linker_plugin;
+
+fn main() {
+ lto_rustc_loads_linker_plugin::foo();
+}
--- /dev/null
+// run-pass
+
+// aux-build:msvc-imp-present.rs
+// compile-flags: -Z thinlto -C codegen-units=8
+// no-prefer-dynamic
+
+// On MSVC we have a "hack" where we emit symbols that look like `_imp_$name`
+// for all exported statics. This is done because we apply `dllimport` to all
+// imported constants and this allows everything to actually link correctly.
+//
+// The ThinLTO passes aggressively remove symbols if they can, and this test
+// asserts that the ThinLTO passes don't remove these compiler-generated
+// `_imp_*` symbols. The external library that we link in here is compiled with
+// ThinLTO and multiple codegen units and has a few exported constants. Note
+// that we also namely compile the library as both a dylib and an rlib, but we
+// link the rlib to ensure that we assert those generated symbols exist.
+
+extern crate msvc_imp_present as bar;
+
+fn main() {
+ println!("{}", bar::A);
+}
--- /dev/null
+// run-pass
+// compile-flags: -Z thinlto -C codegen-units=2
+
+#[global_allocator]
+static A: std::alloc::System = std::alloc::System;
+
+fn main() {}
--- /dev/null
+// run-pass
+
+// compile-flags: -Z thinlto -C codegen-units=8 -O
+// ignore-emscripten can't inspect instructions on emscripten
+
+// We want to assert here that ThinLTO will inline across codegen units. There's
+// not really a great way to do that in general so we sort of hack around it by
+// praying two functions go into separate codegen units and then assuming that
+// if inlining *doesn't* happen the first byte of the functions will differ.
+
+pub fn foo() -> u32 {
+ bar::bar()
+}
+
+mod bar {
+ pub fn bar() -> u32 {
+ 3
+ }
+}
+
+fn main() {
+ println!("{} {}", foo(), bar::bar());
+
+ unsafe {
+ let foo = foo as usize as *const u8;
+ let bar = bar::bar as usize as *const u8;
+
+ assert_eq!(*foo, *bar);
+ }
+}
--- /dev/null
+// run-pass
+
+// compile-flags: -C codegen-units=8 -O -C lto=thin
+// aux-build:thin-lto-inlines-aux.rs
+// no-prefer-dynamic
+// ignore-emscripten can't inspect instructions on emscripten
+
+// We want to assert here that ThinLTO will inline across codegen units. There's
+// not really a great way to do that in general so we sort of hack around it by
+// praying two functions go into separate codegen units and then assuming that
+// if inlining *doesn't* happen the first byte of the functions will differ.
+
+extern crate thin_lto_inlines_aux as bar;
+
+pub fn foo() -> u32 {
+ bar::bar()
+}
+
+fn main() {
+ println!("{} {}", foo(), bar::bar());
+
+ unsafe {
+ let foo = foo as usize as *const u8;
+ let bar = bar::bar as usize as *const u8;
+
+ assert_eq!(*foo, *bar);
+ }
+}
--- /dev/null
+// run-pass
+
+// compile-flags: -C codegen-units=8 -Z thinlto
+// ignore-windows
+
+#![feature(linkage)]
+
+pub mod foo {
+ #[linkage = "weak"]
+ #[no_mangle]
+ pub extern "C" fn FOO() -> i32 {
+ 0
+ }
+}
+
+mod bar {
+ extern "C" {
+ fn FOO() -> i32;
+ }
+
+ pub fn bar() -> i32 {
+ unsafe { FOO() }
+ }
+}
+
+fn main() {
+ bar::bar();
+}
+++ /dev/null
-// run-pass
-// Test for a specific corner case: when we compute the LUB of two fn
-// types and their parameters have unbound variables. In that case, we
-// wind up relating those two variables. This was causing an ICE in an
-// in-progress PR.
-
-fn main() {
- let a_f: fn(_) = |_| ();
- let b_f: fn(_) = |_| ();
- let c_f = match 22 {
- 0 => a_f,
- _ => b_f,
- };
- c_f(4);
-}
--- /dev/null
+#![crate_type = "lib"]
+
+#[macro_export]
+macro_rules! mywrite {
+ ($dst:expr, $($arg:tt)*) => ($dst.write_fmt(format_args!($($arg)*)))
+}
--- /dev/null
+macro_rules! prob1 {
+ (0) => {
+ 0
+ };
+ ($n:expr) => {
+ if ($n % 3 == 0) || ($n % 5 == 0) {
+ $n + prob1!($n - 1); //~ ERROR recursion limit reached while expanding `prob1!`
+ } else {
+ prob1!($n - 1);
+ }
+ };
+}
+
+fn main() {
+ println!("Problem 1: {}", prob1!(1000));
+}
--- /dev/null
+error: recursion limit reached while expanding `prob1!`
+ --> $DIR/issue-16098.rs:7:18
+ |
+LL | $n + prob1!($n - 1);
+ | ^^^^^^^^^^^^^^
+...
+LL | println!("Problem 1: {}", prob1!(1000));
+ | ------------ in this macro invocation
+ |
+ = help: consider increasing the recursion limit by adding a `#![recursion_limit = "256"]` attribute to your crate (`issue_16098`)
+ = note: this error originates in the macro `prob1` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: aborting due to previous error
+
--- /dev/null
+// aux-build:issue-19163.rs
+
+#[macro_use] extern crate issue_19163;
+
+use std::io::Write;
+
+fn main() {
+ let mut v = vec![];
+ mywrite!(&v, "Hello world");
+ //~^ ERROR cannot borrow data in a `&` reference as mutable
+}
--- /dev/null
+error[E0596]: cannot borrow data in a `&` reference as mutable
+ --> $DIR/issue-19163.rs:9:5
+ |
+LL | mywrite!(&v, "Hello world");
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ cannot borrow as mutable
+ |
+ = note: this error originates in the macro `mywrite` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0596`.
--- /dev/null
+#![allow(unused_macros)]
+
+macro_rules! test { ($wrong:t_ty ..) => () }
+ //~^ ERROR: invalid fragment specifier `t_ty`
+
+fn main() {}
--- /dev/null
+error: invalid fragment specifier `t_ty`
+ --> $DIR/issue-21356.rs:3:22
+ |
+LL | macro_rules! test { ($wrong:t_ty ..) => () }
+ | ^^^^^^^^^^^
+ |
+ = help: valid fragment specifiers are `ident`, `block`, `stmt`, `expr`, `pat`, `ty`, `lifetime`, `literal`, `path`, `meta`, `tt`, `item` and `vis`
+
+error: aborting due to previous error
+
--- /dev/null
+// run-pass
+macro_rules! items {
+ () => {
+ type A = ();
+ fn a() {}
+ }
+}
+
+trait Foo {
+ type A;
+ fn a();
+}
+
+impl Foo for () {
+ items!();
+}
+
+fn main() {
+
+}
--- /dev/null
+macro_rules! foo {
+ ($d:expr) => {{
+ fn bar(d: u8) { }
+ bar(&mut $d);
+ //~^ ERROR mismatched types
+ //~| expected `u8`, found `&mut u8`
+ }}
+}
+
+fn main() {
+ foo!(0u8);
+ //~^ in this expansion of foo!
+}
--- /dev/null
+error[E0308]: mismatched types
+ --> $DIR/issue-29084.rs:4:13
+ |
+LL | bar(&mut $d);
+ | ^^^^^^^ expected `u8`, found `&mut u8`
+...
+LL | foo!(0u8);
+ | --------- in this macro invocation
+ |
+ = note: this error originates in the macro `foo` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0308`.
--- /dev/null
+// check-pass
+
+macro_rules! null { ($i:tt) => {} }
+macro_rules! apply_null {
+ ($i:item) => { null! { $i } }
+}
+
+fn main() {
+ apply_null!(#[cfg(all())] fn f() {});
+}
--- /dev/null
+// run-pass
+macro_rules! m { (<$t:ty>) => { stringify!($t) } }
+fn main() {
+ println!("{}", m!(<Vec<i32>>));
+}
--- /dev/null
+#![allow(unused_macros)]
+
+macro_rules! assign {
+ (($($a:tt)*) = ($($b:tt))*) => { //~ ERROR expected one of: `*`, `+`, or `?`
+ $($a)* = $($b)*
+ }
+}
+
+fn main() {}
--- /dev/null
+error: expected one of: `*`, `+`, or `?`
+ --> $DIR/issue-39388.rs:4:22
+ |
+LL | (($($a:tt)*) = ($($b:tt))*) => {
+ | ^^^^^^^
+
+error: aborting due to previous error
+
--- /dev/null
+// run-pass
+#![allow(unused_macros)]
+macro_rules! m {
+ ($e:expr) => {
+ macro_rules! n { () => { $e } }
+ }
+}
+
+fn main() {
+ m!(foo!());
+}
--- /dev/null
+// Regression test for #57597.
+//
+// Make sure that nested matchers work correctly rather than causing an infinite loop or crash.
+
+// edition:2018
+
+macro_rules! foo1 {
+ ($($($i:ident)?)+) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo2 {
+ ($($($i:ident)?)*) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo3 {
+ ($($($i:ident)?)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo4 {
+ ($($($($i:ident)?)?)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo5 {
+ ($($($($i:ident)*)?)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo6 {
+ ($($($($i:ident)?)*)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo7 {
+ ($($($($i:ident)?)?)*) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo8 {
+ ($($($($i:ident)*)*)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo9 {
+ ($($($($i:ident)?)*)*) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo10 {
+ ($($($($i:ident)?)*)+) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo11 {
+ ($($($($i:ident)+)?)*) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+macro_rules! foo12 {
+ ($($($($i:ident)+)*)?) => {};
+ //~^ ERROR repetition matches empty token tree
+}
+
+fn main() {
+ foo1!();
+ foo2!();
+ foo3!();
+ foo4!();
+ foo5!();
+ foo6!();
+ foo7!();
+ foo8!();
+ foo9!();
+ foo10!();
+ foo11!();
+ foo12!();
+}
--- /dev/null
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:8:7
+ |
+LL | ($($($i:ident)?)+) => {};
+ | ^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:13:7
+ |
+LL | ($($($i:ident)?)*) => {};
+ | ^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:18:7
+ |
+LL | ($($($i:ident)?)?) => {};
+ | ^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:23:7
+ |
+LL | ($($($($i:ident)?)?)?) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:28:7
+ |
+LL | ($($($($i:ident)*)?)?) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:33:7
+ |
+LL | ($($($($i:ident)?)*)?) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:38:7
+ |
+LL | ($($($($i:ident)?)?)*) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:43:7
+ |
+LL | ($($($($i:ident)*)*)?) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:48:7
+ |
+LL | ($($($($i:ident)?)*)*) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:53:7
+ |
+LL | ($($($($i:ident)?)*)+) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:58:7
+ |
+LL | ($($($($i:ident)+)?)*) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: repetition matches empty token tree
+ --> $DIR/issue-57597.rs:63:7
+ |
+LL | ($($($($i:ident)+)*)?) => {};
+ | ^^^^^^^^^^^^^^^^^^
+
+error: aborting due to 12 previous errors
+
--- /dev/null
+macro_rules! e {
+ ($inp:ident) => (
+ $nonexistent
+ //~^ ERROR expected expression, found `$`
+ );
+}
+
+fn main() {
+ e!(foo);
+}
--- /dev/null
+error: expected expression, found `$`
+ --> $DIR/issue-6596-1.rs:3:9
+ |
+LL | $nonexistent
+ | ^^^^^^^^^^^^ expected expression
+...
+LL | e!(foo);
+ | ------- in this macro invocation
+ |
+ = note: this error originates in the macro `e` (in Nightly builds, run with -Z macro-backtrace for more info)
+
+error: aborting due to previous error
+
--- /dev/null
+use std::fmt::Write;
+
+fn main() {
+ println!(b"foo");
+ //~^ ERROR format argument must be a string literal
+ //~| HELP consider removing the leading `b`
+ let mut s = String::new();
+ write!(s, b"foo{}", "bar");
+ //~^ ERROR format argument must be a string literal
+ //~| HELP consider removing the leading `b`
+}
--- /dev/null
+error: format argument must be a string literal
+ --> $DIR/issue-86865.rs:4:14
+ |
+LL | println!(b"foo");
+ | -^^^^^
+ | |
+ | help: consider removing the leading `b`
+
+error: format argument must be a string literal
+ --> $DIR/issue-86865.rs:8:15
+ |
+LL | write!(s, b"foo{}", "bar");
+ | -^^^^^^^
+ | |
+ | help: consider removing the leading `b`
+
+error: aborting due to 2 previous errors
+
--- /dev/null
+#![feature(trace_macros)]
+
+fn main() {
+ trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false`
+ trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false`
+ trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false`
+ trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false`
+ trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false`
+ trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false`
+
+
+ // should be fine:
+ macro_rules! expando {
+ ($x: ident) => { trace_macros!($x) }
+ }
+
+ expando!(true);
+}
--- /dev/null
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:4:5
+ |
+LL | trace_macros!();
+ | ^^^^^^^^^^^^^^^
+
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:5:5
+ |
+LL | trace_macros!(1);
+ | ^^^^^^^^^^^^^^^^
+
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:6:5
+ |
+LL | trace_macros!(ident);
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:7:5
+ |
+LL | trace_macros!(for);
+ | ^^^^^^^^^^^^^^^^^^
+
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:8:5
+ |
+LL | trace_macros!(true,);
+ | ^^^^^^^^^^^^^^^^^^^^
+
+error: trace_macros! accepts only `true` or `false`
+ --> $DIR/trace_macros-format.rs:9:5
+ |
+LL | trace_macros!(false 1);
+ | ^^^^^^^^^^^^^^^^^^^^^^
+
+error: aborting due to 6 previous errors
+
--- /dev/null
+// run-pass
+
+#![feature(marker_trait_attr)]
+#![feature(specialization)] //~ WARN the feature `specialization` is incomplete
+
+#[marker]
+trait MyMarker {}
+
+impl<T> MyMarker for T {}
+impl<T> MyMarker for Vec<T> {}
+
+fn foo<T: MyMarker>(t: T) -> T {
+ t
+}
+
+fn main() {
+ assert_eq!(1, foo(1));
+ assert_eq!(2.0, foo(2.0));
+ assert_eq!(vec![1], foo(vec![1]));
+}
--- /dev/null
+warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes
+ --> $DIR/overlap-doesnt-conflict-with-specialization.rs:4:12
+ |
+LL | #![feature(specialization)]
+ | ^^^^^^^^^^^^^^
+ |
+ = note: `#[warn(incomplete_features)]` on by default
+ = note: see issue #31844 <https://github.com/rust-lang/rust/issues/31844> for more information
+ = help: consider using `min_specialization` instead, which is more stable and complete
+
+warning: 1 warning emitted
+
--- /dev/null
+// run-pass
+// Tests for RFC 1268: we allow overlapping impls of marker traits,
+// that is, traits with #[marker]. In this case, a type `T` is
+// `MyMarker` if it is either `Debug` or `Display`.
+
+#![feature(marker_trait_attr)]
+
+use std::fmt::{Debug, Display};
+
+#[marker] trait MyMarker {}
+
+impl<T: Debug> MyMarker for T {}
+impl<T: Display> MyMarker for T {}
+
+fn foo<T: MyMarker>(t: T) -> T {
+ t
+}
+
+fn main() {
+ // Debug && Display:
+ assert_eq!(1, foo(1));
+ assert_eq!(2.0, foo(2.0));
+
+ // Debug && !Display:
+ assert_eq!(vec![1], foo(vec![1]));
+}
--- /dev/null
+// run-pass
+
+const TEST_STR: &'static str = "abcd";
+
+fn main() {
+ let s = "abcd";
+ match s {
+ TEST_STR => (),
+ _ => unreachable!()
+ }
+}
--- /dev/null
+// run-pass
+// Regression test for #18060: match arms were matching in the wrong order.
+
+fn main() {
+ assert_eq!(2, match (1, 3) { (0, 2..=5) => 1, (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
+ assert_eq!(2, match (1, 3) { (1, 3) => 2, (_, 2..=5) => 3, (_, _) => 4 });
+ assert_eq!(2, match (1, 7) { (0, 2..=5) => 1, (1, 7) => 2, (_, 2..=5) => 3, (_, _) => 4 });
+}
--- /dev/null
+// run-pass
+#![allow(overlapping_range_endpoints)]
+
+fn main() {
+ let x = 'a';
+
+ let y = match x {
+ 'a'..='b' if false => "one",
+ 'a' => "two",
+ 'a'..='b' => "three",
+ _ => panic!("what?"),
+ };
+
+ assert_eq!(y, "two");
+}
--- /dev/null
+// run-pass
+
+// This test is bogus (i.e., should be check-fail) during the period
+// where #54986 is implemented and #54987 is *not* implemented. For
+// now: just ignore it
+//
+// ignore-test
+
+// This test is checking that the write to `c.0` (which has been moved out of)
+// won't overwrite the state in `c2`.
+//
+// That's a fine thing to test when this code is accepted by the
+// compiler, and this code is being transcribed accordingly into
+// the ui test issue-21232-partial-init-and-use.rs
+
+fn main() {
+ let mut c = (1, "".to_owned());
+ match c {
+ c2 => {
+ c.0 = 2;
+ assert_eq!(c2.0, 1);
+ }
+ }
+}
--- /dev/null
+// run-pass
+#![feature(box_syntax)]
+#![feature(box_patterns)]
+
+#[derive(Debug, PartialEq)]
+enum Test {
+ Foo(usize),
+ Bar(isize),
+}
+
+fn main() {
+ let a = box Test::Foo(10);
+ let b = box Test::Bar(-20);
+ match (a, b) {
+ (_, box Test::Foo(_)) => unreachable!(),
+ (box Test::Foo(x), b) => {
+ assert_eq!(x, 10);
+ assert_eq!(b, box Test::Bar(-20));
+ },
+ _ => unreachable!(),
+ }
+}
--- /dev/null
+// compile-flags: -O
+// run-pass
+
+struct Foo {
+ x: i32,
+}
+
+pub fn main() {
+ let mut foo = Foo { x: 42 };
+ let x = &mut foo.x;
+ *x = 13;
+ let y = foo;
+ assert_eq!(y.x, 13); // used to print 42 due to mir-opt bug
+}
+++ /dev/null
-// run-pass
-// pretty-expanded FIXME #23616
-
-pub fn main() {
- let _x: &mut [isize] = &mut [ 1, 2, 3 ];
-}
+++ /dev/null
-// run-pass
-
-pub fn main() {
- match -5 {
- -5 => {}
- _ => { panic!() }
- }
-}
+++ /dev/null
-// run-pass
-// aux-build:nested_item.rs
-
-
-extern crate nested_item;
-
-pub fn main() {
- assert_eq!(2, nested_item::foo::<()>());
- assert_eq!(2, nested_item::foo::<isize>());
-}
--- /dev/null
+// After #39485, this test used to pass, but that change was reverted
+// due to numerous inference failures like #39808, so it now fails
+// again. #39485 made it so that diverging types never propagate
+// upward; but we now do propagate such types upward in many more
+// cases.
+
+fn g() {
+ &panic!() //~ ERROR mismatched types
+}
+
+fn f() -> isize {
+ (return 1, return 2) //~ ERROR mismatched types
+}
+
+fn main() {}
--- /dev/null
+error[E0308]: mismatched types
+ --> $DIR/diverging-tuple-parts-39485.rs:8:5
+ |
+LL | &panic!()
+ | ^^^^^^^^^ expected `()`, found reference
+ |
+ = note: expected unit type `()`
+ found reference `&_`
+help: try adding a return type
+ |
+LL | fn g() -> &_ {
+ | +++++
+help: consider removing the borrow
+ |
+LL - &panic!()
+LL + panic!()
+ |
+
+error[E0308]: mismatched types
+ --> $DIR/diverging-tuple-parts-39485.rs:12:5
+ |
+LL | fn f() -> isize {
+ | ----- expected `isize` because of return type
+LL | (return 1, return 2)
+ | ^^^^^^^^^^^^^^^^^^^^ expected `isize`, found tuple
+ |
+ = note: expected type `isize`
+ found tuple `(!, !)`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-// run-pass
-
-fn f(x: Box<isize>) {
- let y: &isize = &*x;
- println!("{}", *x);
- println!("{}", *y);
-}
-
-trait Trait {
- fn printme(&self);
-}
-
-struct Struct;
-
-impl Trait for Struct {
- fn printme(&self) {
- println!("hello world!");
- }
-}
-
-fn g(x: Box<dyn Trait>) {
- x.printme();
- let y: &dyn Trait = &*x;
- y.printme();
-}
-
-fn main() {
- f(Box::new(1234));
- g(Box::new(Struct) as Box<dyn Trait>);
-}
+++ /dev/null
-// run-pass
-
-#![allow(improper_ctypes)]
-#![allow(dead_code)]
-// Issue #901
-// pretty-expanded FIXME #23616
-
-mod libc {
- extern "C" {
- pub fn printf(x: ());
- }
-}
-
-pub fn main() {}
--- /dev/null
+// run-pass
+
+pub fn main() {
+ let a = 1;
+ let a_neg: i8 = -a;
+ println!("{}", a_neg);
+
+ let b = 1;
+ let b_neg: i16 = -b;
+ println!("{}", b_neg);
+
+ let c = 1;
+ let c_neg: i32 = -c;
+ println!("{}", c_neg);
+
+ let d = 1;
+ let d_neg: i64 = -d;
+ println!("{}", d_neg);
+
+ let e = 1;
+ let e_neg: isize = -e;
+ println!("{}", e_neg);
+}
+++ /dev/null
-// Test that an object type `Box<Foo>` is not considered to implement the
-// trait `Foo`. Issue #5087.
-
-trait Foo {}
-fn take_foo<F:Foo>(f: F) {}
-fn take_object(f: Box<dyn Foo>) { take_foo(f); }
-//~^ ERROR `Box<dyn Foo>: Foo` is not satisfied
-fn main() {}
+++ /dev/null
-error[E0277]: the trait bound `Box<dyn Foo>: Foo` is not satisfied
- --> $DIR/object-does-not-impl-trait.rs:6:44
- |
-LL | fn take_object(f: Box<dyn Foo>) { take_foo(f); }
- | -------- ^ the trait `Foo` is not implemented for `Box<dyn Foo>`
- | |
- | required by a bound introduced by this call
- |
-note: required by a bound in `take_foo`
- --> $DIR/object-does-not-impl-trait.rs:5:15
- |
-LL | fn take_foo<F:Foo>(f: F) {}
- | ^^^ required by this bound in `take_foo`
-
-error: aborting due to previous error
-
-For more information about this error, try `rustc --explain E0277`.
+++ /dev/null
-// run-pass
-
-#![feature(marker_trait_attr)]
-#![feature(specialization)] //~ WARN the feature `specialization` is incomplete
-
-#[marker]
-trait MyMarker {}
-
-impl<T> MyMarker for T {}
-impl<T> MyMarker for Vec<T> {}
-
-fn foo<T: MyMarker>(t: T) -> T {
- t
-}
-
-fn main() {
- assert_eq!(1, foo(1));
- assert_eq!(2.0, foo(2.0));
- assert_eq!(vec![1], foo(vec![1]));
-}
+++ /dev/null
-warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes
- --> $DIR/overlap-doesnt-conflict-with-specialization.rs:4:12
- |
-LL | #![feature(specialization)]
- | ^^^^^^^^^^^^^^
- |
- = note: `#[warn(incomplete_features)]` on by default
- = note: see issue #31844 <https://github.com/rust-lang/rust/issues/31844> for more information
- = help: consider using `min_specialization` instead, which is more stable and complete
-
-warning: 1 warning emitted
-
+++ /dev/null
-// run-pass
-// Tests for RFC 1268: we allow overlapping impls of marker traits,
-// that is, traits with #[marker]. In this case, a type `T` is
-// `MyMarker` if it is either `Debug` or `Display`.
-
-#![feature(marker_trait_attr)]
-
-use std::fmt::{Debug, Display};
-
-#[marker] trait MyMarker {}
-
-impl<T: Debug> MyMarker for T {}
-impl<T: Display> MyMarker for T {}
-
-fn foo<T: MyMarker>(t: T) -> T {
- t
-}
-
-fn main() {
- // Debug && Display:
- assert_eq!(1, foo(1));
- assert_eq!(2.0, foo(2.0));
-
- // Debug && !Display:
- assert_eq!(vec![1], foo(vec![1]));
-}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+#![allow(unused_variables)]
+#![feature(unsize, coerce_unsized)]
+
+#[repr(packed)]
+struct UnalignedPtr<'a, T: ?Sized>
+ where T: 'a,
+{
+ data: &'a T,
+}
+
+fn main() {
+
+ impl<'a, T, U> std::ops::CoerceUnsized<UnalignedPtr<'a, U>> for UnalignedPtr<'a, T>
+ where
+ T: std::marker::Unsize<U> + ?Sized,
+ U: ?Sized,
+ { }
+
+ let arr = [1, 2, 3];
+ let arr_unaligned: UnalignedPtr<[i32; 3]> = UnalignedPtr { data: &arr };
+ let arr_unaligned: UnalignedPtr<[i32]> = arr_unaligned;
+}
--- /dev/null
+// check-pass
+
+// Bastion of the Turbofish
+// ------------------------
+// Beware travellers, lest you venture into waters callous and unforgiving,
+// where hope must be abandoned, ere it is cruelly torn from you. For here
+// stands the bastion of the Turbofish: an impenetrable fortress holding
+// unshaking against those who would dare suggest the supererogation of the
+// Turbofish.
+//
+// Once I was young and foolish and had the impudence to imagine that I could
+// shake free from the coils by which that creature had us tightly bound. I
+// dared to suggest that there was a better way: a brighter future, in which
+// Rustaceans both new and old could be rid of that vile beast. But alas! In
+// my foolhardiness my ignorance was unveiled and my dreams were dashed
+// unforgivingly against the rock of syntactic ambiguity.
+//
+// This humble program, small and insignificant though it might seem,
+// demonstrates that to which we had previously cast a blind eye: an ambiguity
+// in permitting generic arguments to be provided without the consent of the
+// Great Turbofish. Should you be so naïve as to try to revolt against its
+// mighty clutches, here shall its wrath be indomitably displayed. This
+// program must pass for all eternity: forever watched by the guardian angel
+// which gave this beast its name, and stands fundamentally at odds with the
+// impetuous rebellion against the Turbofish.
+//
+// My heart aches in sorrow, for I know I am defeated. Let this be a warning
+// to all those who come after: for they too must overcome the impassible
+// hurdle of defeating the great beast, championed by a resolute winged
+// guardian.
+//
+// Here stands the Bastion of the Turbofish, a memorial to Anna Harren,
+// Guardian Angel of these Hallowed Grounds. <3
+
+// See https://github.com/rust-lang/rust/pull/53562
+// and https://github.com/rust-lang/rfcs/pull/2527
+// and https://twitter.com/garblefart/status/1393236602856611843
+// for context.
+
+fn main() {
+ let (the, guardian, stands, resolute) = ("the", "Turbofish", "remains", "undefeated");
+ let _: (bool, bool) = (the<guardian, stands>(resolute));
+}
--- /dev/null
+fn main() {
+ if true {
+ } else if { //~ ERROR missing condition
+ //~^ ERROR mismatched types
+ } else {
+ }
+}
+
+fn foo() {
+ if true {
+ } else if { //~ ERROR missing condition
+ //~^ ERROR mismatched types
+ }
+ bar();
+}
+
+fn bar() {}
--- /dev/null
+error: missing condition for `if` expression
+ --> $DIR/issue-13483.rs:3:14
+ |
+LL | } else if {
+ | ^ expected if condition here
+
+error: missing condition for `if` expression
+ --> $DIR/issue-13483.rs:11:14
+ |
+LL | } else if {
+ | ^ expected if condition here
+
+error[E0308]: mismatched types
+ --> $DIR/issue-13483.rs:3:15
+ |
+LL | } else if {
+ | _______________^
+LL | |
+LL | | } else {
+ | |_____^ expected `bool`, found `()`
+
+error[E0308]: mismatched types
+ --> $DIR/issue-13483.rs:11:15
+ |
+LL | } else if {
+ | _______________^
+LL | |
+LL | | }
+ | |_____^ expected `bool`, found `()`
+
+error: aborting due to 4 previous errors
+
+For more information about this error, try `rustc --explain E0308`.
--- /dev/null
+// We need all these 9 issue-20616-N.rs files
+// because we can only catch one parsing error at a time
+
+type Type_1_<'a, T> = &'a T;
+
+
+//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
+
+
+//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
+
+
+//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
+
+
+type Type_4<T> = Type_1_<'static,, T>;
+//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
+
+
+type Type_5_<'a> = Type_1_<'a, ()>;
+
+
+//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
+
+
+//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
+
+
+//type Type_7 = Box<(),,>; // error: expected type, found `,`
+
+
+//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
+
+
+//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
--- /dev/null
+error: expected one of `>`, a const expression, lifetime, or type, found `,`
+ --> $DIR/issue-20616-4.rs:16:34
+ |
+LL | type Type_4<T> = Type_1_<'static,, T>;
+ | ^ expected one of `>`, a const expression, lifetime, or type
+
+error: aborting due to previous error
+
--- /dev/null
+// We need all these 9 issue-20616-N.rs files
+// because we can only catch one parsing error at a time
+
+type Type_1_<'a, T> = &'a T;
+
+
+//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
+
+
+//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
+
+
+//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
+
+
+//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
+
+
+type Type_5_<'a> = Type_1_<'a, ()>;
+
+
+type Type_5<'a> = Type_1_<'a, (),,>;
+//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
+
+
+//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
+
+
+//type Type_7 = Box<(),,>; // error: expected type, found `,`
+
+
+//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
+
+
+//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
--- /dev/null
+error: expected one of `>`, a const expression, lifetime, or type, found `,`
+ --> $DIR/issue-20616-5.rs:22:34
+ |
+LL | type Type_5<'a> = Type_1_<'a, (),,>;
+ | ^ expected one of `>`, a const expression, lifetime, or type
+
+error: aborting due to previous error
+
--- /dev/null
+// We need all these 9 issue-20616-N.rs files
+// because we can only catch one parsing error at a time
+
+type Type_1_<'a, T> = &'a T;
+
+
+//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
+
+
+//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
+
+
+//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
+
+
+//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
+
+
+type Type_5_<'a> = Type_1_<'a, ()>;
+
+
+//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
+
+
+type Type_6 = Type_5_<'a,,>;
+//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
+
+
+//type Type_7 = Box<(),,>; // error: expected type, found `,`
+
+
+//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
+
+
+//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
--- /dev/null
+error: expected one of `>`, a const expression, lifetime, or type, found `,`
+ --> $DIR/issue-20616-6.rs:25:26
+ |
+LL | type Type_6 = Type_5_<'a,,>;
+ | ^ expected one of `>`, a const expression, lifetime, or type
+
+error: aborting due to previous error
+
--- /dev/null
+// We need all these 9 issue-20616-N.rs files
+// because we can only catch one parsing error at a time
+
+type Type_1_<'a, T> = &'a T;
+
+
+//type Type_1<'a T> = &'a T; // error: expected `,` or `>` after lifetime name, found `T`
+
+
+//type Type_2 = Type_1_<'static ()>; // error: expected `,` or `>` after lifetime name, found `(`
+
+
+//type Type_3<T> = Box<T,,>; // error: expected type, found `,`
+
+
+//type Type_4<T> = Type_1_<'static,, T>; // error: expected type, found `,`
+
+
+type Type_5_<'a> = Type_1_<'a, ()>;
+
+
+//type Type_5<'a> = Type_1_<'a, (),,>; // error: expected type, found `,`
+
+
+//type Type_6 = Type_5_<'a,,>; // error: expected type, found `,`
+
+
+type Type_7 = Box<(),,>;
+//~^ error: expected one of `>`, a const expression, lifetime, or type, found `,`
+
+
+//type Type_8<'a,,> = &'a (); // error: expected ident, found `,`
+
+
+//type Type_9<T,,> = Box<T>; // error: expected ident, found `,`
--- /dev/null
+error: expected one of `>`, a const expression, lifetime, or type, found `,`
+ --> $DIR/issue-20616-7.rs:28:22
+ |
+LL | type Type_7 = Box<(),,>;
+ | ^ expected one of `>`, a const expression, lifetime, or type
+
+error: aborting due to previous error
+
--- /dev/null
+// run-pass
+#![allow(unused_imports, overlapping_range_endpoints)]
+// pretty-expanded FIXME #23616
+
+use m::{START, END};
+
+fn main() {
+ match 42 {
+ m::START..=m::END => {},
+ 0..=m::END => {},
+ m::START..=59 => {},
+ _ => {},
+ }
+}
+
+mod m {
+ pub const START: u32 = 4;
+ pub const END: u32 = 14;
+}
--- /dev/null
+// Test that error recovery in the parser to an EOF does not give an infinite
+// spew of errors.
+
+fn main() {
+ let
+} //~ ERROR expected pattern, found `}`
--- /dev/null
+error: expected pattern, found `}`
+ --> $DIR/issue-31804.rs:6:1
+ |
+LL | }
+ | ^ expected pattern
+
+error: aborting due to previous error
+
--- /dev/null
+enum Test {
+ Drill {
+ field: i32,
+ }
+}
+
+fn main() {
+ Test::Drill(field: 42);
+ //~^ ERROR invalid `struct` delimiters or `fn` call arguments
+}
--- /dev/null
+error: invalid `struct` delimiters or `fn` call arguments
+ --> $DIR/issue-34255-1.rs:8:5
+ |
+LL | Test::Drill(field: 42);
+ | ^^^^^^^^^^^^^^^^^^^^^^
+ |
+help: if `Test::Drill` is a struct, use braces as delimiters
+ |
+LL | Test::Drill { field: 42 };
+ | ~ ~
+help: if `Test::Drill` is a function, use the arguments directly
+ |
+LL - Test::Drill(field: 42);
+LL + Test::Drill(42);
+ |
+
+error: aborting due to previous error
+
--- /dev/null
+#![allow(unused_variables)]; //~ ERROR expected item, found `;`
+//~^ ERROR `main` function
+fn foo() {}
--- /dev/null
+error: expected item, found `;`
+ --> $DIR/issue-49040.rs:1:28
+ |
+LL | #![allow(unused_variables)];
+ | ^ help: remove this semicolon
+
+error[E0601]: `main` function not found in crate `issue_49040`
+ --> $DIR/issue-49040.rs:1:1
+ |
+LL | #![allow(unused_variables)];
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ consider adding a `main` function to `$DIR/issue-49040.rs`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0601`.
--- /dev/null
+struct T;
+
+impl for T {}
+//~^ ERROR missing trait in a trait impl
+
+fn main() {}
--- /dev/null
+error: missing trait in a trait impl
+ --> $DIR/issue-56031.rs:3:5
+ |
+LL | impl for T {}
+ | ^
+ |
+help: add a trait here
+ |
+LL | impl Trait for T {}
+ | +++++
+help: for an inherent impl, drop this `for`
+ |
+LL - impl for T {}
+LL + impl T {}
+ |
+
+error: aborting due to previous error
+
--- /dev/null
+// run-pass
+// Destructuring struct variants would ICE where regular structs wouldn't
+
+enum Foo {
+ VBar { num: isize }
+}
+
+struct SBar { num: isize }
+
+pub fn main() {
+ let vbar = Foo::VBar { num: 1 };
+ let Foo::VBar { num } = vbar;
+ assert_eq!(num, 1);
+
+ let sbar = SBar { num: 2 };
+ let SBar { num } = sbar;
+ assert_eq!(num, 2);
+}
--- /dev/null
+// run-pass
+
+fn main() {
+ let mut x: &[_] = &[1, 2, 3, 4];
+
+ let mut result = vec![];
+ loop {
+ x = match *x {
+ [1, n, 3, ref rest @ ..] => {
+ result.push(n);
+ rest
+ }
+ [n, ref rest @ ..] => {
+ result.push(n);
+ rest
+ }
+ [] =>
+ break
+ }
+ }
+ assert_eq!(result, [2, 4]);
+}
--- /dev/null
+struct Binder(i32, i32, i32);
+
+fn main() {
+ let x = Binder(1, 2, 3);
+ match x {
+ Binder(_a, _x @ ..) => {}
+ _ => {}
+ }
+}
+//~^^^^ ERROR `_x @` is not allowed in a tuple struct
+//~| ERROR: `..` patterns are not allowed here
+//~| ERROR: this pattern has 2 fields, but the corresponding tuple struct has 3 fields
--- /dev/null
+error: `_x @` is not allowed in a tuple struct
+ --> $DIR/issue-72574-2.rs:6:20
+ |
+LL | Binder(_a, _x @ ..) => {}
+ | ^^^^^^^ this is only allowed in slice patterns
+ |
+ = help: remove this and bind each tuple field independently
+help: if you don't need to use the contents of _x, discard the tuple's remaining fields
+ |
+LL | Binder(_a, ..) => {}
+ | ~~
+
+error: `..` patterns are not allowed here
+ --> $DIR/issue-72574-2.rs:6:25
+ |
+LL | Binder(_a, _x @ ..) => {}
+ | ^^
+ |
+ = note: only allowed in tuple, tuple struct, and slice patterns
+
+error[E0023]: this pattern has 2 fields, but the corresponding tuple struct has 3 fields
+ --> $DIR/issue-72574-2.rs:6:16
+ |
+LL | struct Binder(i32, i32, i32);
+ | --- --- --- tuple struct has 3 fields
+...
+LL | Binder(_a, _x @ ..) => {}
+ | ^^ ^^^^^^^ expected 3 fields, found 2
+ |
+help: use `_` to explicitly ignore each field
+ |
+LL | Binder(_a, _x @ .., _) => {}
+ | +++
+
+error: aborting due to 3 previous errors
+
+For more information about this error, try `rustc --explain E0023`.
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+
+enum E {
+ Foo{f: isize},
+ Bar,
+}
+
+pub fn main() {
+ let e = E::Foo{f: 0};
+ match e {
+ E::Foo{f: 1} => panic!(),
+ E::Foo{..} => (),
+ _ => panic!(),
+ }
+}
--- /dev/null
+// run-pass
+#![allow(dead_code)]
+
+enum E {
+ Foo{f: isize, b: bool},
+ Bar,
+}
+
+pub fn main() {
+ let e = E::Foo{f: 0, b: false};
+ match e {
+ E::Foo{f: 1, b: true} => panic!(),
+ E::Foo{b: false, f: 0} => (),
+ _ => panic!(),
+ }
+}
--- /dev/null
+// run-pass
+#![allow(unused_mut)]
+// ignore-emscripten no processes
+// ignore-sgx no processes
+
+use std::env;
+use std::io::prelude::*;
+use std::io;
+use std::process::{Command, Stdio};
+
+fn main() {
+ let args: Vec<String> = env::args().collect();
+ if args.len() > 1 && args[1] == "child" {
+ return child()
+ }
+
+ test();
+}
+
+fn child() {
+ writeln!(&mut io::stdout(), "foo").unwrap();
+ writeln!(&mut io::stderr(), "bar").unwrap();
+ let mut stdin = io::stdin();
+ let mut s = String::new();
+ stdin.lock().read_line(&mut s).unwrap();
+ assert_eq!(s.len(), 0);
+}
+
+fn test() {
+ let args: Vec<String> = env::args().collect();
+ let mut p = Command::new(&args[0]).arg("child")
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn().unwrap();
+ assert!(p.wait().unwrap().success());
+}
--- /dev/null
+// run-pass
+// ignore-emscripten no processes
+// ignore-sgx no processes
+
+use std::process::Command;
+use std::env;
+
+fn main() {
+ let len = env::args().len();
+
+ if len == 1 {
+ test();
+ } else {
+ assert_eq!(len, 3);
+ }
+}
+
+fn test() {
+ let status = Command::new(&env::current_exe().unwrap())
+ .arg("foo").arg("")
+ .status().unwrap();
+ assert!(status.success());
+}
--- /dev/null
+// run-pass
+#![allow(stable_features)]
+
+// ignore-emscripten no processes
+// ignore-sgx no processes
+
+#![feature(os)]
+
+#[cfg(unix)]
+fn main() {
+ use std::process::Command;
+ use std::env;
+ use std::os::unix::prelude::*;
+ use std::ffi::OsStr;
+
+ if env::args().len() == 1 {
+ assert!(Command::new(&env::current_exe().unwrap())
+ .arg(<OsStr as OsStrExt>::from_bytes(b"\xff"))
+ .status().unwrap().success())
+ }
+}
+
+#[cfg(windows)]
+fn main() {}
--- /dev/null
+// run-pass
+// ignore-emscripten no processes
+// ignore-sgx no processes
+// ignore-windows
+
+use std::env;
+use std::process::Command;
+
+pub fn main() {
+ let args: Vec<String> = env::args().collect();
+ if args.len() >= 2 && args[1] == "signal" {
+ // Raise a segfault.
+ unsafe { *(1 as *mut isize) = 0; }
+ } else {
+ let status = Command::new(&args[0]).arg("signal").status().unwrap();
+ assert!(status.code().is_none());
+ }
+}
--- /dev/null
+// check-pass
+#![allow(dead_code)]
+// Test that the requirement (in `Bar`) that `T::Bar : 'static` does
+// not wind up propagating to `T`.
+
+// pretty-expanded FIXME #23616
+
+pub trait Foo {
+ type Bar;
+
+ fn foo(&self) -> Self;
+}
+
+pub struct Static<T:'static>(T);
+
+struct Bar<T:Foo>
+ where T::Bar : 'static
+{
+ x: Static<Option<T::Bar>>
+}
+
+fn main() { }
--- /dev/null
+// run-pass
+
+pub trait Foo<T> {
+ fn foo(self) -> T;
+}
+
+impl<'a, T> Foo<T> for &'a str where &'a str: Into<T> {
+ fn foo(self) -> T {
+ panic!();
+ }
+}
+
+fn main() {}
--- /dev/null
+// check-pass
+
+pub struct Bar<T> {
+ items: Vec<&'static str>,
+ inner: T,
+}
+
+pub trait IntoBar<T> {
+ fn into_bar(self) -> Bar<T>;
+}
+
+impl<'a, T> IntoBar<T> for &'a str where &'a str: Into<T> {
+ fn into_bar(self) -> Bar<T> {
+ Bar {
+ items: Vec::new(),
+ inner: self.into(),
+ }
+ }
+}
+
+fn main() {}
--- /dev/null
+// check-pass
+
+pub struct Item {
+ _inner: &'static str,
+}
+
+pub struct Bar<T> {
+ items: Vec<Item>,
+ inner: T,
+}
+
+pub trait IntoBar<T> {
+ fn into_bar(self) -> Bar<T>;
+}
+
+impl<'a, T> IntoBar<T> for &'a str where &'a str: Into<T> {
+ fn into_bar(self) -> Bar<T> {
+ Bar {
+ items: Vec::new(),
+ inner: self.into(),
+ }
+ }
+}
+
+fn main() {}
+++ /dev/null
-// build-fail
-
-#![feature(lang_items, no_core)]
-#![no_core]
-
-#[lang="copy"] pub trait Copy { }
-#[lang="sized"] pub trait Sized { }
-
-// error-pattern:requires `start` lang_item
-
-fn main() {}
+++ /dev/null
-error: requires `start` lang_item
-
-error: aborting due to previous error
-
--- /dev/null
+// edition:2015
+
+mod inner {
+ fn global_inner(_: ::nonexistant::Foo) {
+ //~^ ERROR failed to resolve: maybe a missing crate `nonexistant`?
+ }
+ fn crate_inner(_: crate::nonexistant::Foo) {
+ //~^ ERROR failed to resolve: maybe a missing crate `nonexistant`?
+ }
+
+ fn bare_global(_: ::nonexistant) {
+ //~^ ERROR cannot find type `nonexistant` in the crate root
+ }
+ fn bare_crate(_: crate::nonexistant) {
+ //~^ ERROR cannot find type `nonexistant` in the crate root
+ }
+}
+
+fn main() {
+
+}
--- /dev/null
+error[E0433]: failed to resolve: maybe a missing crate `nonexistant`?
+ --> $DIR/editions-crate-root-2015.rs:4:26
+ |
+LL | fn global_inner(_: ::nonexistant::Foo) {
+ | ^^^^^^^^^^^ maybe a missing crate `nonexistant`?
+
+error[E0433]: failed to resolve: maybe a missing crate `nonexistant`?
+ --> $DIR/editions-crate-root-2015.rs:7:30
+ |
+LL | fn crate_inner(_: crate::nonexistant::Foo) {
+ | ^^^^^^^^^^^ maybe a missing crate `nonexistant`?
+
+error[E0412]: cannot find type `nonexistant` in the crate root
+ --> $DIR/editions-crate-root-2015.rs:11:25
+ |
+LL | fn bare_global(_: ::nonexistant) {
+ | ^^^^^^^^^^^ not found in the crate root
+
+error[E0412]: cannot find type `nonexistant` in the crate root
+ --> $DIR/editions-crate-root-2015.rs:14:29
+ |
+LL | fn bare_crate(_: crate::nonexistant) {
+ | ^^^^^^^^^^^ not found in the crate root
+
+error: aborting due to 4 previous errors
+
+Some errors have detailed explanations: E0412, E0433.
+For more information about an error, try `rustc --explain E0412`.
--- /dev/null
+trait Trait {
+ fn outer(&self) {
+ fn inner(_: &Self) {
+ //~^ ERROR can't use generic parameters from outer function
+ }
+ }
+}
+
+fn main() { }
--- /dev/null
+error[E0401]: can't use generic parameters from outer function
+ --> $DIR/issue-12796.rs:3:22
+ |
+LL | fn inner(_: &Self) {
+ | ^^^^
+ | |
+ | use of generic parameter from outer function
+ | can't use `Self` here
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0401`.
--- /dev/null
+static foo: i32 = 0;
+
+fn bar(foo: i32) {}
+//~^ ERROR function parameters cannot shadow statics
+//~| cannot be named the same as a static
+
+mod submod {
+ pub static answer: i32 = 42;
+}
+
+use self::submod::answer;
+
+fn question(answer: i32) {}
+//~^ ERROR function parameters cannot shadow statics
+//~| cannot be named the same as a static
+fn main() {
+}
--- /dev/null
+error[E0530]: function parameters cannot shadow statics
+ --> $DIR/issue-23716.rs:3:8
+ |
+LL | static foo: i32 = 0;
+ | -------------------- the static `foo` is defined here
+LL |
+LL | fn bar(foo: i32) {}
+ | ^^^ cannot be named the same as a static
+
+error[E0530]: function parameters cannot shadow statics
+ --> $DIR/issue-23716.rs:13:13
+ |
+LL | use self::submod::answer;
+ | -------------------- the static `answer` is imported here
+LL |
+LL | fn question(answer: i32) {}
+ | ^^^^^^ cannot be named the same as a static
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0530`.
--- /dev/null
+fn siphash<T>() {
+
+ trait U {
+ fn g(&self, x: T) -> T; //~ ERROR can't use generic parameters from outer function
+ //~^ ERROR can't use generic parameters from outer function
+ }
+}
+
+fn main() {}
--- /dev/null
+error[E0401]: can't use generic parameters from outer function
+ --> $DIR/issue-3021-c.rs:4:24
+ |
+LL | fn siphash<T>() {
+ | - type parameter from outer function
+...
+LL | fn g(&self, x: T) -> T;
+ | - ^ use of generic parameter from outer function
+ | |
+ | help: try using a local generic parameter instead: `g<T>`
+
+error[E0401]: can't use generic parameters from outer function
+ --> $DIR/issue-3021-c.rs:4:30
+ |
+LL | fn siphash<T>() {
+ | - type parameter from outer function
+...
+LL | fn g(&self, x: T) -> T;
+ | - ^ use of generic parameter from outer function
+ | |
+ | help: try using a local generic parameter instead: `g<T>`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0401`.
--- /dev/null
+trait SipHash {
+ fn reset(&self);
+}
+
+fn siphash(k0 : u64) {
+ struct SipState {
+ v0: u64,
+ }
+
+ impl SipHash for SipState {
+ fn reset(&self) {
+ self.v0 = k0 ^ 0x736f6d6570736575; //~ ERROR can't capture dynamic environment
+ }
+ }
+ panic!();
+}
+
+fn main() {}
--- /dev/null
+error[E0434]: can't capture dynamic environment in a fn item
+ --> $DIR/issue-3021.rs:12:22
+ |
+LL | self.v0 = k0 ^ 0x736f6d6570736575;
+ | ^^
+ |
+ = help: use the `|| { ... }` closure form instead
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0434`.
--- /dev/null
+// Checks lexical scopes cannot see through normal module boundaries
+
+fn f() {
+ fn g() {}
+ mod foo {
+ fn h() {
+ g(); //~ ERROR cannot find function `g` in this scope
+ }
+ }
+}
+
+fn main() {}
--- /dev/null
+error[E0425]: cannot find function `g` in this scope
+ --> $DIR/issue-31845.rs:7:12
+ |
+LL | g();
+ | ^ not found in this scope
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0425`.
--- /dev/null
+trait B <A> {
+ fn a() -> A {
+ this.a //~ ERROR cannot find value `this` in this scope
+ }
+ fn b(x: i32) {
+ this.b(x); //~ ERROR cannot find value `this` in this scope
+ }
+ fn c() {
+ let _ = || this.a; //~ ERROR cannot find value `this` in this scope
+ }
+}
+
+fn main() {}
--- /dev/null
+error[E0425]: cannot find value `this` in this scope
+ --> $DIR/issue-5099.rs:3:9
+ |
+LL | this.a
+ | ^^^^ not found in this scope
+ |
+help: you might have meant to use `self` here instead
+ |
+LL | self.a
+ | ~~~~
+help: if you meant to use `self`, you are also missing a `self` receiver argument
+ |
+LL | fn a(&self) -> A {
+ | +++++
+
+error[E0425]: cannot find value `this` in this scope
+ --> $DIR/issue-5099.rs:6:9
+ |
+LL | this.b(x);
+ | ^^^^ not found in this scope
+ |
+help: you might have meant to use `self` here instead
+ |
+LL | self.b(x);
+ | ~~~~
+help: if you meant to use `self`, you are also missing a `self` receiver argument
+ |
+LL | fn b(&self, x: i32) {
+ | ++++++
+
+error[E0425]: cannot find value `this` in this scope
+ --> $DIR/issue-5099.rs:9:20
+ |
+LL | let _ = || this.a;
+ | ^^^^ not found in this scope
+ |
+help: you might have meant to use `self` here instead
+ |
+LL | let _ = || self.a;
+ | ~~~~
+help: if you meant to use `self`, you are also missing a `self` receiver argument
+ |
+LL | fn c(&self) {
+ | +++++
+
+error: aborting due to 3 previous errors
+
+For more information about this error, try `rustc --explain E0425`.
--- /dev/null
+// Matching against NaN should result in a warning
+
+#![allow(unused)]
+#![deny(illegal_floating_point_literal_pattern)]
+
+const NAN: f64 = f64::NAN;
+
+fn main() {
+ let x = NAN;
+ match x {
+ NAN => {}, //~ ERROR floating-point types cannot be used
+ //~| WARN this was previously accepted by the compiler but is being phased out
+ _ => {},
+ };
+
+ match [x, 1.0] {
+ [NAN, _] => {}, //~ ERROR floating-point types cannot be used
+ //~| WARN this was previously accepted by the compiler but is being phased out
+ _ => {},
+ };
+}
--- /dev/null
+error: floating-point types cannot be used in patterns
+ --> $DIR/issue-6804.rs:11:9
+ |
+LL | NAN => {},
+ | ^^^
+ |
+note: the lint level is defined here
+ --> $DIR/issue-6804.rs:4:9
+ |
+LL | #![deny(illegal_floating_point_literal_pattern)]
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+ = note: for more information, see issue #41620 <https://github.com/rust-lang/rust/issues/41620>
+
+error: floating-point types cannot be used in patterns
+ --> $DIR/issue-6804.rs:17:10
+ |
+LL | [NAN, _] => {},
+ | ^^^
+ |
+ = warning: this was previously accepted by the compiler but is being phased out; it will become a hard error in a future release!
+ = note: for more information, see issue #41620 <https://github.com/rust-lang/rust/issues/41620>
+
+error: aborting due to 2 previous errors
+
--- /dev/null
+struct A<T>(T);
+
+impl A<&'static u8> {
+ fn f() {
+ let x = 0;
+ Self(&x);
+ //~^ ERROR `x` does not live long enough
+ }
+}
+
+fn main() {}
--- /dev/null
+error[E0597]: `x` does not live long enough
+ --> $DIR/issue-61882-2.rs:6:14
+ |
+LL | Self(&x);
+ | ^^
+ | |
+ | borrowed value does not live long enough
+ | this usage requires that `x` is borrowed for `'static`
+LL |
+LL | }
+ | - `x` dropped here while still borrowed
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0597`.
--- /dev/null
+struct A<T>(T);
+
+impl A<bool> {
+ const B: A<u8> = Self(0);
+ //~^ ERROR mismatched types
+ //~| ERROR mismatched types
+}
+
+fn main() {}
--- /dev/null
+error[E0308]: mismatched types
+ --> $DIR/issue-61882.rs:4:27
+ |
+LL | const B: A<u8> = Self(0);
+ | ^ expected `bool`, found integer
+
+error[E0308]: mismatched types
+ --> $DIR/issue-61882.rs:4:22
+ |
+LL | const B: A<u8> = Self(0);
+ | ^^^^^^^ expected `u8`, found `bool`
+ |
+ = note: expected struct `A<u8>`
+ found struct `A<bool>`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0308`.
+++ /dev/null
-// run-pass
-// ignore-emscripten no processes
-// ignore-sgx no processes
-// ignore-windows
-
-use std::env;
-use std::process::Command;
-
-pub fn main() {
- let args: Vec<String> = env::args().collect();
- if args.len() >= 2 && args[1] == "signal" {
- // Raise a segfault.
- unsafe { *(1 as *mut isize) = 0; }
- } else {
- let status = Command::new(&args[0]).arg("signal").status().unwrap();
- assert!(status.code().is_none());
- }
-}
--- /dev/null
+// run-pass
+
+#![feature(specialization)] //~ WARN the feature `specialization` is incomplete
+
+trait Specializable { type Output; }
+
+impl<T> Specializable for T {
+ default type Output = u16;
+}
+
+fn main() {
+ unsafe {
+ std::mem::transmute::<u16, <() as Specializable>::Output>(0);
+ }
+}
--- /dev/null
+warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes
+ --> $DIR/transmute-specialization.rs:3:12
+ |
+LL | #![feature(specialization)]
+ | ^^^^^^^^^^^^^^
+ |
+ = note: `#[warn(incomplete_features)]` on by default
+ = note: see issue #31844 <https://github.com/rust-lang/rust/issues/31844> for more information
+ = help: consider using `min_specialization` instead, which is more stable and complete
+
+warning: 1 warning emitted
+
--- /dev/null
+// original problem
+pub fn foo<T>() -> isize {
+ {
+ static foo: isize = 2;
+ foo
+ }
+}
+
+// issue 8134
+struct Foo;
+impl Foo {
+ pub fn foo<T>(&self) {
+ static X: usize = 1;
+ }
+}
+
+// issue 8134
+pub struct Parser<T>(T);
+impl<T: std::iter::Iterator<Item=char>> Parser<T> {
+ fn in_doctype(&mut self) {
+ static DOCTYPEPattern: [char; 6] = ['O', 'C', 'T', 'Y', 'P', 'E'];
+ }
+}
+
+struct Bar;
+impl Foo {
+ pub fn bar<T>(&self) {
+ static X: usize = 1;
+ }
+}
--- /dev/null
+// run-pass
+// aux-build:nested_item.rs
+
+
+extern crate nested_item;
+
+pub fn main() {
+ assert_eq!(2, nested_item::foo::<()>());
+ assert_eq!(2, nested_item::foo::<isize>());
+}
--- /dev/null
+error[E0133]: use of extern static is unsafe and requires unsafe function or block
+ --> $DIR/issue-14227.rs:7:21
+ |
+LL | static CRASH: u32 = symbol;
+ | ^^^^^^ use of extern static
+ |
+ = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0133`.
--- /dev/null
+// revisions: mir thir
+// [thir]compile-flags: -Z thir-unsafeck
+
+extern "C" {
+ pub static symbol: u32;
+}
+static CRASH: u32 = symbol;
+//~^ ERROR use of extern static is unsafe and requires
+
+fn main() {}
--- /dev/null
+error[E0133]: use of extern static is unsafe and requires unsafe function or block
+ --> $DIR/issue-14227.rs:7:21
+ |
+LL | static CRASH: u32 = symbol;
+ | ^^^^^^ use of extern static
+ |
+ = note: extern statics are not controlled by the Rust type system: invalid data, aliasing violations or data races will cause undefined behavior
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0133`.
--- /dev/null
+// run-pass
+enum Void {}
+fn foo(_: Result<(Void, u32), (Void, String)>) {}
+fn main() {
+ let _: fn(_) = foo;
+}
+++ /dev/null
-// run-pass
-
-#![allow(non_camel_case_types)]
-
-
-#[derive(Copy, Clone, Debug)]
-enum foo { large, small, }
-
-impl PartialEq for foo {
- fn eq(&self, other: &foo) -> bool {
- ((*self) as usize) == ((*other) as usize)
- }
- fn ne(&self, other: &foo) -> bool { !(*self).eq(other) }
-}
-
-pub fn main() {
- let a = (1, 2, 3);
- let b = (1, 2, 3);
- assert_eq!(a, b);
- assert!((a != (1, 2, 4)));
- assert!((a < (1, 2, 4)));
- assert!((a <= (1, 2, 4)));
- assert!(((1, 2, 4) > a));
- assert!(((1, 2, 4) >= a));
- let x = foo::large;
- let y = foo::small;
- assert!((x != y));
- assert_eq!(x, foo::large);
- assert!((x != foo::small));
-}
+++ /dev/null
-// run-pass
-
-pub fn main() {
- let f = 1_usize as *const String;
- println!("{:?}", f as isize);
- println!("{:?}", f as usize);
- println!("{:?}", f as i8);
- println!("{:?}", f as i16);
- println!("{:?}", f as i32);
- println!("{:?}", f as i64);
- println!("{:?}", f as u8);
- println!("{:?}", f as u16);
- println!("{:?}", f as u32);
- println!("{:?}", f as u64);
-
- println!("{:?}", 1 as isize);
- println!("{:?}", 1 as usize);
- println!("{:?}", 1 as *const String);
- println!("{:?}", 1 as i8);
- println!("{:?}", 1 as i16);
- println!("{:?}", 1 as i32);
- println!("{:?}", 1 as i64);
- println!("{:?}", 1 as u8);
- println!("{:?}", 1 as u16);
- println!("{:?}", 1 as u32);
- println!("{:?}", 1 as u64);
- println!("{:?}", 1 as f32);
- println!("{:?}", 1 as f64);
-
- println!("{:?}", 1_usize as isize);
- println!("{:?}", 1_usize as usize);
- println!("{:?}", 1_usize as *const String);
- println!("{:?}", 1_usize as i8);
- println!("{:?}", 1_usize as i16);
- println!("{:?}", 1_usize as i32);
- println!("{:?}", 1_usize as i64);
- println!("{:?}", 1_usize as u8);
- println!("{:?}", 1_usize as u16);
- println!("{:?}", 1_usize as u32);
- println!("{:?}", 1_usize as u64);
- println!("{:?}", 1_usize as f32);
- println!("{:?}", 1_usize as f64);
-
- println!("{:?}", 1i8 as isize);
- println!("{:?}", 1i8 as usize);
- println!("{:?}", 1i8 as *const String);
- println!("{:?}", 1i8 as i8);
- println!("{:?}", 1i8 as i16);
- println!("{:?}", 1i8 as i32);
- println!("{:?}", 1i8 as i64);
- println!("{:?}", 1i8 as u8);
- println!("{:?}", 1i8 as u16);
- println!("{:?}", 1i8 as u32);
- println!("{:?}", 1i8 as u64);
- println!("{:?}", 1i8 as f32);
- println!("{:?}", 1i8 as f64);
-
- println!("{:?}", 1u8 as isize);
- println!("{:?}", 1u8 as usize);
- println!("{:?}", 1u8 as *const String);
- println!("{:?}", 1u8 as i8);
- println!("{:?}", 1u8 as i16);
- println!("{:?}", 1u8 as i32);
- println!("{:?}", 1u8 as i64);
- println!("{:?}", 1u8 as u8);
- println!("{:?}", 1u8 as u16);
- println!("{:?}", 1u8 as u32);
- println!("{:?}", 1u8 as u64);
- println!("{:?}", 1u8 as f32);
- println!("{:?}", 1u8 as f64);
-
- println!("{:?}", 1i16 as isize);
- println!("{:?}", 1i16 as usize);
- println!("{:?}", 1i16 as *const String);
- println!("{:?}", 1i16 as i8);
- println!("{:?}", 1i16 as i16);
- println!("{:?}", 1i16 as i32);
- println!("{:?}", 1i16 as i64);
- println!("{:?}", 1i16 as u8);
- println!("{:?}", 1i16 as u16);
- println!("{:?}", 1i16 as u32);
- println!("{:?}", 1i16 as u64);
- println!("{:?}", 1i16 as f32);
- println!("{:?}", 1i16 as f64);
-
- println!("{:?}", 1u16 as isize);
- println!("{:?}", 1u16 as usize);
- println!("{:?}", 1u16 as *const String);
- println!("{:?}", 1u16 as i8);
- println!("{:?}", 1u16 as i16);
- println!("{:?}", 1u16 as i32);
- println!("{:?}", 1u16 as i64);
- println!("{:?}", 1u16 as u8);
- println!("{:?}", 1u16 as u16);
- println!("{:?}", 1u16 as u32);
- println!("{:?}", 1u16 as u64);
- println!("{:?}", 1u16 as f32);
- println!("{:?}", 1u16 as f64);
-
- println!("{:?}", 1i32 as isize);
- println!("{:?}", 1i32 as usize);
- println!("{:?}", 1i32 as *const String);
- println!("{:?}", 1i32 as i8);
- println!("{:?}", 1i32 as i16);
- println!("{:?}", 1i32 as i32);
- println!("{:?}", 1i32 as i64);
- println!("{:?}", 1i32 as u8);
- println!("{:?}", 1i32 as u16);
- println!("{:?}", 1i32 as u32);
- println!("{:?}", 1i32 as u64);
- println!("{:?}", 1i32 as f32);
- println!("{:?}", 1i32 as f64);
-
- println!("{:?}", 1u32 as isize);
- println!("{:?}", 1u32 as usize);
- println!("{:?}", 1u32 as *const String);
- println!("{:?}", 1u32 as i8);
- println!("{:?}", 1u32 as i16);
- println!("{:?}", 1u32 as i32);
- println!("{:?}", 1u32 as i64);
- println!("{:?}", 1u32 as u8);
- println!("{:?}", 1u32 as u16);
- println!("{:?}", 1u32 as u32);
- println!("{:?}", 1u32 as u64);
- println!("{:?}", 1u32 as f32);
- println!("{:?}", 1u32 as f64);
-
- println!("{:?}", 1i64 as isize);
- println!("{:?}", 1i64 as usize);
- println!("{:?}", 1i64 as *const String);
- println!("{:?}", 1i64 as i8);
- println!("{:?}", 1i64 as i16);
- println!("{:?}", 1i64 as i32);
- println!("{:?}", 1i64 as i64);
- println!("{:?}", 1i64 as u8);
- println!("{:?}", 1i64 as u16);
- println!("{:?}", 1i64 as u32);
- println!("{:?}", 1i64 as u64);
- println!("{:?}", 1i64 as f32);
- println!("{:?}", 1i64 as f64);
-
- println!("{:?}", 1u64 as isize);
- println!("{:?}", 1u64 as usize);
- println!("{:?}", 1u64 as *const String);
- println!("{:?}", 1u64 as i8);
- println!("{:?}", 1u64 as i16);
- println!("{:?}", 1u64 as i32);
- println!("{:?}", 1u64 as i64);
- println!("{:?}", 1u64 as u8);
- println!("{:?}", 1u64 as u16);
- println!("{:?}", 1u64 as u32);
- println!("{:?}", 1u64 as u64);
- println!("{:?}", 1u64 as f32);
- println!("{:?}", 1u64 as f64);
-
- println!("{:?}", 1u64 as isize);
- println!("{:?}", 1u64 as usize);
- println!("{:?}", 1u64 as *const String);
- println!("{:?}", 1u64 as i8);
- println!("{:?}", 1u64 as i16);
- println!("{:?}", 1u64 as i32);
- println!("{:?}", 1u64 as i64);
- println!("{:?}", 1u64 as u8);
- println!("{:?}", 1u64 as u16);
- println!("{:?}", 1u64 as u32);
- println!("{:?}", 1u64 as u64);
- println!("{:?}", 1u64 as f32);
- println!("{:?}", 1u64 as f64);
-
- println!("{:?}", true as isize);
- println!("{:?}", true as usize);
- println!("{:?}", true as i8);
- println!("{:?}", true as i16);
- println!("{:?}", true as i32);
- println!("{:?}", true as i64);
- println!("{:?}", true as u8);
- println!("{:?}", true as u16);
- println!("{:?}", true as u32);
- println!("{:?}", true as u64);
-
- println!("{:?}", 1f32 as isize);
- println!("{:?}", 1f32 as usize);
- println!("{:?}", 1f32 as i8);
- println!("{:?}", 1f32 as i16);
- println!("{:?}", 1f32 as i32);
- println!("{:?}", 1f32 as i64);
- println!("{:?}", 1f32 as u8);
- println!("{:?}", 1f32 as u16);
- println!("{:?}", 1f32 as u32);
- println!("{:?}", 1f32 as u64);
- println!("{:?}", 1f32 as f32);
- println!("{:?}", 1f32 as f64);
-
- println!("{:?}", 1f64 as isize);
- println!("{:?}", 1f64 as usize);
- println!("{:?}", 1f64 as i8);
- println!("{:?}", 1f64 as i16);
- println!("{:?}", 1f64 as i32);
- println!("{:?}", 1f64 as i64);
- println!("{:?}", 1f64 as u8);
- println!("{:?}", 1f64 as u16);
- println!("{:?}", 1f64 as u32);
- println!("{:?}", 1f64 as u64);
- println!("{:?}", 1f64 as f32);
- println!("{:?}", 1f64 as f64);
-}
--- /dev/null
+#![crate_name = "a"]
+
+pub fn foo<T>() {}
--- /dev/null
+#![crate_name = "a"]
+
+pub fn foo<T>() { println!("hello!"); }
--- /dev/null
+#![crate_name = "b"]
+
+extern crate a;
+
+pub fn foo() { a::foo::<isize>(); }
--- /dev/null
+// ignore-msvc FIXME #31306
+
+// note that these aux-build directives must be in this order
+// aux-build:changing-crates-a1.rs
+// aux-build:changing-crates-b.rs
+// aux-build:changing-crates-a2.rs
+// normalize-stderr-test: "(crate `(\w+)`:) .*" -> "$1 $$PATH_$2"
+
+extern crate a;
+extern crate b; //~ ERROR: found possibly newer version of crate `a` which `b` depends on
+
+fn main() {}
--- /dev/null
+error[E0460]: found possibly newer version of crate `a` which `b` depends on
+ --> $DIR/changing-crates.rs:10:1
+ |
+LL | extern crate b;
+ | ^^^^^^^^^^^^^^^
+ |
+ = note: perhaps that crate needs to be recompiled?
+ = note: the following crate versions were found:
+ crate `a`: $PATH_a
+ crate `b`: $PATH_b
+
+error: aborting due to previous error
+
+++ /dev/null
-#![feature(negative_impls)]
-
-use std::marker::Send;
-
-struct TestType;
-
-impl !TestType {}
-//~^ ERROR inherent impls cannot be negative
-
-trait TestTrait {}
-
-unsafe impl !Send for TestType {}
-//~^ ERROR negative impls cannot be unsafe
-impl !TestTrait for TestType {}
-
-struct TestType2<T>(T);
-
-impl<T> !TestType2<T> {}
-//~^ ERROR inherent impls cannot be negative
-
-unsafe impl<T> !Send for TestType2<T> {}
-//~^ ERROR negative impls cannot be unsafe
-impl<T> !TestTrait for TestType2<T> {}
-
-fn main() {}
+++ /dev/null
-error: inherent impls cannot be negative
- --> $DIR/syntax-trait-polarity.rs:7:7
- |
-LL | impl !TestType {}
- | -^^^^^^^^ inherent impl for this type
- | |
- | negative because of this
-
-error[E0198]: negative impls cannot be unsafe
- --> $DIR/syntax-trait-polarity.rs:12:13
- |
-LL | unsafe impl !Send for TestType {}
- | ------ -^^^^
- | | |
- | | negative because of this
- | unsafe because of this
-
-error: inherent impls cannot be negative
- --> $DIR/syntax-trait-polarity.rs:18:10
- |
-LL | impl<T> !TestType2<T> {}
- | -^^^^^^^^^^^^ inherent impl for this type
- | |
- | negative because of this
-
-error[E0198]: negative impls cannot be unsafe
- --> $DIR/syntax-trait-polarity.rs:21:16
- |
-LL | unsafe impl<T> !Send for TestType2<T> {}
- | ------ -^^^^
- | | |
- | | negative because of this
- | unsafe because of this
-
-error: aborting due to 4 previous errors
-
-For more information about this error, try `rustc --explain E0198`.
+++ /dev/null
-// run-pass
-// ignore-emscripten no threads support
-
-// Issue #787
-// Don't try to clean up uninitialized locals
-
-
-use std::thread;
-
-fn test_break() { loop { let _x: Box<isize> = break; } }
-
-fn test_cont() { let mut i = 0; while i < 1 { i += 1; let _x: Box<isize> = continue; } }
-
-fn test_ret() { let _x: Box<isize> = return; }
-
-fn test_panic() {
- fn f() { let _x: Box<isize> = panic!(); }
- thread::spawn(move|| f() ).join().unwrap_err();
-}
-
-fn test_panic_indirect() {
- fn f() -> ! { panic!(); }
- fn g() { let _x: Box<isize> = f(); }
- thread::spawn(move|| g() ).join().unwrap_err();
-}
-
-pub fn main() {
- test_break();
- test_cont();
- test_ret();
- test_panic();
- test_panic_indirect();
-}
--- /dev/null
+// run-pass
+// compile-flags: --test
+
+#[test]
+pub fn foo() {}
+++ /dev/null
-// run-pass
-// compile-flags: -Z thinlto -C codegen-units=2
-
-#[global_allocator]
-static A: std::alloc::System = std::alloc::System;
-
-fn main() {}
+++ /dev/null
-// run-pass
-
-// compile-flags: -Clto=thin
-// no-prefer-dynamic
-
-fn main() {
- println!("hello!");
-}
+++ /dev/null
-// compile-flags: -Z thinlto -C codegen-units=8
-
-#[inline]
-pub fn foo(b: u8) {
- b.to_string();
-}
+++ /dev/null
-// no-prefer-dynamic
-// compile-flags: -Z thinlto -C codegen-units=8 -C prefer-dynamic
-
-#![crate_type = "rlib"]
-#![crate_type = "dylib"]
-
-pub static A: u32 = 43;
-
-pub mod a {
- pub static A: u32 = 43;
-}
+++ /dev/null
-// no-prefer-dynamic
-
-#![crate_type = "rlib"]
-
-pub fn bar() -> u32 {
- 3
-}
+++ /dev/null
-// run-pass
-
-// aux-build:dylib.rs
-
-extern crate dylib;
-
-fn main() {
- dylib::foo(1);
-}
+++ /dev/null
-// run-pass
-
-// aux-build:msvc-imp-present.rs
-// compile-flags: -Z thinlto -C codegen-units=8
-// no-prefer-dynamic
-
-// On MSVC we have a "hack" where we emit symbols that look like `_imp_$name`
-// for all exported statics. This is done because we apply `dllimport` to all
-// imported constants and this allows everything to actually link correctly.
-//
-// The ThinLTO passes aggressively remove symbols if they can, and this test
-// asserts that the ThinLTO passes don't remove these compiler-generated
-// `_imp_*` symbols. The external library that we link in here is compiled with
-// ThinLTO and multiple codegen units and has a few exported constants. Note
-// that we also namely compile the library as both a dylib and an rlib, but we
-// link the rlib to ensure that we assert those generated symbols exist.
-
-extern crate msvc_imp_present as bar;
-
-fn main() {
- println!("{}", bar::A);
-}
+++ /dev/null
-// run-pass
-
-// compile-flags: -Z thinlto -C codegen-units=8 -O
-// ignore-emscripten can't inspect instructions on emscripten
-
-// We want to assert here that ThinLTO will inline across codegen units. There's
-// not really a great way to do that in general so we sort of hack around it by
-// praying two functions go into separate codegen units and then assuming that
-// if inlining *doesn't* happen the first byte of the functions will differ.
-
-pub fn foo() -> u32 {
- bar::bar()
-}
-
-mod bar {
- pub fn bar() -> u32 {
- 3
- }
-}
-
-fn main() {
- println!("{} {}", foo(), bar::bar());
-
- unsafe {
- let foo = foo as usize as *const u8;
- let bar = bar::bar as usize as *const u8;
-
- assert_eq!(*foo, *bar);
- }
-}
+++ /dev/null
-// run-pass
-
-// compile-flags: -C codegen-units=8 -O -C lto=thin
-// aux-build:thin-lto-inlines-aux.rs
-// no-prefer-dynamic
-// ignore-emscripten can't inspect instructions on emscripten
-
-// We want to assert here that ThinLTO will inline across codegen units. There's
-// not really a great way to do that in general so we sort of hack around it by
-// praying two functions go into separate codegen units and then assuming that
-// if inlining *doesn't* happen the first byte of the functions will differ.
-
-extern crate thin_lto_inlines_aux as bar;
-
-pub fn foo() -> u32 {
- bar::bar()
-}
-
-fn main() {
- println!("{} {}", foo(), bar::bar());
-
- unsafe {
- let foo = foo as usize as *const u8;
- let bar = bar::bar as usize as *const u8;
-
- assert_eq!(*foo, *bar);
- }
-}
+++ /dev/null
-// run-pass
-
-// compile-flags: -C codegen-units=8 -Z thinlto
-// ignore-windows
-
-#![feature(linkage)]
-
-pub mod foo {
- #[linkage = "weak"]
- #[no_mangle]
- pub extern "C" fn FOO() -> i32 {
- 0
- }
-}
-
-mod bar {
- extern "C" {
- fn FOO() -> i32;
- }
-
- pub fn bar() -> i32 {
- unsafe { FOO() }
- }
-}
-
-fn main() {
- bar::bar();
-}
--- /dev/null
+// run-pass
+// ignore-emscripten no threads
+// ignore-sgx no processes
+
+use std::thread;
+use std::env;
+use std::process::Command;
+
+struct Handle(i32);
+
+impl Drop for Handle {
+ fn drop(&mut self) { panic!(); }
+}
+
+thread_local!(static HANDLE: Handle = Handle(0));
+
+fn main() {
+ let args = env::args().collect::<Vec<_>>();
+ if args.len() == 1 {
+ let out = Command::new(&args[0]).arg("test").output().unwrap();
+ let stderr = std::str::from_utf8(&out.stderr).unwrap();
+ assert!(stderr.contains("panicked at 'explicit panic'"),
+ "bad failure message:\n{}\n", stderr);
+ } else {
+ // TLS dtors are not always run on process exit
+ thread::spawn(|| {
+ HANDLE.with(|h| {
+ println!("{}", h.0);
+ });
+ }).join().unwrap();
+ }
+}
--- /dev/null
+// run-pass
+// ignore-emscripten no threads support
+
+use std::sync::mpsc::channel;
+use std::thread;
+
+pub fn main() {
+ let (tx, rx) = channel::<&'static str>();
+
+ let t = thread::spawn(move|| {
+ assert_eq!(rx.recv().unwrap(), "hello, world");
+ });
+
+ tx.send("hello, world").unwrap();
+ t.join().ok().unwrap();
+}
--- /dev/null
+// run-pass
+// ignore-emscripten no threads support
+
+use std::thread;
+use std::sync::mpsc::{channel, Receiver};
+
+fn periodical(n: isize) -> Receiver<bool> {
+ let (chan, port) = channel();
+ thread::spawn(move|| {
+ loop {
+ for _ in 1..n {
+ match chan.send(false) {
+ Ok(()) => {}
+ Err(..) => break,
+ }
+ }
+ match chan.send(true) {
+ Ok(()) => {}
+ Err(..) => break
+ }
+ }
+ });
+ return port;
+}
+
+fn integers() -> Receiver<isize> {
+ let (chan, port) = channel();
+ thread::spawn(move|| {
+ let mut i = 1;
+ loop {
+ match chan.send(i) {
+ Ok(()) => {}
+ Err(..) => break,
+ }
+ i = i + 1;
+ }
+ });
+ return port;
+}
+
+fn main() {
+ let ints = integers();
+ let threes = periodical(3);
+ let fives = periodical(5);
+ for _ in 1..100 {
+ match (ints.recv().unwrap(), threes.recv().unwrap(), fives.recv().unwrap()) {
+ (_, true, true) => println!("FizzBuzz"),
+ (_, true, false) => println!("Fizz"),
+ (_, false, true) => println!("Buzz"),
+ (i, false, false) => println!("{}", i)
+ }
+ }
+}
--- /dev/null
+// run-pass
+#![allow(unused_must_use)]
+#![allow(deprecated)]
+// ignore-emscripten no threads support
+
+use std::sync::mpsc::{TryRecvError, channel};
+use std::thread;
+
+pub fn main() {
+ let (tx, rx) = channel();
+ let t = thread::spawn(move||{
+ thread::sleep_ms(10);
+ tx.send(()).unwrap();
+ });
+ loop {
+ match rx.try_recv() {
+ Ok(()) => break,
+ Err(TryRecvError::Empty) => {}
+ Err(TryRecvError::Disconnected) => unreachable!()
+ }
+ }
+ t.join();
+}
--- /dev/null
+// run-pass
+
+#![allow(unused_must_use)]
+/*
+ This is about the simplest program that can successfully send a
+ message.
+ */
+
+use std::sync::mpsc::channel;
+
+pub fn main() {
+ let (tx, rx) = channel();
+ tx.send(42);
+ let r = rx.recv();
+ println!("{:?}", r);
+}
--- /dev/null
+// run-pass
+
+use std::thread;
+
+pub fn main() {
+ let mut i: isize = 0;
+ while i < 100 { i = i + 1; println!("{}", i); thread::yield_now(); }
+}
+++ /dev/null
-#![feature(trace_macros)]
-
-fn main() {
- trace_macros!(); //~ ERROR trace_macros! accepts only `true` or `false`
- trace_macros!(1); //~ ERROR trace_macros! accepts only `true` or `false`
- trace_macros!(ident); //~ ERROR trace_macros! accepts only `true` or `false`
- trace_macros!(for); //~ ERROR trace_macros! accepts only `true` or `false`
- trace_macros!(true,); //~ ERROR trace_macros! accepts only `true` or `false`
- trace_macros!(false 1); //~ ERROR trace_macros! accepts only `true` or `false`
-
-
- // should be fine:
- macro_rules! expando {
- ($x: ident) => { trace_macros!($x) }
- }
-
- expando!(true);
-}
+++ /dev/null
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:4:5
- |
-LL | trace_macros!();
- | ^^^^^^^^^^^^^^^
-
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:5:5
- |
-LL | trace_macros!(1);
- | ^^^^^^^^^^^^^^^^
-
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:6:5
- |
-LL | trace_macros!(ident);
- | ^^^^^^^^^^^^^^^^^^^^
-
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:7:5
- |
-LL | trace_macros!(for);
- | ^^^^^^^^^^^^^^^^^^
-
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:8:5
- |
-LL | trace_macros!(true,);
- | ^^^^^^^^^^^^^^^^^^^^
-
-error: trace_macros! accepts only `true` or `false`
- --> $DIR/trace_macros-format.rs:9:5
- |
-LL | trace_macros!(false 1);
- | ^^^^^^^^^^^^^^^^^^^^^^
-
-error: aborting due to 6 previous errors
-
--- /dev/null
+// run-pass
+
+trait Foo: Fn(i32) -> i32 + Send {}
+
+impl<T: ?Sized + Fn(i32) -> i32 + Send> Foo for T {}
+
+fn wants_foo(f: Box<dyn Foo>) -> i32 {
+ f(42)
+}
+
+fn main() {
+ let f = Box::new(|x| x);
+ assert_eq!(wants_foo(f), 42);
+}
--- /dev/null
+trait Q<T:?Sized> {}
+trait Foo where u32: Q<Self> {
+ fn foo(&self);
+}
+
+impl Q<()> for u32 {}
+impl Foo for () {
+ fn foo(&self) {
+ println!("foo!");
+ }
+}
+
+fn main() {
+ let _f: Box<dyn Foo> = //~ ERROR `Foo` cannot be made into an object
+ Box::new(()); //~ ERROR `Foo` cannot be made into an object
+}
--- /dev/null
+error[E0038]: the trait `Foo` cannot be made into an object
+ --> $DIR/issue-38604.rs:14:13
+ |
+LL | let _f: Box<dyn Foo> =
+ | ^^^^^^^^^^^^ `Foo` cannot be made into an object
+ |
+note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
+ --> $DIR/issue-38604.rs:2:22
+ |
+LL | trait Foo where u32: Q<Self> {
+ | --- ^^^^^^^ ...because it uses `Self` as a type parameter
+ | |
+ | this trait cannot be made into an object...
+
+error[E0038]: the trait `Foo` cannot be made into an object
+ --> $DIR/issue-38604.rs:15:9
+ |
+LL | Box::new(());
+ | ^^^^^^^^^^^^ `Foo` cannot be made into an object
+ |
+note: for a trait to be "object safe" it needs to allow building a vtable to allow the call to be resolvable dynamically; for more information visit <https://doc.rust-lang.org/reference/items/traits.html#object-safety>
+ --> $DIR/issue-38604.rs:2:22
+ |
+LL | trait Foo where u32: Q<Self> {
+ | --- ^^^^^^^ ...because it uses `Self` as a type parameter
+ | |
+ | this trait cannot be made into an object...
+ = note: required because of the requirements on the impl of `CoerceUnsized<Box<dyn Foo>>` for `Box<()>`
+ = note: required by cast to type `Box<dyn Foo>`
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0038`.
--- /dev/null
+struct Point {
+ x: f64,
+ y: f64,
+}
+
+trait ToString_ {
+ fn to_string(&self) -> String;
+}
+
+impl ToString_ for Point {
+ fn new(x: f64, y: f64) -> Point {
+ //~^ ERROR method `new` is not a member of trait `ToString_`
+ Point { x: x, y: y }
+ }
+
+ fn to_string(&self) -> String {
+ format!("({}, {})", self.x, self.y)
+ }
+}
+
+fn main() {
+ let p = Point::new(0.0, 0.0);
+ //~^ ERROR no function or associated item named `new` found for struct `Point`
+ println!("{}", p.to_string());
+}
--- /dev/null
+error[E0407]: method `new` is not a member of trait `ToString_`
+ --> $DIR/issue-3973.rs:11:5
+ |
+LL | / fn new(x: f64, y: f64) -> Point {
+LL | |
+LL | | Point { x: x, y: y }
+LL | | }
+ | |_____^ not a member of trait `ToString_`
+
+error[E0599]: no function or associated item named `new` found for struct `Point` in the current scope
+ --> $DIR/issue-3973.rs:22:20
+ |
+LL | struct Point {
+ | ------------ function or associated item `new` not found for this
+...
+LL | let p = Point::new(0.0, 0.0);
+ | ^^^ function or associated item not found in `Point`
+
+error: aborting due to 2 previous errors
+
+Some errors have detailed explanations: E0407, E0599.
+For more information about an error, try `rustc --explain E0407`.
--- /dev/null
+#![feature(trait_alias)]
+
+trait Svc<Req> { type Res; }
+
+trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
+//~^ ERROR associated type `Res` not found for `Self`
+//~| ERROR associated type `Res` not found for `Self`
+
+fn main() {}
--- /dev/null
+error[E0220]: associated type `Res` not found for `Self`
+ --> $DIR/issue-59029-1.rs:5:52
+ |
+LL | trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
+ | ^^^ associated type `Res` not found
+
+error[E0220]: associated type `Res` not found for `Self`
+ --> $DIR/issue-59029-1.rs:5:52
+ |
+LL | trait MkSvc<Target, Req> = Svc<Target> where Self::Res: Svc<Req>;
+ | ^^^ associated type `Res` not found
+
+error: aborting due to 2 previous errors
+
+For more information about this error, try `rustc --explain E0220`.
--- /dev/null
+// check-pass
+
+pub trait ResultExt {
+ type Ok;
+ fn err_eprint_and_ignore(self) -> Option<Self::Ok>;
+}
+
+impl<O, E> ResultExt for std::result::Result<O, E>
+where
+ E: std::error::Error,
+{
+ type Ok = O;
+ fn err_eprint_and_ignore(self) -> Option<O>
+ where
+ Self: ,
+ {
+ match self {
+ Err(e) => {
+ eprintln!("{}", e);
+ None
+ }
+ Ok(o) => Some(o),
+ }
+ }
+}
+
+fn main() {}
--- /dev/null
+// Test that an object type `Box<Foo>` is not considered to implement the
+// trait `Foo`. Issue #5087.
+
+trait Foo {}
+fn take_foo<F:Foo>(f: F) {}
+fn take_object(f: Box<dyn Foo>) { take_foo(f); }
+//~^ ERROR `Box<dyn Foo>: Foo` is not satisfied
+fn main() {}
--- /dev/null
+error[E0277]: the trait bound `Box<dyn Foo>: Foo` is not satisfied
+ --> $DIR/object-does-not-impl-trait.rs:6:44
+ |
+LL | fn take_object(f: Box<dyn Foo>) { take_foo(f); }
+ | -------- ^ the trait `Foo` is not implemented for `Box<dyn Foo>`
+ | |
+ | required by a bound introduced by this call
+ |
+note: required by a bound in `take_foo`
+ --> $DIR/object-does-not-impl-trait.rs:5:15
+ |
+LL | fn take_foo<F:Foo>(f: F) {}
+ | ^^^ required by this bound in `take_foo`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0277`.
--- /dev/null
+#![feature(negative_impls)]
+
+use std::marker::Send;
+
+struct TestType;
+
+impl !TestType {}
+//~^ ERROR inherent impls cannot be negative
+
+trait TestTrait {}
+
+unsafe impl !Send for TestType {}
+//~^ ERROR negative impls cannot be unsafe
+impl !TestTrait for TestType {}
+
+struct TestType2<T>(T);
+
+impl<T> !TestType2<T> {}
+//~^ ERROR inherent impls cannot be negative
+
+unsafe impl<T> !Send for TestType2<T> {}
+//~^ ERROR negative impls cannot be unsafe
+impl<T> !TestTrait for TestType2<T> {}
+
+fn main() {}
--- /dev/null
+error: inherent impls cannot be negative
+ --> $DIR/syntax-trait-polarity.rs:7:7
+ |
+LL | impl !TestType {}
+ | -^^^^^^^^ inherent impl for this type
+ | |
+ | negative because of this
+
+error[E0198]: negative impls cannot be unsafe
+ --> $DIR/syntax-trait-polarity.rs:12:13
+ |
+LL | unsafe impl !Send for TestType {}
+ | ------ -^^^^
+ | | |
+ | | negative because of this
+ | unsafe because of this
+
+error: inherent impls cannot be negative
+ --> $DIR/syntax-trait-polarity.rs:18:10
+ |
+LL | impl<T> !TestType2<T> {}
+ | -^^^^^^^^^^^^ inherent impl for this type
+ | |
+ | negative because of this
+
+error[E0198]: negative impls cannot be unsafe
+ --> $DIR/syntax-trait-polarity.rs:21:16
+ |
+LL | unsafe impl<T> !Send for TestType2<T> {}
+ | ------ -^^^^
+ | | |
+ | | negative because of this
+ | unsafe because of this
+
+error: aborting due to 4 previous errors
+
+For more information about this error, try `rustc --explain E0198`.
+++ /dev/null
-// run-pass
-
-#![feature(specialization)] //~ WARN the feature `specialization` is incomplete
-
-trait Specializable { type Output; }
-
-impl<T> Specializable for T {
- default type Output = u16;
-}
-
-fn main() {
- unsafe {
- std::mem::transmute::<u16, <() as Specializable>::Output>(0);
- }
-}
+++ /dev/null
-warning: the feature `specialization` is incomplete and may not be safe to use and/or cause compiler crashes
- --> $DIR/transmute-specialization.rs:3:12
- |
-LL | #![feature(specialization)]
- | ^^^^^^^^^^^^^^
- |
- = note: `#[warn(incomplete_features)]` on by default
- = note: see issue #31844 <https://github.com/rust-lang/rust/issues/31844> for more information
- = help: consider using `min_specialization` instead, which is more stable and complete
-
-warning: 1 warning emitted
-
+++ /dev/null
-// run-pass
-
-#![allow(unused_must_use)]
-/*
- This is about the simplest program that can successfully send a
- message.
- */
-
-use std::sync::mpsc::channel;
-
-pub fn main() {
- let (tx, rx) = channel();
- tx.send(42);
- let r = rx.recv();
- println!("{:?}", r);
-}
--- /dev/null
+// run-pass
+#![allow(unreachable_code)]
+// compile-flags: --edition 2018
+
+#![feature(try_blocks)]
+
+fn main() {
+ let mut a = 0;
+ let () = {
+ let _: Result<(), ()> = try {
+ let _ = Err(())?;
+ return
+ };
+ a += 1;
+ };
+ a += 2;
+ assert_eq!(a, 3);
+}
+++ /dev/null
-// compile-flags: --edition 2018
-fn foo() -> Result<(), ()> {
- Ok(try!()); //~ ERROR use of deprecated `try` macro
- Ok(try!(Ok(()))) //~ ERROR use of deprecated `try` macro
-}
-
-fn main() {
- let _ = foo();
-}
+++ /dev/null
-error: use of deprecated `try` macro
- --> $DIR/try-macro-suggestion.rs:3:8
- |
-LL | Ok(try!());
- | ^^^^^^
- |
- = note: in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated
-help: you can still access the deprecated `try!()` macro using the "raw identifier" syntax
- |
-LL | Ok(r#try!());
- | ++
-
-error: use of deprecated `try` macro
- --> $DIR/try-macro-suggestion.rs:4:8
- |
-LL | Ok(try!(Ok(())))
- | ^^^^^^^^^^^^
- |
- = note: in the 2018 edition `try` is a reserved keyword, and the `try!()` macro is deprecated
-help: you can use the `?` operator instead
- |
-LL - Ok(try!(Ok(())))
-LL + Ok(Ok(())?)
- |
-help: alternatively, you can still access the deprecated `try!()` macro using the "raw identifier" syntax
- |
-LL | Ok(r#try!(Ok(())))
- | ++
-
-error: aborting due to 2 previous errors
-
--- /dev/null
+// check-pass
+// compile-flags: -Z unpretty=hir
+
+#![feature(type_alias_impl_trait)]
+
+trait Animal {}
+
+fn main() {
+ pub type ServeFut = impl Animal;
+}
--- /dev/null
+// check-pass
+// compile-flags: -Z unpretty=hir
+
+#![feature(type_alias_impl_trait)]
+#[prelude_import]
+use ::std::prelude::rust_2015::*;
+#[macro_use]
+extern crate std;
+
+trait Animal { }
+
+fn main() {
+ pub type ServeFut = /*impl Trait*/;
+ }
--- /dev/null
+// Regression test for #30225, which was an ICE that would trigger as
+// a result of a poor interaction between trait result caching and
+// type inference. Specifically, at that time, unification could cause
+// unrelated type variables to become instantiated, if subtyping
+// relationships existed. These relationships are now propagated
+// through obligations and hence everything works out fine.
+
+trait Foo<U,V> : Sized {
+ fn foo(self, u: Option<U>, v: Option<V>) {}
+}
+
+struct A;
+struct B;
+
+impl Foo<A, B> for () {} // impl A
+impl Foo<u32, u32> for u32 {} // impl B, creating ambiguity
+
+fn toxic() {
+ // cache the resolution <() as Foo<$0,$1>> = impl A
+ let u = None;
+ let v = None;
+ Foo::foo((), u, v);
+}
+
+fn bomb() {
+ let mut u = None; // type is Option<$0>
+ let mut v = None; // type is Option<$1>
+ let mut x = None; // type is Option<$2>
+
+ Foo::foo(x.unwrap(),u,v); // register <$2 as Foo<$0, $1>>
+ u = v; // mark $0 and $1 in a subtype relationship
+ //~^ ERROR mismatched types
+ x = Some(()); // set $2 = (), allowing impl selection
+ // to proceed for <() as Foo<$0, $1>> = impl A.
+ // kaboom, this *used* to trigge an ICE
+}
+
+fn main() {}
--- /dev/null
+error[E0308]: mismatched types
+ --> $DIR/issue-30225.rs:31:9
+ |
+LL | u = v; // mark $0 and $1 in a subtype relationship
+ | ^ expected struct `A`, found struct `B`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0308`.
--- /dev/null
+#![crate_type="lib"]
+
+
+pub trait A {
+ fn a(&self) {}
+}
+impl A for () {}
--- /dev/null
+#![crate_type="lib"]
+
+pub extern crate xcrate_issue_43189_a;
--- /dev/null
+#![crate_type="lib"]
+
+pub extern crate core;
--- /dev/null
+// edition:2018
+#![crate_type="lib"]
+#![crate_name="xcrate_issue_61711_b"]
+pub struct Struct;
+pub use crate as alias;
--- /dev/null
+// Issue 46112: An extern crate pub re-exporting libcore was causing
+// paths rooted from `std` to be misrendered in the diagnostic output.
+
+// ignore-windows
+// aux-build:xcrate-issue-43189-a.rs
+// aux-build:xcrate-issue-43189-b.rs
+
+extern crate xcrate_issue_43189_b;
+fn main() {
+ ().a();
+ //~^ ERROR no method named `a` found
+}
--- /dev/null
+error[E0599]: no method named `a` found for unit type `()` in the current scope
+ --> $DIR/issue-43189.rs:10:8
+ |
+LL | ().a();
+ | ^ method not found in `()`
+ |
+ ::: $DIR/auxiliary/xcrate-issue-43189-a.rs:5:8
+ |
+LL | fn a(&self) {}
+ | - the method is available for `()` here
+ |
+ = help: items from traits can only be used if the trait is in scope
+help: the following trait is implemented but not in scope; perhaps add a `use` for it:
+ |
+LL | use xcrate_issue_43189_b::xcrate_issue_43189_a::A;
+ |
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0599`.
--- /dev/null
+// Issue 46112: An extern crate pub re-exporting libcore was causing
+// paths rooted from `std` to be misrendered in the diagnostic output.
+
+// ignore-windows
+// aux-build:xcrate-issue-46112-rexport-core.rs
+
+extern crate xcrate_issue_46112_rexport_core;
+fn test(r: Result<Option<()>, &'static str>) { }
+fn main() { test(Ok(())); }
+//~^ mismatched types
--- /dev/null
+error[E0308]: mismatched types
+ --> $DIR/issue-46112.rs:9:21
+ |
+LL | fn main() { test(Ok(())); }
+ | ^^
+ | |
+ | expected enum `Option`, found `()`
+ | help: try using a variant of the expected enum: `Some(())`
+ |
+ = note: expected enum `Option<()>`
+ found unit type `()`
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0308`.
--- /dev/null
+// Issue 61711: A crate pub re-exporting `crate` was causing an
+// infinite loop.
+
+// edition:2018
+// aux-build:xcrate-issue-61711-b.rs
+// compile-flags:--extern xcrate_issue_61711_b
+
+// build-pass
+
+fn f<F: Fn(xcrate_issue_61711_b::Struct)>(_: F) { }
+fn main() { }
+++ /dev/null
-// run-pass
-
-pub fn main() {
- let a = 1;
- let a_neg: i8 = -a;
- println!("{}", a_neg);
-
- let b = 1;
- let b_neg: i16 = -b;
- println!("{}", b_neg);
-
- let c = 1;
- let c_neg: i32 = -c;
- println!("{}", c_neg);
-
- let d = 1;
- let d_neg: i64 = -d;
- println!("{}", d_neg);
-
- let e = 1;
- let e_neg: isize = -e;
- println!("{}", e_neg);
-}
--- /dev/null
+// run-pass
+// Tests multiple free variables being passed by value into an unboxed
+// once closure as an optimization by codegen. This used to hit an
+// incorrect assert.
+
+fn main() {
+ let x = 2u8;
+ let y = 3u8;
+ assert_eq!((move || x + y)(), 5);
+}
+++ /dev/null
-// edition:2018
-
-#![deny(unused_extern_crates)]
-#![feature(test, rustc_private, crate_visibility_modifier)]
-
-extern crate libc;
-//~^ ERROR unused extern crate
-//~| HELP remove
-extern crate libc as x;
-//~^ ERROR unused extern crate
-//~| HELP remove
-
-extern crate proc_macro;
-
-#[macro_use]
-extern crate test;
-
-pub extern crate test as y;
-
-pub extern crate alloc;
-
-pub(crate) extern crate alloc as a;
-
-crate extern crate alloc as b;
-
-mod foo {
- pub(in crate::foo) extern crate alloc as c;
-
- pub(super) extern crate alloc as d;
-
- extern crate libc;
- //~^ ERROR unused extern crate
- //~| HELP remove
-
- extern crate libc as x;
- //~^ ERROR unused extern crate
- //~| HELP remove
-
- pub extern crate test;
-
- pub extern crate test as y;
-
- mod bar {
- extern crate libc;
- //~^ ERROR unused extern crate
- //~| HELP remove
-
- extern crate libc as x;
- //~^ ERROR unused extern crate
- //~| HELP remove
-
- pub(in crate::foo::bar) extern crate alloc as e;
-
- fn dummy() {
- e::string::String::new();
- }
- }
-
- fn dummy() {
- c::string::String::new();
- d::string::String::new();
- }
-}
-
-
-fn main() {
- a::string::String::new();
- b::string::String::new();
-
- proc_macro::TokenStream::new();
-}
+++ /dev/null
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:6:1
- |
-LL | extern crate libc;
- | ^^^^^^^^^^^^^^^^^^ help: remove it
- |
-note: the lint level is defined here
- --> $DIR/unnecessary-extern-crate.rs:3:9
- |
-LL | #![deny(unused_extern_crates)]
- | ^^^^^^^^^^^^^^^^^^^^
-
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:9:1
- |
-LL | extern crate libc as x;
- | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
-
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:31:5
- |
-LL | extern crate libc;
- | ^^^^^^^^^^^^^^^^^^ help: remove it
-
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:35:5
- |
-LL | extern crate libc as x;
- | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
-
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:44:9
- |
-LL | extern crate libc;
- | ^^^^^^^^^^^^^^^^^^ help: remove it
-
-error: unused extern crate
- --> $DIR/unnecessary-extern-crate.rs:48:9
- |
-LL | extern crate libc as x;
- | ^^^^^^^^^^^^^^^^^^^^^^^ help: remove it
-
-error: aborting due to 6 previous errors
-
+++ /dev/null
-// build-pass (FIXME(62277): could be check-pass?)
-
-#![feature(rustc_attrs)]
-
-#[rustc_dummy(a b c d)]
-#[rustc_dummy[a b c d]]
-#[rustc_dummy{a b c d}]
-fn main() {}
--- /dev/null
+pub struct X([u8]);
+
+pub static Y: &'static X = {
+ const Y: &'static [u8] = b"";
+ &X(*Y)
+ //~^ ERROR E0277
+};
+
+fn main() {}
--- /dev/null
+error[E0277]: the size for values of type `[u8]` cannot be known at compilation time
+ --> $DIR/issue-30355.rs:5:8
+ |
+LL | &X(*Y)
+ | ^^ doesn't have a size known at compile-time
+ |
+ = help: the trait `Sized` is not implemented for `[u8]`
+ = note: all function arguments must have a statically known size
+ = help: unsized fn params are gated as an unstable feature
+
+error: aborting due to previous error
+
+For more information about this error, try `rustc --explain E0277`.
+++ /dev/null
-// run-pass
-
-#![allow(dead_code)]
-// compile-flags:-D improper-ctypes
-
-// pretty-expanded FIXME #23616
-#![allow(improper_ctypes)]
-
-mod libc {
- extern "C" {
- pub fn malloc(size: isize) -> *const u8;
- }
-}
-
-pub fn main() {}
+++ /dev/null
-// run-pass
-
-use std::thread;
-
-pub fn main() {
- let mut i: isize = 0;
- while i < 100 { i = i + 1; println!("{}", i); thread::yield_now(); }
-}
use clippy_utils::{is_entrypoint_fn, is_expn_of, match_panic_def_id, method_chain_args, return_ty};
use if_chain::if_chain;
use itertools::Itertools;
-use rustc_ast::ast::{Async, AttrKind, Attribute, FnKind, FnRetTy, ItemKind};
+use rustc_ast::ast::{Async, AttrKind, Attribute, Fn, FnRetTy, ItemKind};
use rustc_ast::token::CommentKind;
use rustc_data_structures::fx::FxHashSet;
use rustc_data_structures::sync::Lrc;
| ItemKind::ExternCrate(..)
| ItemKind::ForeignMod(..) => return false,
// We found a main function ...
- ItemKind::Fn(box FnKind(_, sig, _, Some(block))) if item.ident.name == sym::main => {
+ ItemKind::Fn(box Fn { sig, body: Some(block), .. }) if item.ident.name == sym::main => {
let is_async = matches!(sig.header.asyncness, Async::Yes { .. });
let returns_nothing = match &sig.decl.output {
FnRetTy::Default(..) => true,
use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::in_macro;
-use rustc_ast::ast::{AssocItemKind, Extern, FnKind, FnSig, ImplKind, Item, ItemKind, TraitKind, Ty, TyKind};
+use rustc_ast::ast::{AssocItemKind, Extern, Fn, FnSig, Impl, Item, ItemKind, Trait, Ty, TyKind};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::{sym, Span};
);
}
},
- ItemKind::Impl(box ImplKind {
+ ItemKind::Impl(box Impl {
of_trait: None, items, ..
})
- | ItemKind::Trait(box TraitKind(.., items)) => {
+ | ItemKind::Trait(box Trait { items, .. }) => {
for item in items {
- if let AssocItemKind::Fn(box FnKind(_, fn_sig, _, _)) = &item.kind {
- self.check_fn_sig(cx, fn_sig, item.span);
+ if let AssocItemKind::Fn(box Fn { sig, .. }) = &item.kind {
+ self.check_fn_sig(cx, sig, item.span);
}
}
},
- ItemKind::Fn(box FnKind(_, fn_sig, _, _)) => self.check_fn_sig(cx, fn_sig, item.span),
+ ItemKind::Fn(box Fn { sig, .. }) => self.check_fn_sig(cx, sig, item.span),
_ => (),
}
}
use clippy_utils::diagnostics::{span_lint, span_lint_and_then};
use rustc_ast::ast::{
- Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, FnKind, Item, ItemKind, Local, Pat, PatKind,
+ self, Arm, AssocItem, AssocItemKind, Attribute, Block, FnDecl, Item, ItemKind, Local, Pat, PatKind,
};
use rustc_ast::visit::{walk_block, walk_expr, walk_pat, Visitor};
use rustc_lint::{EarlyContext, EarlyLintPass};
return;
}
- if let ItemKind::Fn(box FnKind(_, ref sig, _, Some(ref blk))) = item.kind {
+ if let ItemKind::Fn(box ast::Fn { ref sig, body: Some(ref blk), .. }) = item.kind {
do_check(self, cx, &item.attrs, &sig.decl, blk);
}
}
return;
}
- if let AssocItemKind::Fn(box FnKind(_, ref sig, _, Some(ref blk))) = item.kind {
+ if let AssocItemKind::Fn(box ast::Fn { ref sig, body: Some(ref blk), .. }) = item.kind {
do_check(self, cx, &item.attrs, &sig.decl, blk);
}
}
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::{snippet_opt, snippet_with_applicability};
-use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
+use rustc_ast::ast::{Expr, ExprKind, Impl, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
use rustc_ast::token::{self, LitKind};
use rustc_ast::tokenstream::TokenStream;
use rustc_errors::Applicability;
impl EarlyLintPass for Write {
fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
- if let ItemKind::Impl(box ImplKind {
+ if let ItemKind::Impl(box Impl {
of_trait: Some(trait_ref),
..
}) = &item.kind
(Use(l), Use(r)) => eq_use_tree(l, r),
(Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
(Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
- (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
+ (Fn(box ast::Fn { defaultness: ld, sig: lf, generics: lg, body: lb }),
+ Fn(box ast::Fn { defaultness: rd, sig: rf, generics: rg, body: rb })) => {
eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
},
(Mod(lu, lmk), Mod(ru, rmk)) => {
(ForeignMod(l), ForeignMod(r)) => {
both(&l.abi, &r.abi, eq_str_lit) && over(&l.items, &r.items, |l, r| eq_item(l, r, eq_foreign_item_kind))
},
- (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
+ (TyAlias(box ast::TyAlias { defaultness: ld, generics: lg, bounds: lb, ty: lt }),
+ TyAlias(box ast::TyAlias { defaultness: rd, generics: rg, bounds: rb, ty: rt })) => {
eq_defaultness(*ld, *rd)
&& eq_generics(lg, rg)
&& over(lb, rb, eq_generic_bound)
(Struct(lv, lg), Struct(rv, rg)) | (Union(lv, lg), Union(rv, rg)) => {
eq_variant_data(lv, rv) && eq_generics(lg, rg)
},
- (Trait(box TraitKind(la, lu, lg, lb, li)), Trait(box TraitKind(ra, ru, rg, rb, ri))) => {
+ (Trait(box ast::Trait { is_auto: la, unsafety: lu, generics: lg, bounds: lb, items: li }),
+ Trait(box ast::Trait { is_auto: ra, unsafety: ru, generics: rg, bounds: rb, items: ri })) => {
la == ra
&& matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No)
&& eq_generics(lg, rg)
},
(TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, eq_generic_bound),
(
- Impl(box ImplKind {
+ Impl(box ast::Impl {
unsafety: lu,
polarity: lp,
defaultness: ld,
self_ty: lst,
items: li,
}),
- Impl(box ImplKind {
+ Impl(box ast::Impl {
unsafety: ru,
polarity: rp,
defaultness: rd,
use ForeignItemKind::*;
match (l, r) {
(Static(lt, lm, le), Static(rt, rm, re)) => lm == rm && eq_ty(lt, rt) && eq_expr_opt(le, re),
- (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
+ (Fn(box ast::Fn { defaultness: ld, sig: lf, generics: lg, body: lb }),
+ Fn(box ast::Fn { defaultness: rd, sig: rf, generics: rg, body: rb })) => {
eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
},
- (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
+ (TyAlias(box ast::TyAlias { defaultness: ld, generics: lg, bounds: lb, ty: lt }),
+ TyAlias(box ast::TyAlias { defaultness: rd, generics: rg, bounds: rb, ty: rt })) => {
eq_defaultness(*ld, *rd)
&& eq_generics(lg, rg)
&& over(lb, rb, eq_generic_bound)
use AssocItemKind::*;
match (l, r) {
(Const(ld, lt, le), Const(rd, rt, re)) => eq_defaultness(*ld, *rd) && eq_ty(lt, rt) && eq_expr_opt(le, re),
- (Fn(box FnKind(ld, lf, lg, lb)), Fn(box FnKind(rd, rf, rg, rb))) => {
+ (Fn(box ast::Fn { defaultness: ld, sig: lf, generics: lg, body: lb }),
+ Fn(box ast::Fn { defaultness: rd, sig: rf, generics: rg, body: rb })) => {
eq_defaultness(*ld, *rd) && eq_fn_sig(lf, rf) && eq_generics(lg, rg) && both(lb, rb, |l, r| eq_block(l, r))
},
- (TyAlias(box TyAliasKind(ld, lg, lb, lt)), TyAlias(box TyAliasKind(rd, rg, rb, rt))) => {
+ (TyAlias(box ast::TyAlias { defaultness: ld, generics: lg, bounds: lb, ty: lt }),
+ TyAlias(box ast::TyAlias { defaultness: rd, generics: rg, bounds: rb, ty: rt })) => {
eq_defaultness(*ld, *rd)
&& eq_generics(lg, rg)
&& over(lb, rb, eq_generic_bound)
#![deny(clippy::missing_docs_in_private_items)]
use crate::ty::is_type_diagnostic_item;
-use crate::{is_expn_of, last_path_segment, match_def_path, path_to_local_id, paths};
+use crate::{is_expn_of, last_path_segment, match_def_path, paths};
use if_chain::if_chain;
use rustc_ast::ast::{self, LitKind};
use rustc_hir as hir;
use rustc_hir::{
- Arm, Block, BorrowKind, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, PatKind, QPath, StmtKind, UnOp,
+ Arm, Block, BorrowKind, Expr, ExprKind, HirId, LoopSource, MatchSource, Node, Pat, QPath, StmtKind, UnOp,
};
use rustc_lint::LateContext;
use rustc_span::{sym, symbol, ExpnKind, Span, Symbol};
pub format_string_parts: &'tcx [Expr<'tcx>],
/// Symbols corresponding to [`Self::format_string_parts`]
pub format_string_symbols: Vec<Symbol>,
- /// Match arm patterns, the `arg0`, etc. from the next field `args`
- pub arg_names: &'tcx [Pat<'tcx>],
/// Expressions like `ArgumentV1::new(arg0, Debug::fmt)`
pub args: &'tcx [Expr<'tcx>],
/// The final argument passed to `Arguments::new_v1_formatted`, if applicable
_ => None,
})
.collect();
- if let PatKind::Tuple(arg_names, None) = arm.pat.kind;
if let ExprKind::Array(args) = arm.body.kind;
then {
Some(FormatArgsExpn {
value_args,
format_string_parts,
format_string_symbols,
- arg_names,
args,
fmt_expr,
})
if let Ok(i) = usize::try_from(position);
let arg = &self.args[i];
if let ExprKind::Call(_, [arg_name, _]) = arg.kind;
- if let Some(j) = self
- .arg_names
- .iter()
- .position(|pat| path_to_local_id(arg_name, pat.hir_id));
+ if let ExprKind::Field(_, j) = arg_name.kind;
+ if let Ok(j) = j.name.as_str().parse::<usize>();
then {
Some(FormatArgsArg { value: self.value_args[j], arg, fmt: Some(fmt) })
} else {
-Subproject commit 04f03a360ab8fef3d9c0ff84de2d39b8a196c717
+Subproject commit 2c0f433fd2e838ae181f87019b6f1fefe33c6f54
--- /dev/null
+name: rustdoc check
+on:
+ push:
+ branches:
+ - master
+ pull_request:
+
+jobs:
+ rustdoc_check:
+ runs-on: ubuntu-latest
+ name: rustdoc check
+ steps:
+ - name: checkout
+ uses: actions/checkout@v2
+
+ - name: install rustup
+ run: |
+ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs > rustup-init.sh
+ sh rustup-init.sh -y --default-toolchain none
+ rustup target add x86_64-unknown-linux-gnu
+
+ - name: document rustfmt
+ env:
+ RUSTDOCFLAGS: --document-private-items --enable-index-page --show-type-layout --generate-link-to-definition -Zunstable-options -Dwarnings
+ run: cargo doc -Zskip-rustdoc-fingerprint --no-deps -p rustfmt-nightly -p rustfmt-config_proc_macro
Controls the strategy for how imports are grouped together.
- **Default value**: `Preserve`
-- **Possible values**: `Preserve`, `StdExternalCrate`
+- **Possible values**: `Preserve`, `StdExternalCrate`, `One`
- **Stable**: No
#### `Preserve` (default):
use crate::models::Event;
```
+#### `One`:
+
+Discard existing import groups, and create a single group for everything
+
+```rust
+use super::schema::{Context, Payload};
+use super::update::convert_publish_payload;
+use crate::models::Event;
+use alloc::alloc::Layout;
+use broker::database::PooledConnection;
+use chrono::Utc;
+use core::f32;
+use juniper::{FieldError, FieldResult};
+use std::sync::Arc;
+use uuid::Uuid;
+```
+
## `reorder_modules`
Reorder `mod` declarations alphabetically in group.
## Debugging
Some `rewrite_*` methods use the `debug!` macro for printing useful information.
-These messages can be printed by using the environment variable `RUST_LOG=rustfmt=DEBUG`.
+These messages can be printed by using the environment variable `RUSTFMT_LOG=rustfmt=DEBUG`.
These traces can be helpful in understanding which part of the code was used
and get a better grasp on the execution flow.
## Limitations
-Rustfmt tries to work on as much Rust code as possible, sometimes, the code
+Rustfmt tries to work on as much Rust code as possible. Sometimes, the code
doesn't even need to compile! As we approach a 1.0 release we are also looking
to limit areas of instability; in particular, post-1.0, the formatting of most
code should not change as Rustfmt improves. However, there are some things that
binary and library targets of your crate.
You can run `rustfmt --help` for information about available arguments.
+The easiest way to run rustfmt against a project is with `cargo fmt`. `cargo fmt` works on both
+single-crate projects and [cargo workspaces](https://doc.rust-lang.org/book/ch14-03-cargo-workspaces.html).
+Please see `cargo fmt --help` for usage information.
+
+You can specify the path to your own `rustfmt` binary for cargo to use by setting the`RUSTFMT`
+environment variable. This was added in v1.4.22, so you must have this version or newer to leverage this feature (`cargo fmt --version`)
+
+### Running `rustfmt` directly
+
+To format individual files or arbitrary codes from stdin, the `rustfmt` binary should be used. Some
+examples follow:
+
+- `rustfmt lib.rs main.rs` will format "lib.rs" and "main.rs" in place
+- `rustfmt` will read a code from stdin and write formatting to stdout
+ - `echo "fn main() {}" | rustfmt` would emit "fn main() {}".
+
+For more information, including arguments and emit options, see `rustfmt --help`.
+
+### Verifying code is formatted
When running with `--check`, Rustfmt will exit with `0` if Rustfmt would not
make any formatting changes to the input, and `1` if Rustfmt would make changes.
It will also print any found differences. (Older versions of Rustfmt don't
support `--check`, use `--write-mode diff`).
-A minimal Travis setup could look like this (requires Rust 1.24.0 or greater):
+A minimal Travis setup could look like this (requires Rust 1.31.0 or greater):
```yaml
language: rust
+++ /dev/null
-environment:
- global:
- PROJECT_NAME: rustfmt
-
-build: false
-
-test_script:
- - echo Why does no one have access to delete me?
## Installation
- Install [CLion](https://www.jetbrains.com/clion/), [IntelliJ Ultimate or CE](https://www.jetbrains.com/idea/) through the direct download link or using the [JetBrains Toolbox](https://www.jetbrains.com/toolbox/).
- CLion provides a built-in debugger interface but its not free like IntelliJ CE - which does not provide the debugger interface. (IntelliJ seems to lack the toolchain for that, see this discussion [intellij-rust/issues/535](https://github.com/intellij-rust/intellij-rust/issues/535))
-
-- Install the [Rust Plugin](https://intellij-rust.github.io/) by navigating to File -> Settings -> Plugins and press "Install JetBrains Plugin"
- ![plugins](https://user-images.githubusercontent.com/1133787/47240861-f40af680-d3e9-11e8-9b82-cdd5c8d5f5b8.png)
+ CLion and IntelliJ Ultimate [provide a built-in debugger interface](https://github.com/intellij-rust/intellij-rust#compatible-ides) but they are not free like IntelliJ CE.
+
+- Install the [Rust Plugin](https://intellij-rust.github.io/) by navigating to File → Settings → Plugins and searching the plugin in the Marketplace
+ ![plugins](https://user-images.githubusercontent.com/6505554/83944518-6f1e5c00-a81d-11ea-9c35-e16948811ba8.png)
-- Press "Install" on the rust plugin
- ![install rust](https://user-images.githubusercontent.com/1133787/47240803-c0c86780-d3e9-11e8-9265-22f735e4d7ed.png)
+- Press "Install" on the Rust plugin
+ ![install rust](https://user-images.githubusercontent.com/6505554/83944533-82c9c280-a81d-11ea-86b3-ee2e31bc7d12.png)
- Restart CLion/IntelliJ
## Configuration
-- Open the settings window (File -> Settings) and search for "reformat"
+### Run Rustfmt on save
+
+- Open Rustfmt settings (File → Settings → Languages & Frameworks → Rust → Rustfmt) and enable "Run rustfmt on Save"
+ ![run_rustfmt_on_save](https://user-images.githubusercontent.com/6505554/83944610-3468f380-a81e-11ea-9c34-0cbd18dd4969.png)
+
+- IntellJ uses autosave, so now your files will always be formatted according to rustfmt. Alternatively you can use Ctrl+S to reformat file manually
+
+### Bind shortcut to "Reformat File with Rustfmt" action
+
+- Open the settings window (File → Settings) and search for "reformat"
![keymap](https://user-images.githubusercontent.com/1133787/47240922-2ae10c80-d3ea-11e8-9d8f-c798d9749240.png)
- Right-click on "Reformat File with Rustfmt" and assign a keyboard shortcut
+++ /dev/null
-indent_style = "Visual"
-combine_control_expr = false
[toolchain]
-channel = "nightly-2021-10-20"
+channel = "nightly-2021-11-08"
components = ["rustc-dev"]
if next.is_doc_comment() {
let snippet = context.snippet(missing_span);
let (_, mlb) = has_newlines_before_after_comment(snippet);
- result.push_str(&mlb);
+ result.push_str(mlb);
}
}
result.push('\n');
if next.is_doc_comment() {
let snippet = context.snippet(missing_span);
let (_, mlb) = has_newlines_before_after_comment(snippet);
- result.push_str(&mlb);
+ result.push_str(mlb);
}
}
result.push('\n');
) {
assert_eq!(
expected_comment,
- format!("{}", DocCommentFormatter::new(&literal, style))
+ format!("{}", DocCommentFormatter::new(literal, style))
);
}
}
};
fn main() {
- env_logger::init();
+ env_logger::Builder::from_env("RUSTFMT_LOG").init();
let opts = make_opts();
let exit_code = match execute(&opts) {
fn get_targets_recursive(
manifest_path: Option<&Path>,
- mut targets: &mut BTreeSet<Target>,
+ targets: &mut BTreeSet<Target>,
visited: &mut BTreeSet<String>,
) -> Result<(), io::Error> {
let metadata = get_cargo_metadata(manifest_path)?;
for package in &metadata.packages {
- add_targets(&package.targets, &mut targets);
+ add_targets(&package.targets, targets);
// Look for local dependencies using information available since cargo v1.51
// It's theoretically possible someone could use a newer version of rustfmt with
.any(|p| p.manifest_path.eq(&manifest_path))
{
visited.insert(dependency.name.to_owned());
- get_targets_recursive(Some(&manifest_path), &mut targets, visited)?;
+ get_targets_recursive(Some(&manifest_path), targets, visited)?;
}
}
}
} else {
self.rewrites
.iter()
- .map(|rw| utils::unicode_str_width(&rw))
+ .map(|rw| utils::unicode_str_width(rw))
.sum()
} + last.tries;
let one_line_budget = if self.child_count == 1 {
ChainItemKind::Comment(_, CommentPosition::Top) => result.push_str(&connector),
_ => result.push_str(&connector),
}
- result.push_str(&rewrite);
+ result.push_str(rewrite);
}
Some(result)
/// attributes are valid rust attributes
/// See <https://doc.rust-lang.org/rustdoc/print.html#attributes>
fn new(attributes: &str) -> CodeBlockAttribute {
- for attribute in attributes.split(",") {
+ for attribute in attributes.split(',') {
match attribute.trim() {
"" | "rust" | "should_panic" | "no_run" | "edition2015" | "edition2018"
| "edition2021" => (),
result.push_str(line);
result.push_str(match iter.peek() {
Some(next_line) if next_line.is_empty() => sep.trim_end(),
- Some(..) => &sep,
+ Some(..) => sep,
None => "",
});
}
let is_last = i == count_newlines(orig);
if let Some(ref mut ib) = self.item_block {
- if ib.add_line(&line) {
+ if ib.add_line(line) {
return false;
}
self.is_prev_line_multi_line = false;
self.item_block = None;
if let Some(stripped) = line.strip_prefix("```") {
self.code_block_attr = Some(CodeBlockAttribute::new(stripped))
- } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(&line) {
- let ib = ItemizedBlock::new(&line);
+ } else if self.fmt.config.wrap_comments() && ItemizedBlock::is_itemized_line(line) {
+ let ib = ItemizedBlock::new(line);
self.item_block = Some(ib);
return false;
}
{
(&line[4..], true)
} else if let CommentStyle::Custom(opener) = *style {
- if let Some(ref stripped) = line.strip_prefix(opener) {
+ if let Some(stripped) = line.strip_prefix(opener) {
(stripped, true)
} else {
(&line[opener.trim_end().len()..], false)
None => unreachable!(),
};
- while let Some((kind, c)) = self.base.next() {
+ for (kind, c) in self.base.by_ref() {
// needed to set the kind of the ending character on the last line
self.kind = kind;
if c == '\n' {
context.parse_sess.span_to_filename(span),
vec![FormattingError::from_span(
span,
- &context.parse_sess,
+ context.parse_sess,
ErrorKind::LostComment,
)],
);
fn remove_comment_header(comment: &str) -> &str {
if comment.starts_with("///") || comment.starts_with("//!") {
&comment[3..]
- } else if let Some(ref stripped) = comment.strip_prefix("//") {
+ } else if let Some(stripped) = comment.strip_prefix("//") {
stripped
} else if (comment.starts_with("/**") && !comment.starts_with("/**/"))
|| comment.starts_with("/*!")
Windows,
/// Force CR (`\n).
Unix,
- /// `\r\n` in Windows, `\n`` on other platforms.
+ /// `\r\n` in Windows, `\n` on other platforms.
Native,
}
/// 2. other imports
/// 3. `self` / `crate` / `super` imports
StdExternalCrate,
+ /// Discard existing groups, and create a single group for everything
+ One,
}
#[config_type]
format!(r#"<file name="{}">"#, bin_file),
format!(
r#"<error line="2" severity="warning" message="Should be `{}`" />"#,
- XmlEscaped(&r#" println!("Hello, world!");"#),
+ XmlEscaped(r#" println!("Hello, world!");"#),
),
String::from("</file>"),
];
format!(r#"<file name="{}">"#, lib_file),
format!(
r#"<error line="2" severity="warning" message="Should be `{}`" />"#,
- XmlEscaped(&r#" println!("Greetings!");"#),
+ XmlEscaped(r#" println!("Greetings!");"#),
),
String::from("</file>"),
];
}: FormattedFile<'_>,
) -> Result<EmitterResult, io::Error> {
const CONTEXT_SIZE: usize = 3;
- let mismatch = make_diff(&original_text, formatted_text, CONTEXT_SIZE);
+ let mismatch = make_diff(original_text, formatted_text, CONTEXT_SIZE);
let has_diff = !mismatch.is_empty();
if has_diff {
}
_ => false,
},
- ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, &expr),
+ ast::ExprKind::Unary(_, ref expr) => needs_space_before_range(context, expr),
_ => false,
}
}
prefix: &str,
shape: Shape,
) -> Option<String> {
- if block_has_statements(&block) {
+ if block_has_statements(block) {
return None;
}
block: &ast::Block,
attrs: Option<&[ast::Attribute]>,
) -> bool {
- !block_has_statements(&block)
+ !block_has_statements(block)
&& !block_contains_comment(context, block)
&& attrs.map_or(true, |a| inner_attributes(a).is_empty())
}
let span = lit.span;
let symbol = lit.token.symbol.as_str();
- if symbol.starts_with("0x") {
+ if let Some(symbol_stripped) = symbol.strip_prefix("0x") {
let hex_lit = match context.config.hex_literal_case() {
HexLiteralCase::Preserve => None,
- HexLiteralCase::Upper => Some(symbol[2..].to_ascii_uppercase()),
- HexLiteralCase::Lower => Some(symbol[2..].to_ascii_lowercase()),
+ HexLiteralCase::Upper => Some(symbol_stripped.to_ascii_uppercase()),
+ HexLiteralCase::Lower => Some(symbol_stripped.to_ascii_lowercase()),
};
if let Some(hex_lit) = hex_lit {
return wrap_str(
};
let fields_str =
- wrap_struct_field(context, &attrs, &fields_str, shape, v_shape, one_line_width)?;
+ wrap_struct_field(context, attrs, &fields_str, shape, v_shape, one_line_width)?;
Some(format!("{} {{{}}}", path_str, fields_str))
// FIXME if context.config.indent_style() == Visual, but we run out
shape: Shape,
rhs_tactics: RhsTactics,
) -> Option<String> {
- let last_line_width = last_line_width(&lhs).saturating_sub(if lhs.contains('\n') {
+ let last_line_width = last_line_width(lhs).saturating_sub(if lhs.contains('\n') {
shape.indent.width()
} else {
0
if contains_comment {
let rhs = rhs.trim_start();
- combine_strs_with_missing_comments(context, &lhs, &rhs, between_span, shape, allow_extend)
+ combine_strs_with_missing_comments(context, &lhs, rhs, between_span, shape, allow_extend)
} else {
Some(lhs + &rhs)
}
has_rhs_comment: bool,
) -> Option<String> {
match orig_rhs {
+ Some(ref new_str) if new_str.is_empty() => {
+ return Some(String::new());
+ }
Some(ref new_str)
if !new_str.contains('\n') && unicode_str_width(new_str) <= shape.width =>
{
}
fn main() {
- env_logger::init();
+ env_logger::Builder::from_env("RUSTFMT_LOG").init();
let opts = Opts::from_args();
if let Err(e) = run(opts) {
println!("{}", e);
let snippet_provider = self.parse_session.snippet_provider(module.span);
let mut visitor = FmtVisitor::from_parse_sess(
&self.parse_session,
- &self.config,
+ self.config,
&snippet_provider,
self.report.clone(),
);
&mut visitor.buffer,
&path,
&visitor.skipped_range.borrow(),
- &self.config,
+ self.config,
&self.report,
);
}
fn main() {
- env_logger::init();
+ env_logger::Builder::from_env("RUSTFMT_LOG").init();
let opts = make_opts();
let matches = opts
shape: Shape,
) -> Option<String> {
let vis = self.visibility.as_ref().map_or(Cow::from(""), |vis| {
- crate::utils::format_visibility(context, &vis)
+ crate::utils::format_visibility(context, vis)
});
let use_str = self
.rewrite(context, shape.offset_left(vis.len())?)
fn rewrite(&self, context: &RewriteContext<'_>, mut shape: Shape) -> Option<String> {
let mut result = String::with_capacity(256);
let mut iter = self.path.iter().peekable();
- while let Some(ref segment) = iter.next() {
+ while let Some(segment) = iter.next() {
let segment_str = segment.rewrite(context, shape)?;
result.push_str(&segment_str);
if iter.peek().is_some() {
fn to_str(&self, context: &RewriteContext<'_>) -> String {
let mut result = String::with_capacity(128);
// Vis defaultness constness unsafety abi.
- result.push_str(&*format_visibility(context, &self.visibility));
+ result.push_str(&*format_visibility(context, self.visibility));
result.push_str(format_defaultness(self.defaultness));
result.push_str(format_constness(self.constness));
result.push_str(format_async(&self.is_async));
fn need_empty_line(a: &ast::AssocItemKind, b: &ast::AssocItemKind) -> bool {
match (a, b) {
(TyAlias(lty), TyAlias(rty))
- if both_type(<y.3, &rty.3) || both_opaque(<y.3, &rty.3) =>
+ if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) =>
{
false
}
buffer.sort_by(|(_, a), (_, b)| match (&a.kind, &b.kind) {
(TyAlias(lty), TyAlias(rty))
- if both_type(<y.3, &rty.3) || both_opaque(<y.3, &rty.3) =>
+ if both_type(<y.ty, &rty.ty) || both_opaque(<y.ty, &rty.ty) =>
{
a.ident.as_str().cmp(&b.ident.as_str())
}
a.ident.as_str().cmp(&b.ident.as_str())
}
(Fn(..), Fn(..)) => a.span.lo().cmp(&b.span.lo()),
- (TyAlias(ty), _) if is_type(&ty.3) => Ordering::Less,
- (_, TyAlias(ty)) if is_type(&ty.3) => Ordering::Greater,
+ (TyAlias(ty), _) if is_type(&ty.ty) => Ordering::Less,
+ (_, TyAlias(ty)) if is_type(&ty.ty) => Ordering::Greater,
(TyAlias(..), _) => Ordering::Less,
(_, TyAlias(..)) => Ordering::Greater,
(Const(..), _) => Ordering::Less,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Impl(impl_kind) = &item.kind {
- let ast::ImplKind {
+ let ast::Impl {
ref generics,
ref self_ty,
ref items,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Impl(impl_kind) = &item.kind {
- let ast::ImplKind {
+ let ast::Impl {
unsafety,
polarity,
defaultness,
offset: Indent,
) -> Option<String> {
if let ast::ItemKind::Trait(trait_kind) = &item.kind {
- let ast::TraitKind(is_auto, unsafety, ref generics, ref generic_bounds, ref trait_items) =
- **trait_kind;
+ let ast::Trait {
+ is_auto,
+ unsafety,
+ ref generics,
+ ref bounds,
+ ref items,
+ } = **trait_kind;
let mut result = String::with_capacity(128);
let header = format!(
"{}{}{}trait ",
result.push_str(&generics_str);
// FIXME(#2055): rustfmt fails to format when there are comments between trait bounds.
- if !generic_bounds.is_empty() {
+ if !bounds.is_empty() {
let ident_hi = context
.snippet_provider
.span_after(item.span, &item.ident.as_str());
- let bound_hi = generic_bounds.last().unwrap().span().hi();
+ let bound_hi = bounds.last().unwrap().span().hi();
let snippet = context.snippet(mk_sp(ident_hi, bound_hi));
if contains_comment(snippet) {
return None;
result = rewrite_assign_rhs_with(
context,
result + ":",
- generic_bounds,
+ bounds,
shape,
RhsTactics::ForceNextLineWithoutIndent,
)?;
let where_on_new_line = context.config.indent_style() != IndentStyle::Block;
let where_budget = context.budget(last_line_width(&result));
- let pos_before_where = if generic_bounds.is_empty() {
+ let pos_before_where = if bounds.is_empty() {
generics.where_clause.span.lo()
} else {
- generic_bounds[generic_bounds.len() - 1].span().hi()
+ bounds[bounds.len() - 1].span().hi()
};
let option = WhereClauseOption::snuggled(&generics_str);
let where_clause_str = rewrite_where_clause(
}
}
+ let block_span = mk_sp(generics.where_clause.span.hi(), item.span.hi());
+ let snippet = context.snippet(block_span);
+ let open_pos = snippet.find_uncommented("{")? + 1;
+
match context.config.brace_style() {
_ if last_line_contains_single_line_comment(&result)
|| last_line_width(&result) + 2 > context.budget(offset.width()) =>
{
result.push_str(&offset.to_string_with_newline(context.config));
}
+ _ if context.config.empty_item_single_line()
+ && items.is_empty()
+ && !result.contains('\n')
+ && !contains_comment(&snippet[open_pos..]) =>
+ {
+ result.push_str(" {}");
+ return Some(result);
+ }
BraceStyle::AlwaysNextLine => {
result.push_str(&offset.to_string_with_newline(context.config));
}
BraceStyle::PreferSameLine => result.push(' '),
BraceStyle::SameLineWhere => {
if result.contains('\n')
- || (!generics.where_clause.predicates.is_empty() && !trait_items.is_empty())
+ || (!generics.where_clause.predicates.is_empty() && !items.is_empty())
{
result.push_str(&offset.to_string_with_newline(context.config));
} else {
}
result.push('{');
- let block_span = mk_sp(generics.where_clause.span.hi(), item.span.hi());
- let snippet = context.snippet(block_span);
- let open_pos = snippet.find_uncommented("{")? + 1;
let outer_indent_str = offset.block_only().to_string_with_newline(context.config);
- if !trait_items.is_empty() || contains_comment(&snippet[open_pos..]) {
+ if !items.is_empty() || contains_comment(&snippet[open_pos..]) {
let mut visitor = FmtVisitor::from_context(context);
visitor.block_indent = offset.block_only().block_indent(context.config);
visitor.last_pos = block_span.lo() + BytePos(open_pos as u32);
- for item in trait_items {
+ for item in items {
visitor.visit_trait_item(item);
}
}
}
-struct OpaqueTypeBounds<'a> {
- generic_bounds: &'a ast::GenericBounds,
-}
-
-impl<'a> Rewrite for OpaqueTypeBounds<'a> {
- fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
- self.generic_bounds
- .rewrite(context, shape)
- .map(|s| format!("impl {}", s))
- }
-}
-
pub(crate) struct TraitAliasBounds<'a> {
generic_bounds: &'a ast::GenericBounds,
generics: &'a ast::Generics,
} else if fits_single_line {
Cow::from(" ")
} else {
- shape.indent.to_string_with_newline(&context.config)
+ shape.indent.to_string_with_newline(context.config)
};
Some(format!("{}{}{}", generic_bounds_str, space, where_str))
let alias = rewrite_ident(context, ident);
// 6 = "trait ", 2 = " ="
let g_shape = shape.offset_left(6)?.sub_width(2)?;
- let generics_str = rewrite_generics(context, &alias, generics, g_shape)?;
+ let generics_str = rewrite_generics(context, alias, generics, g_shape)?;
let vis_str = format_visibility(context, vis);
let lhs = format!("{}trait {} =", vis_str, generics_str);
// 1 = ";"
closer: &str,
) {
// 3 = " {}" or "();"
- let used_width = last_line_used_width(&result, offset.width()) + 3;
+ let used_width = last_line_used_width(result, offset.width()) + 3;
if used_width > context.config.max_width() {
result.push_str(&offset.to_string_with_newline(context.config))
}
Some(result)
}
-pub(crate) fn rewrite_type<R: Rewrite>(
- context: &RewriteContext<'_>,
+pub(crate) enum ItemVisitorKind<'a> {
+ Item(&'a ast::Item),
+ AssocTraitItem(&'a ast::AssocItem),
+ AssocImplItem(&'a ast::AssocItem),
+ ForeignItem(&'a ast::ForeignItem),
+}
+
+struct TyAliasRewriteInfo<'c, 'g>(
+ &'c RewriteContext<'c>,
+ Indent,
+ &'g ast::Generics,
+ symbol::Ident,
+ Span,
+);
+
+pub(crate) fn rewrite_type_alias<'a, 'b>(
+ ty_alias_kind: &ast::TyAlias,
+ context: &RewriteContext<'a>,
indent: Indent,
- ident: symbol::Ident,
- vis: &ast::Visibility,
- generics: &ast::Generics,
+ visitor_kind: &ItemVisitorKind<'b>,
+ span: Span,
+) -> Option<String> {
+ use ItemVisitorKind::*;
+
+ let ast::TyAlias {
+ defaultness,
+ ref generics,
+ ref bounds,
+ ref ty,
+ } = *ty_alias_kind;
+ let ty_opt = ty.as_ref().map(|t| &**t);
+ let (ident, vis) = match visitor_kind {
+ Item(i) => (i.ident, &i.vis),
+ AssocTraitItem(i) | AssocImplItem(i) => (i.ident, &i.vis),
+ ForeignItem(i) => (i.ident, &i.vis),
+ };
+ let rw_info = &TyAliasRewriteInfo(context, indent, generics, ident, span);
+
+ // Type Aliases are formatted slightly differently depending on the context
+ // in which they appear, whether they are opaque, and whether they are associated.
+ // https://rustc-dev-guide.rust-lang.org/opaque-types-type-alias-impl-trait.html
+ // https://github.com/rust-dev-tools/fmt-rfcs/blob/master/guide/items.md#type-aliases
+ match (visitor_kind, ty_opt) {
+ (Item(_), None) => {
+ let op_ty = OpaqueType { bounds };
+ rewrite_ty(rw_info, Some(bounds), Some(&op_ty), vis)
+ }
+ (Item(_), Some(ty)) => rewrite_ty(rw_info, Some(bounds), Some(&*ty), vis),
+ (AssocImplItem(_), _) => {
+ let result = if let Some(ast::Ty {
+ kind: ast::TyKind::ImplTrait(_, ref bounds),
+ ..
+ }) = ty_opt
+ {
+ let op_ty = OpaqueType { bounds };
+ rewrite_ty(rw_info, None, Some(&op_ty), &DEFAULT_VISIBILITY)
+ } else {
+ rewrite_ty(rw_info, None, ty.as_ref(), vis)
+ }?;
+ match defaultness {
+ ast::Defaultness::Default(..) => Some(format!("default {}", result)),
+ _ => Some(result),
+ }
+ }
+ (AssocTraitItem(_), _) | (ForeignItem(_), _) => {
+ rewrite_ty(rw_info, Some(bounds), ty.as_ref(), vis)
+ }
+ }
+}
+
+fn rewrite_ty<R: Rewrite>(
+ rw_info: &TyAliasRewriteInfo<'_, '_>,
generic_bounds_opt: Option<&ast::GenericBounds>,
rhs: Option<&R>,
- span: Span,
+ vis: &ast::Visibility,
) -> Option<String> {
let mut result = String::with_capacity(128);
+ let TyAliasRewriteInfo(context, indent, generics, ident, span) = *rw_info;
result.push_str(&format!("{}type ", format_visibility(context, vis)));
let ident_str = rewrite_ident(context, ident);
}
}
-pub(crate) fn rewrite_opaque_type(
- context: &RewriteContext<'_>,
- indent: Indent,
- ident: symbol::Ident,
- generic_bounds: &ast::GenericBounds,
- generics: &ast::Generics,
- vis: &ast::Visibility,
- span: Span,
-) -> Option<String> {
- let opaque_type_bounds = OpaqueTypeBounds { generic_bounds };
- rewrite_type(
- context,
- indent,
- ident,
- vis,
- generics,
- Some(generic_bounds),
- Some(&opaque_type_bounds),
- span,
- )
-}
-
fn type_annotation_spacing(config: &Config) -> (&str, &str) {
(
if config.space_before_colon() { " " } else { "" },
}
}
-pub(crate) fn rewrite_impl_type(
- ident: symbol::Ident,
- vis: &ast::Visibility,
- defaultness: ast::Defaultness,
- ty_opt: Option<&ptr::P<ast::Ty>>,
- generics: &ast::Generics,
- context: &RewriteContext<'_>,
- indent: Indent,
- span: Span,
-) -> Option<String> {
- // Opaque type
- let result = if let Some(rustc_ast::ast::Ty {
- kind: ast::TyKind::ImplTrait(_, ref bounds),
- ..
- }) = ty_opt.map(|t| &**t)
- {
- rewrite_type(
- context,
- indent,
- ident,
- &DEFAULT_VISIBILITY,
- generics,
- None,
- Some(&OpaqueType { bounds }),
- span,
- )
- } else {
- rewrite_type(context, indent, ident, vis, generics, None, ty_opt, span)
- }?;
-
- match defaultness {
- ast::Defaultness::Default(..) => Some(format!("default {}", result)),
- _ => Some(result),
- }
-}
-
impl Rewrite for ast::FnRetTy {
fn rewrite(&self, context: &RewriteContext<'_>, shape: Shape) -> Option<String> {
match *self {
)?;
Some(combine_strs_with_missing_comments(
context,
- ¶m_attrs,
+ param_attrs,
&format!("&{} {}self", lifetime_str, mut_str),
span,
shape,
}
None => Some(combine_strs_with_missing_comments(
context,
- ¶m_attrs,
+ param_attrs,
&format!("&{}self", mut_str),
span,
shape,
Some(combine_strs_with_missing_comments(
context,
- ¶m_attrs,
+ param_attrs,
&format!("{}self: {}", format_mutability(mutability), type_str),
span,
shape,
}
ast::SelfKind::Value(mutability) => Some(combine_strs_with_missing_comments(
context,
- ¶m_attrs,
+ param_attrs,
&format!("{}self", format_mutability(mutability)),
span,
shape,
}
// Skip `pub(crate)`.
- let lo_after_visibility = get_bytepos_after_visibility(&fn_sig.visibility, span);
+ let lo_after_visibility = get_bytepos_after_visibility(fn_sig.visibility, span);
// A conservative estimation, the goal is to be over all parens in generics
let params_start = fn_sig
.generics
let mut result = String::with_capacity(128);
let shape = Shape::indented(offset, context.config);
- result.push_str(&format_visibility(context, vis).trim());
+ result.push_str(format_visibility(context, vis).trim());
// Check for a missing comment between the visibility and the item name.
let after_vis = vis.span.hi();
}
}
- result.push_str(&rewrite_ident(context, ident));
+ result.push_str(rewrite_ident(context, ident));
result
}
let item_str = match self.kind {
ast::ForeignItemKind::Fn(ref fn_kind) => {
- let ast::FnKind(defaultness, ref fn_sig, ref generics, ref block) = **fn_kind;
- if let Some(ref body) = block {
+ let ast::Fn {
+ defaultness,
+ ref sig,
+ ref generics,
+ ref body,
+ } = **fn_kind;
+ if let Some(ref body) = body {
let mut visitor = FmtVisitor::from_context(context);
visitor.block_indent = shape.indent;
visitor.last_pos = self.span.lo();
let inner_attrs = inner_attributes(&self.attrs);
let fn_ctxt = visit::FnCtxt::Foreign;
visitor.visit_fn(
- visit::FnKind::Fn(fn_ctxt, self.ident, &fn_sig, &self.vis, Some(body)),
+ visit::FnKind::Fn(fn_ctxt, self.ident, &sig, &self.vis, Some(body)),
generics,
- &fn_sig.decl,
+ &sig.decl,
self.span,
defaultness,
Some(&inner_attrs),
context,
shape.indent,
self.ident,
- &FnSig::from_method_sig(&fn_sig, generics, &self.vis),
+ &FnSig::from_method_sig(&sig, generics, &self.vis),
span,
FnBraceStyle::None,
)
// 1 = ;
rewrite_assign_rhs(context, prefix, &**ty, shape.sub_width(1)?).map(|s| s + ";")
}
- ast::ForeignItemKind::TyAlias(ref ty_alias_kind) => {
- let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref type_default) =
- **ty_alias_kind;
- rewrite_type(
- &context,
- shape.indent,
- self.ident,
- &self.vis,
- generics,
- Some(generic_bounds),
- type_default.as_ref(),
- self.span,
- )
+ ast::ForeignItemKind::TyAlias(ref ty_alias) => {
+ let (kind, span) = (&ItemVisitorKind::ForeignItem(&self), self.span);
+ rewrite_type_alias(ty_alias, context, shape.indent, kind, span)
}
ast::ForeignItemKind::MacCall(ref mac) => {
rewrite_macro(mac, None, context, shape, MacroPosition::Item)
combine_strs_with_missing_comments(
context,
&attrs_str,
- &item_str,
+ item_str,
missed_span,
shape,
allow_extend,
writeln!(
t,
"{}",
- FormatReportFormatterBuilder::new(&self)
+ FormatReportFormatterBuilder::new(self)
.enable_colors(true)
.build()
)?;
impl fmt::Display for FormatReport {
// Prints all the formatting errors.
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
- write!(fmt, "{}", FormatReportFormatterBuilder::new(&self).build())?;
+ write!(fmt, "{}", FormatReportFormatterBuilder::new(self).build())?;
Ok(())
}
}
result.push('\n');
result.push_str(indent_str);
// This is the width of the item (without comments).
- line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(&s));
+ line_len = item.item.as_ref().map_or(0, |s| unicode_str_width(s));
}
} else {
result.push(' ')
pub(crate) fn total_item_width(item: &ListItem) -> usize {
comment_len(item.pre_comment.as_ref().map(|x| &(*x)[..]))
+ comment_len(item.post_comment.as_ref().map(|x| &(*x)[..]))
- + item.item.as_ref().map_or(0, |s| unicode_str_width(&s))
+ + item.item.as_ref().map_or(0, |s| unicode_str_width(s))
}
fn comment_len(comment: Option<&str>) -> usize {
})
.unwrap_or(false);
if is_like_block_indent_style {
- return trim_left_preserve_layout(context.snippet(span), indent, &context.config);
+ return trim_left_preserve_layout(context.snippet(span), indent, context.config);
}
context.skipped_range.borrow_mut().push((
// the `macro_name!` and `{ /* macro_body */ }` but skip modifying
// anything in between the braces (for now).
let snippet = context.snippet(mac.span()).trim_start_matches(|c| c != '{');
- match trim_left_preserve_layout(snippet, shape.indent, &context.config) {
+ match trim_left_preserve_layout(snippet, shape.indent, context.config) {
Some(macro_body) => Some(format!("{} {}", macro_name, macro_body)),
None => Some(format!("{} {}", macro_name, snippet)),
}
break;
}
TokenTree::Token(ref t) => {
- buffer.push_str(&pprust::token_to_string(&t));
+ buffer.push_str(&pprust::token_to_string(t));
}
_ => return None,
}
let mut iter = args.iter().peekable();
let indent_str = shape.indent.to_string_with_newline(context.config);
- while let Some(ref arg) = iter.next() {
+ while let Some(arg) = iter.next() {
result.push_str(&arg.rewrite(context, shape, use_multiple_lines)?);
if use_multiple_lines
result.pop();
}
result.push_str(&indent_str);
- } else if let Some(ref next_arg) = iter.peek() {
+ } else if let Some(next_arg) = iter.peek() {
let space_before_dollar =
!arg.kind.ends_with_space() && next_arg.kind.starts_with_dollar();
let space_before_brace = next_arg.kind.starts_with_brace();
{
s += &indent_str;
}
- (s + l + "\n", indent_next_line(kind, &l, &config))
+ (s + l + "\n", indent_next_line(kind, l, &config))
},
)
.0;
MacroArg::Item(item) => item,
_ => return None,
};
- visitor.visit_item(&item);
+ visitor.visit_item(item);
}
let mut result = String::with_capacity(256);
- result.push_str(¯o_name);
+ result.push_str(macro_name);
result.push_str(opener);
result.push_str(&visitor.block_indent.to_string_with_newline(context.config));
result.push_str(visitor.buffer.trim());
.map(|a| {
context
.snippet(a.pat.span)
- .starts_with("|")
+ .starts_with('|')
.then(|| a.pat.span().lo())
})
.collect()
let can_extend =
|expr| !context.config.force_multiline_blocks() && can_flatten_block_around_this(expr);
- if let Some(ref block) = block_can_be_flattened(context, body) {
+ if let Some(block) = block_can_be_flattened(context, body) {
if let ast::StmtKind::Expr(ref expr) = block.stmts[0].kind {
if let ast::ExprKind::Block(..) = expr.kind {
flatten_arm_body(context, expr, None)
if comment_str.is_empty() {
String::new()
} else {
- rewrite_comment(comment_str, false, shape, &context.config)?
+ rewrite_comment(comment_str, false, shape, context.config)?
}
};
result.push_str(&arrow_comment);
}
result.push_str(&nested_indent_str);
- result.push_str(&body_str);
- result.push_str(&comma);
+ result.push_str(body_str);
+ result.push_str(comma);
return Some(result);
}
result.push_str(&arrow_comment);
}
result.push_str(&block_sep);
- result.push_str(&body_str);
+ result.push_str(body_str);
result.push_str(&body_suffix);
Some(result)
};
Directory, DirectoryOwnership, ModError, ModulePathSuccess, Parser, ParserError,
};
use crate::syntux::session::ParseSess;
-use crate::utils::contains_skip;
+use crate::utils::{contains_skip, mk_sp};
mod visitor;
self.visit_mod_from_ast(&krate.items)?;
}
+ let snippet_provider = self.parse_sess.snippet_provider(krate.span);
+
self.file_map.insert(
root_filename,
Module::new(
- krate.span,
+ mk_sp(snippet_provider.start_pos(), snippet_provider.end_pos()),
None,
Cow::Borrowed(&krate.items),
Cow::Borrowed(&krate.attrs),
/// Visit modules from AST.
fn visit_mod_from_ast(
&mut self,
- items: &'ast Vec<rustc_ast::ptr::P<ast::Item>>,
+ items: &'ast [rustc_ast::ptr::P<ast::Item>],
) -> Result<(), ModuleResolutionError> {
for item in items {
if is_cfg_if(item) {
};
self.visit_sub_mod_after_directory_update(sub_mod, Some(directory))
}
- SubModKind::Internal(ref item) => {
+ SubModKind::Internal(item) => {
self.push_inline_mod_directory(item.ident, &item.attrs);
self.visit_sub_mod_after_directory_update(sub_mod, None)
}
}
match (sub_mod.ast_mod_kind, sub_mod.items) {
(Some(Cow::Borrowed(ast::ModKind::Loaded(items, _, _))), _) => {
- self.visit_mod_from_ast(&items)
+ self.visit_mod_from_ast(items)
+ }
+ (Some(Cow::Owned(ast::ModKind::Loaded(items, _, _))), _) | (_, Cow::Owned(items)) => {
+ self.visit_mod_outside_ast(items)
}
- (Some(Cow::Owned(..)), Cow::Owned(items)) => self.visit_mod_outside_ast(items),
(_, _) => Ok(()),
}
}
) -> Option<String> {
let last_item = self.last_item()?;
let rewrite = match last_item {
- OverflowableItem::Expr(ref expr) => {
+ OverflowableItem::Expr(expr) => {
match expr.kind {
// When overflowing the closure which consists of a single control flow
// expression, force to use block if its condition uses multi line.
for ((_, rewrite), s) in list.list.iter().zip(list.separators.iter()) {
if let Some(rewrite) = rewrite {
- if !is_single_line(&rewrite) || result.len() > shape.width {
+ if !is_single_line(rewrite) || result.len() > shape.width {
return None;
}
- result.push_str(&rewrite);
+ result.push_str(rewrite);
result.push(' ');
result.push_str(s);
result.push(' ');
shape: Shape,
context: &RewriteContext<'_>,
) -> Option<String> {
- let rhs_offset = shape.rhs_overhead(&context.config);
+ let rhs_offset = shape.rhs_overhead(context.config);
let nested_shape = (match context.config.indent_style() {
IndentStyle::Visual => shape.visual_indent(0),
IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
})
- .with_max_width(&context.config)
+ .with_max_width(context.config)
.sub_width(rhs_offset)?;
let indent_str = nested_shape.indent.to_string_with_newline(context.config);
let mut result = String::new();
- result.push_str(&list.list[0].1.as_ref()?);
+ result.push_str(list.list[0].1.as_ref()?);
for ((e, default_rw), s) in list.list[1..].iter().zip(list.separators.iter()) {
// The following test checks if we should keep two subexprs on the same
}
}
- result.push_str(&default_rw.as_ref()?);
+ result.push_str(default_rw.as_ref()?);
}
Some(result)
}
return node.rewrite(context, shape);
}
let nested_overhead = sep + 1;
- let rhs_offset = shape.rhs_overhead(&context.config);
+ let rhs_offset = shape.rhs_overhead(context.config);
let nested_shape = (match context.config.indent_style() {
IndentStyle::Visual => shape.visual_indent(0),
IndentStyle::Block => shape.block_indent(context.config.tab_spaces()),
})
- .with_max_width(&context.config)
+ .with_max_width(context.config)
.sub_width(rhs_offset)?;
let default_shape = match context.config.binop_separator() {
SeparatorPlace::Back => nested_shape.sub_width(nested_overhead)?,
context: &RewriteContext<'_>,
shape: Shape,
) -> Option<String> {
- let mut pat_vec: Vec<_> = pats.iter().map(|x| TuplePatField::Pat(x)).collect();
-
- if pat_vec.is_empty() {
+ if pats.is_empty() {
return Some(format!("{}()", path_str.unwrap_or_default()));
}
+ let mut pat_vec: Vec<_> = pats.iter().map(TuplePatField::Pat).collect();
+
let wildcard_suffix_len = count_wildcard_suffix_len(context, &pat_vec, span, shape);
let (pat_vec, span) = if context.config.condense_wildcard_suffixes() && wildcard_suffix_len >= 2
{
let path_str = path_str.unwrap_or_default();
overflow::rewrite_with_parens(
- &context,
+ context,
&path_str,
pat_vec.iter(),
shape,
};
let mut regrouped_items = match context.config.group_imports() {
- GroupImportsTactic::Preserve => vec![normalized_items],
+ GroupImportsTactic::Preserve | GroupImportsTactic::One => {
+ vec![normalized_items]
+ }
GroupImportsTactic::StdExternalCrate => group_imports(normalized_items),
};
span: Span,
) -> Result<(Vec<ast::Attribute>, Vec<ptr::P<ast::Item>>, Span), ParserError> {
let result = catch_unwind(AssertUnwindSafe(|| {
- let mut parser = new_parser_from_file(sess.inner(), &path, Some(span));
+ let mut parser = new_parser_from_file(sess.inner(), path, Some(span));
match parser.parse_mod(&TokenKind::Eof) {
Ok(result) => Some(result),
Err(mut e) => {
}
}));
match result {
- Ok(Some(m)) => {
- if !sess.has_errors() {
- return Ok(m);
- }
-
- if sess.can_reset_errors() {
- sess.reset_errors();
- return Ok(m);
- }
- Err(ParserError::ParseError)
+ Ok(Some(m)) if !sess.has_errors() => Ok(m),
+ Ok(Some(m)) if sess.can_reset_errors() => {
+ sess.reset_errors();
+ Ok(m)
}
- Ok(None) => Err(ParserError::ParseError),
+ Ok(_) => Err(ParserError::ParseError),
Err(..) if path.exists() => Err(ParserError::ParseError),
Err(_) => Err(ParserError::ParsePanicError),
}
}
pub(crate) fn ignore_file(&self, path: &FileName) -> bool {
- self.ignore_path_set.as_ref().is_match(&path)
+ self.ignore_path_set.as_ref().is_match(path)
}
pub(crate) fn set_silent_emitter(&mut self) {
debug!("Testing '{}'...", file_name.display());
- match idempotent_check(&file_name, &opt_config) {
+ match idempotent_check(&file_name, opt_config) {
Ok(ref report) if report.has_warnings() => {
- print!("{}", FormatReportFormatterBuilder::new(&report).build());
+ print!("{}", FormatReportFormatterBuilder::new(report).build());
fails += 1;
}
Ok(report) => reports.push(report),
use crate::{FileName, Input, Session};
-#[test]
-fn nested_out_of_line_mods_loaded() {
- // See also https://github.com/rust-lang/rustfmt/issues/4874
- let filename = "tests/mod-resolver/issue-4874/main.rs";
- let input_file = PathBuf::from(filename);
+fn verify_mod_resolution(input_file_name: &str, exp_misformatted_files: &[&str]) {
+ let input_file = PathBuf::from(input_file_name);
let config = read_config(&input_file);
let mut session = Session::<io::Stdout>::new(config, None);
let report = session
- .format(Input::File(filename.into()))
+ .format(Input::File(input_file_name.into()))
.expect("Should not have had any execution errors");
let errors_by_file = &report.internal.borrow().0;
- assert!(errors_by_file.contains_key(&FileName::Real(PathBuf::from(
- "tests/mod-resolver/issue-4874/bar/baz.rs",
- ))));
- assert!(errors_by_file.contains_key(&FileName::Real(PathBuf::from(
- "tests/mod-resolver/issue-4874/foo/qux.rs",
- ))));
+ for exp_file in exp_misformatted_files {
+ assert!(errors_by_file.contains_key(&FileName::Real(PathBuf::from(exp_file))));
+ }
+}
+
+#[test]
+fn nested_out_of_line_mods_loaded() {
+ // See also https://github.com/rust-lang/rustfmt/issues/4874
+ verify_mod_resolution(
+ "tests/mod-resolver/issue-4874/main.rs",
+ &[
+ "tests/mod-resolver/issue-4874/bar/baz.rs",
+ "tests/mod-resolver/issue-4874/foo/qux.rs",
+ ],
+ );
+}
+
+#[test]
+fn out_of_line_nested_inline_within_out_of_line() {
+ // See also https://github.com/rust-lang/rustfmt/issues/5063
+ verify_mod_resolution(
+ "tests/mod-resolver/issue-5063/main.rs",
+ &[
+ "tests/mod-resolver/issue-5063/foo/bar/baz.rs",
+ "tests/mod-resolver/issue-5063/foo.rs",
+ ],
+ );
}
result = combine_strs_with_missing_comments(
context,
result.trim_end(),
- &mt.ty.rewrite(&context, shape)?,
+ &mt.ty.rewrite(context, shape)?,
before_ty_span,
shape,
true,
let budget = shape.width.checked_sub(used_width)?;
let ty_str = mt
.ty
- .rewrite(&context, Shape::legacy(budget, shape.indent + used_width))?;
+ .rewrite(context, Shape::legacy(budget, shape.indent + used_width))?;
result.push_str(&ty_str);
}
(
VisibilityKind::Restricted { path: p, .. },
VisibilityKind::Restricted { path: q, .. },
- ) => pprust::path_to_string(&p) == pprust::path_to_string(&q),
+ ) => pprust::path_to_string(p) == pprust::path_to_string(q),
(VisibilityKind::Public, VisibilityKind::Public)
| (VisibilityKind::Inherited, VisibilityKind::Inherited)
| (
#[test]
fn test_remove_trailing_white_spaces() {
let s = " r#\"\n test\n \"#";
- assert_eq!(remove_trailing_white_spaces(&s), s);
+ assert_eq!(remove_trailing_white_spaces(s), s);
}
#[test]
let config = Config::default();
let indent = Indent::new(4, 0);
assert_eq!(
- trim_left_preserve_layout(&s, indent, &config),
+ trim_left_preserve_layout(s, indent, &config),
Some("aaa\n bbb\n ccc".to_string())
);
}
use crate::coverage::transform_missing_snippet;
use crate::items::{
format_impl, format_trait, format_trait_alias, is_mod_decl, is_use_item, rewrite_extern_crate,
- rewrite_impl_type, rewrite_opaque_type, rewrite_type, FnBraceStyle, FnSig, StaticParts,
- StructParts,
+ rewrite_type_alias, FnBraceStyle, FnSig, ItemVisitorKind, StaticParts, StructParts,
};
use crate::macros::{macro_style, rewrite_macro, rewrite_macro_def, MacroPosition};
use crate::modules::Module;
);
} else {
let shape = self.shape();
- let rewrite = self.with_context(|ctx| stmt.rewrite(&ctx, shape));
+ let rewrite = self.with_context(|ctx| stmt.rewrite(ctx, shape));
self.push_rewrite(stmt.span(), rewrite)
}
}
let comment_snippet = self.snippet(span);
- let align_to_right = if unindent_comment && contains_comment(&comment_snippet) {
+ let align_to_right = if unindent_comment && contains_comment(comment_snippet) {
let first_lines = comment_snippet.splitn(2, '/').next().unwrap_or("");
- last_line_width(first_lines) > last_line_width(&comment_snippet)
+ last_line_width(first_lines) > last_line_width(comment_snippet)
} else {
false
};
let filtered_attrs;
let mut attrs = &item.attrs;
let skip_context_saved = self.skip_context.clone();
- self.skip_context.update_with_attrs(&attrs);
+ self.skip_context.update_with_attrs(attrs);
let should_visit_node_again = match item.kind {
// For use/extern crate items, skip rewriting attributes but check for a skip attribute.
ast::ItemKind::Use(ref tree) => self.format_import(item, tree),
ast::ItemKind::Impl { .. } => {
let block_indent = self.block_indent;
- let rw = self.with_context(|ctx| format_impl(&ctx, item, block_indent));
+ let rw = self.with_context(|ctx| format_impl(ctx, item, block_indent));
self.push_rewrite(item.span, rw);
}
ast::ItemKind::Trait(..) => {
let block_indent = self.block_indent;
- let rw = self.with_context(|ctx| format_trait(&ctx, item, block_indent));
+ let rw = self.with_context(|ctx| format_trait(ctx, item, block_indent));
self.push_rewrite(item.span, rw);
}
ast::ItemKind::TraitAlias(ref generics, ref generic_bounds) => {
self.visit_static(&StaticParts::from_item(item));
}
ast::ItemKind::Fn(ref fn_kind) => {
- let ast::FnKind(defaultness, ref fn_signature, ref generics, ref block) =
- **fn_kind;
- if let Some(ref body) = block {
+ let ast::Fn {
+ defaultness,
+ ref sig,
+ ref generics,
+ ref body,
+ } = **fn_kind;
+ if let Some(ref body) = body {
let inner_attrs = inner_attributes(&item.attrs);
- let fn_ctxt = match fn_signature.header.ext {
+ let fn_ctxt = match sig.header.ext {
ast::Extern::None => visit::FnCtxt::Free,
_ => visit::FnCtxt::Foreign,
};
self.visit_fn(
- visit::FnKind::Fn(
- fn_ctxt,
- item.ident,
- &fn_signature,
- &item.vis,
- Some(body),
- ),
+ visit::FnKind::Fn(fn_ctxt, item.ident, &sig, &item.vis, Some(body)),
generics,
- &fn_signature.decl,
+ &sig.decl,
item.span,
defaultness,
Some(&inner_attrs),
} else {
let indent = self.block_indent;
let rewrite = self.rewrite_required_fn(
- indent,
- item.ident,
- &fn_signature,
- &item.vis,
- generics,
- item.span,
+ indent, item.ident, &sig, &item.vis, generics, item.span,
);
self.push_rewrite(item.span, rewrite);
}
}
- ast::ItemKind::TyAlias(ref alias_kind) => {
- let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref ty) =
- **alias_kind;
- match ty {
- Some(ty) => {
- let rewrite = rewrite_type(
- &self.get_context(),
- self.block_indent,
- item.ident,
- &item.vis,
- generics,
- Some(generic_bounds),
- Some(&*ty),
- item.span,
- );
- self.push_rewrite(item.span, rewrite);
- }
- None => {
- let rewrite = rewrite_opaque_type(
- &self.get_context(),
- self.block_indent,
- item.ident,
- generic_bounds,
- generics,
- &item.vis,
- item.span,
- );
- self.push_rewrite(item.span, rewrite);
- }
- }
+ ast::ItemKind::TyAlias(ref ty_alias) => {
+ use ItemVisitorKind::Item;
+ self.visit_ty_alias_kind(ty_alias, &Item(&item), item.span);
}
ast::ItemKind::GlobalAsm(..) => {
let snippet = Some(self.snippet(item.span).to_owned());
self.skip_context = skip_context_saved;
}
- pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
- skip_out_of_file_lines_range_visitor!(self, ti.span);
+ fn visit_ty_alias_kind(
+ &mut self,
+ ty_kind: &ast::TyAlias,
+ visitor_kind: &ItemVisitorKind<'_>,
+ span: Span,
+ ) {
+ let rewrite = rewrite_type_alias(
+ ty_kind,
+ &self.get_context(),
+ self.block_indent,
+ visitor_kind,
+ span,
+ );
+ self.push_rewrite(span, rewrite);
+ }
+
+ fn visit_assoc_item(&mut self, visitor_kind: &ItemVisitorKind<'_>) {
+ use ItemVisitorKind::*;
+ // TODO(calebcartwright): Not sure the skip spans are correct
+ let (ai, skip_span, assoc_ctxt) = match visitor_kind {
+ AssocTraitItem(ai) => (*ai, ai.span(), visit::AssocCtxt::Trait),
+ AssocImplItem(ai) => (*ai, ai.span, visit::AssocCtxt::Impl),
+ _ => unreachable!(),
+ };
+ skip_out_of_file_lines_range_visitor!(self, ai.span);
- if self.visit_attrs(&ti.attrs, ast::AttrStyle::Outer) {
- self.push_skipped_with_span(ti.attrs.as_slice(), ti.span(), ti.span());
+ if self.visit_attrs(&ai.attrs, ast::AttrStyle::Outer) {
+ self.push_skipped_with_span(&ai.attrs.as_slice(), skip_span, skip_span);
return;
}
// TODO(calebcartwright): consider enabling box_patterns feature gate
- match ti.kind {
- ast::AssocItemKind::Const(..) => self.visit_static(&StaticParts::from_trait_item(ti)),
- ast::AssocItemKind::Fn(ref fn_kind) => {
- let ast::FnKind(defaultness, ref sig, ref generics, ref block) = **fn_kind;
- if let Some(ref body) = block {
- let inner_attrs = inner_attributes(&ti.attrs);
- let fn_ctxt = visit::FnCtxt::Assoc(visit::AssocCtxt::Trait);
+ match (&ai.kind, visitor_kind) {
+ (ast::AssocItemKind::Const(..), AssocTraitItem(_)) => {
+ self.visit_static(&StaticParts::from_trait_item(&ai))
+ }
+ (ast::AssocItemKind::Const(..), AssocImplItem(_)) => {
+ self.visit_static(&StaticParts::from_impl_item(&ai))
+ }
+ (ast::AssocItemKind::Fn(ref fn_kind), _) => {
+ let ast::Fn {
+ defaultness,
+ ref sig,
+ ref generics,
+ ref body,
+ } = **fn_kind;
+ if let Some(ref body) = body {
+ let inner_attrs = inner_attributes(&ai.attrs);
+ let fn_ctxt = visit::FnCtxt::Assoc(assoc_ctxt);
self.visit_fn(
- visit::FnKind::Fn(fn_ctxt, ti.ident, sig, &ti.vis, Some(body)),
+ visit::FnKind::Fn(fn_ctxt, ai.ident, sig, &ai.vis, Some(body)),
generics,
&sig.decl,
- ti.span,
+ ai.span,
defaultness,
Some(&inner_attrs),
);
} else {
let indent = self.block_indent;
let rewrite =
- self.rewrite_required_fn(indent, ti.ident, sig, &ti.vis, generics, ti.span);
- self.push_rewrite(ti.span, rewrite);
+ self.rewrite_required_fn(indent, ai.ident, sig, &ai.vis, generics, ai.span);
+ self.push_rewrite(ai.span, rewrite);
}
}
- ast::AssocItemKind::TyAlias(ref ty_alias_kind) => {
- let ast::TyAliasKind(_, ref generics, ref generic_bounds, ref type_default) =
- **ty_alias_kind;
- let rewrite = rewrite_type(
- &self.get_context(),
- self.block_indent,
- ti.ident,
- &ti.vis,
- generics,
- Some(generic_bounds),
- type_default.as_ref(),
- ti.span,
- );
- self.push_rewrite(ti.span, rewrite);
+ (ast::AssocItemKind::TyAlias(ref ty_alias), _) => {
+ self.visit_ty_alias_kind(ty_alias, visitor_kind, ai.span);
}
- ast::AssocItemKind::MacCall(ref mac) => {
- self.visit_mac(mac, Some(ti.ident), MacroPosition::Item);
+ (ast::AssocItemKind::MacCall(ref mac), _) => {
+ self.visit_mac(mac, Some(ai.ident), MacroPosition::Item);
}
+ _ => unreachable!(),
}
}
- pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
- skip_out_of_file_lines_range_visitor!(self, ii.span);
-
- if self.visit_attrs(&ii.attrs, ast::AttrStyle::Outer) {
- self.push_skipped_with_span(ii.attrs.as_slice(), ii.span, ii.span);
- return;
- }
+ pub(crate) fn visit_trait_item(&mut self, ti: &ast::AssocItem) {
+ self.visit_assoc_item(&ItemVisitorKind::AssocTraitItem(ti));
+ }
- match ii.kind {
- ast::AssocItemKind::Fn(ref fn_kind) => {
- let ast::FnKind(defaultness, ref sig, ref generics, ref block) = **fn_kind;
- if let Some(ref body) = block {
- let inner_attrs = inner_attributes(&ii.attrs);
- let fn_ctxt = visit::FnCtxt::Assoc(visit::AssocCtxt::Impl);
- self.visit_fn(
- visit::FnKind::Fn(fn_ctxt, ii.ident, sig, &ii.vis, Some(body)),
- generics,
- &sig.decl,
- ii.span,
- defaultness,
- Some(&inner_attrs),
- );
- } else {
- let indent = self.block_indent;
- let rewrite =
- self.rewrite_required_fn(indent, ii.ident, sig, &ii.vis, generics, ii.span);
- self.push_rewrite(ii.span, rewrite);
- }
- }
- ast::AssocItemKind::Const(..) => self.visit_static(&StaticParts::from_impl_item(ii)),
- ast::AssocItemKind::TyAlias(ref ty_alias_kind) => {
- let ast::TyAliasKind(defaultness, ref generics, _, ref ty) = **ty_alias_kind;
- self.push_rewrite(
- ii.span,
- rewrite_impl_type(
- ii.ident,
- &ii.vis,
- defaultness,
- ty.as_ref(),
- &generics,
- &self.get_context(),
- self.block_indent,
- ii.span,
- ),
- );
- }
- ast::AssocItemKind::MacCall(ref mac) => {
- self.visit_mac(mac, Some(ii.ident), MacroPosition::Item);
- }
- }
+ pub(crate) fn visit_impl_item(&mut self, ii: &ast::AssocItem) {
+ self.visit_assoc_item(&ItemVisitorKind::AssocImplItem(ii));
}
fn visit_mac(&mut self, mac: &ast::MacCall, ident: Option<symbol::Ident>, pos: MacroPosition) {
}
fn walk_mod_items(&mut self, items: &[rustc_ast::ptr::P<ast::Item>]) {
- self.visit_items_with_reordering(&ptr_vec_to_ref_vec(&items));
+ self.visit_items_with_reordering(&ptr_vec_to_ref_vec(items));
}
fn walk_stmts(&mut self, stmts: &[Stmt<'_>], include_current_empty_semi: bool) {
--- /dev/null
+mod bar {
+ mod baz;}
\ No newline at end of file
--- /dev/null
+fn baz() { }
\ No newline at end of file
--- /dev/null
+fn main() {
+ println!("Hello, world!");
+}
+
+mod foo;
\ No newline at end of file
--- /dev/null
+// rustfmt-group_imports: One
+// rustfmt-imports_granularity: Crate
+use chrono::Utc;
+use super::update::convert_publish_payload;
+
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+use alloc::alloc::Layout;
+
+use std::sync::Arc;
+use alloc::vec::Vec;
+
+use broker::database::PooledConnection;
+
+use super::schema::{Context, Payload};
+use core::f32;
+use crate::models::Event;
--- /dev/null
+// rustfmt-group_imports: One
+mod test {
+ use crate::foo::bar;
+
+ use std::path;
+ use crate::foo::bar2;
+}
--- /dev/null
+// rustfmt-group_imports: One
+// rustfmt-reorder_imports: false
+use chrono::Utc;
+use super::update::convert_publish_payload;
+
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+use alloc::alloc::Layout;
+
+use std::sync::Arc;
+
+use broker::database::PooledConnection;
+
+use super::schema::{Context, Payload};
+use core::f32;
+use crate::models::Event;
--- /dev/null
+// rustfmt-group_imports: One
+use chrono::Utc;
+use super::update::convert_publish_payload;
+
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+use alloc::alloc::Layout;
+
+use std::sync::Arc;
+
+use broker::database::PooledConnection;
+
+use super::schema::{Context, Payload};
+use core::f32;
+use crate::models::Event;
--- /dev/null
+// rustfmt-brace_style: AlwaysNextLine
+// rustfmt-empty_item_single_line: false
+
+fn function()
+{
+
+}
+
+struct Struct
+{
+
+}
+
+enum Enum
+{
+
+}
+
+trait Trait
+{
+
+}
+
+impl<T> Trait for T
+{
+
+}
+
+trait Trait2<T>
+where
+ T: Copy + Display + Write + Read + FromStr, {}
+
+trait Trait3<T>
+where
+ T: Something
+ + SomethingElse
+ + Sync
+ + Send
+ + Display
+ + Debug
+ + Copy
+ + Hash
+ + Debug
+ + Display
+ + Write
+ + Read, {}
struct D<T> where T: Copy {}
}
+
+
+fn function()
+{
+
+}
+
+trait Trait
+{
+
+}
+
+impl<T> Trait for T
+{
+
+}
+
+trait Trait2<T>
+where
+ T: Copy + Display + Write + Read + FromStr, {}
+
+trait Trait3<T>
+where
+ T: Something
+ + SomethingElse
+ + Sync
+ + Send
+ + Display
+ + Debug
+ + Copy
+ + Hash
+ + Debug
+ + Display
+ + Write
+ + Read, {}
--- /dev/null
+// rustfmt-group_imports: One
+// rustfmt-imports_granularity: Crate
+use super::{
+ schema::{Context, Payload},
+ update::convert_publish_payload,
+};
+use crate::models::Event;
+use alloc::{alloc::Layout, vec::Vec};
+use broker::database::PooledConnection;
+use chrono::Utc;
+use core::f32;
+use juniper::{FieldError, FieldResult};
+use std::sync::Arc;
+use uuid::Uuid;
--- /dev/null
+// rustfmt-group_imports: One
+mod test {
+ use crate::foo::bar;
+ use crate::foo::bar2;
+ use std::path;
+}
--- /dev/null
+// rustfmt-group_imports: One
+// rustfmt-reorder_imports: false
+use chrono::Utc;
+use super::update::convert_publish_payload;
+use juniper::{FieldError, FieldResult};
+use uuid::Uuid;
+use alloc::alloc::Layout;
+use std::sync::Arc;
+use broker::database::PooledConnection;
+use super::schema::{Context, Payload};
+use core::f32;
+use crate::models::Event;
--- /dev/null
+// rustfmt-group_imports: One
+use super::schema::{Context, Payload};
+use super::update::convert_publish_payload;
+use crate::models::Event;
+use alloc::alloc::Layout;
+use broker::database::PooledConnection;
+use chrono::Utc;
+use core::f32;
+use juniper::{FieldError, FieldResult};
+use std::sync::Arc;
+use uuid::Uuid;
--- /dev/null
+// rustfmt-brace_style: AlwaysNextLine
+// rustfmt-empty_item_single_line: false
+
+fn function()
+{
+}
+
+struct Struct {}
+
+enum Enum {}
+
+trait Trait
+{
+}
+
+impl<T> Trait for T
+{
+}
+
+trait Trait2<T>
+where
+ T: Copy + Display + Write + Read + FromStr,
+{
+}
+
+trait Trait3<T>
+where
+ T: Something
+ + SomethingElse
+ + Sync
+ + Send
+ + Display
+ + Debug
+ + Copy
+ + Hash
+ + Debug
+ + Display
+ + Write
+ + Read,
+{
+}
--- /dev/null
+// rustfmt-trailing_comma: Always
+
+pub struct Matrix<T, const R: usize, const C: usize,>
+where
+ [T; R * C]:,
+{
+ contents: [T; R * C],
+}
--- /dev/null
+// rustfmt-trailing_comma: Never
+
+pub struct Matrix<T, const R: usize, const C: usize>
+where
+ [T; R * C]:
+{
+ contents: [T; R * C]
+}
--- /dev/null
+// leading comment
+
+#![rustfmt::skip]
+fn main() {
+ println!("main"); // commented
+}
+
+// post comment
--- /dev/null
+#![rustfmt::skip]
+
+mod a {
+ mod b {
+
+ }
+
+ // trailing comment b
+}
+
+// trailing comment a
--- /dev/null
+impl ThisIsALongStructNameToPushTheWhereToWrapLolololol where
+ [(); this_is_a_long_const_function_name()]:
+{
+}
where
T: Copy, {}
}
+
+fn function() {}
+
+trait Trait {}
+
+impl<T> Trait for T {}
+
+trait Trait2<T>
+where
+ T: Copy + Display + Write + Read + FromStr,
+{
+}
+
+trait Trait3<T>
+where
+ T: Something
+ + SomethingElse
+ + Sync
+ + Send
+ + Display
+ + Debug
+ + Copy
+ + Hash
+ + Debug
+ + Display
+ + Write
+ + Read,
+{
+}
const ENTRY_LIMIT: usize = 1000;
// FIXME: The following limits should be reduced eventually.
-const ROOT_ENTRY_LIMIT: usize = 1331;
-const ISSUES_ENTRY_LIMIT: usize = 2488;
+const ROOT_ENTRY_LIMIT: usize = 1275;
+const ISSUES_ENTRY_LIMIT: usize = 2310;
fn check_entries(path: &Path, bad: &mut bool) {
let dirs = walkdir::WalkDir::new(&path.join("test/ui"))