From 274b7e49e0fb9bb896386fd051e70090a2c8761d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Fri, 24 May 2019 18:23:43 -0700 Subject: [PATCH 01/12] Suggest borrowing for loop head on move error --- .../borrow_check/conflict_errors.rs | 24 +++++++++---------- src/test/ui/issues/issue-61108.rs | 7 ++++++ src/test/ui/issues/issue-61108.stderr | 17 +++++++++++++ .../suggestions/borrow-for-loop-head.stderr | 9 ++++--- 4 files changed, 39 insertions(+), 18 deletions(-) create mode 100644 src/test/ui/issues/issue-61108.rs create mode 100644 src/test/ui/issues/issue-61108.stderr diff --git a/src/librustc_mir/borrow_check/conflict_errors.rs b/src/librustc_mir/borrow_check/conflict_errors.rs index b00a75bb56968..4ff6fa829ffb3 100644 --- a/src/librustc_mir/borrow_check/conflict_errors.rs +++ b/src/librustc_mir/borrow_check/conflict_errors.rs @@ -158,18 +158,6 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { span, format!("value moved{} here, in previous iteration of loop", move_msg), ); - if Some(CompilerDesugaringKind::ForLoop) == span.compiler_desugaring_kind() { - if let Ok(snippet) = self.infcx.tcx.sess.source_map() - .span_to_snippet(span) - { - err.span_suggestion( - move_span, - "consider borrowing this to avoid moving it into the for loop", - format!("&{}", snippet), - Applicability::MaybeIncorrect, - ); - } - } is_loop_move = true; } else if move_site.traversed_back_edge { err.span_label( @@ -185,7 +173,17 @@ impl<'cx, 'gcx, 'tcx> MirBorrowckCtxt<'cx, 'gcx, 'tcx> { &mut err, format!("variable moved due to use{}", move_spans.describe()), ); - }; + } + if Some(CompilerDesugaringKind::ForLoop) == move_span.compiler_desugaring_kind() { + if let Ok(snippet) = self.infcx.tcx.sess.source_map().span_to_snippet(span) { + err.span_suggestion( + move_span, + "consider borrowing to avoid moving into the for loop", + format!("&{}", snippet), + Applicability::MaybeIncorrect, + ); + } + } } use_spans.var_span_label( diff --git a/src/test/ui/issues/issue-61108.rs b/src/test/ui/issues/issue-61108.rs new file mode 100644 index 0000000000000..0a883b9581835 --- /dev/null +++ b/src/test/ui/issues/issue-61108.rs @@ -0,0 +1,7 @@ +fn main() { + let mut bad_letters = vec!['e', 't', 'o', 'i']; + for l in bad_letters { + // something here + } + bad_letters.push('s'); //~ ERROR borrow of moved value: `bad_letters` +} diff --git a/src/test/ui/issues/issue-61108.stderr b/src/test/ui/issues/issue-61108.stderr new file mode 100644 index 0000000000000..8523a6f6548a6 --- /dev/null +++ b/src/test/ui/issues/issue-61108.stderr @@ -0,0 +1,17 @@ +error[E0382]: borrow of moved value: `bad_letters` + --> $DIR/issue-61108.rs:6:5 + | +LL | let mut bad_letters = vec!['e', 't', 'o', 'i']; + | --------------- move occurs because `bad_letters` has type `std::vec::Vec`, which does not implement the `Copy` trait +LL | for l in bad_letters { + | ----------- + | | + | value moved here + | help: consider borrowing to avoid moving into the for loop: `&bad_letters` +... +LL | bad_letters.push('s'); + | ^^^^^^^^^^^ value borrowed here after move + +error: aborting due to previous error + +For more information about this error, try `rustc --explain E0382`. diff --git a/src/test/ui/suggestions/borrow-for-loop-head.stderr b/src/test/ui/suggestions/borrow-for-loop-head.stderr index 10287f59ccec9..36bced9e4332b 100644 --- a/src/test/ui/suggestions/borrow-for-loop-head.stderr +++ b/src/test/ui/suggestions/borrow-for-loop-head.stderr @@ -13,11 +13,10 @@ LL | let a = vec![1, 2, 3]; | - move occurs because `a` has type `std::vec::Vec`, which does not implement the `Copy` trait LL | for i in &a { LL | for j in a { - | ^ value moved here, in previous iteration of loop -help: consider borrowing this to avoid moving it into the for loop - | -LL | for j in &a { - | ^^ + | ^ + | | + | value moved here, in previous iteration of loop + | help: consider borrowing to avoid moving into the for loop: `&a` error: aborting due to 2 previous errors From 0b7d4fa4a84653f81ed63f8491dd8cc1dd67037e Mon Sep 17 00:00:00 2001 From: Andrew Xu Date: Sun, 19 May 2019 16:26:08 +0800 Subject: [PATCH 02/12] Rename "Associated*" to "Assoc*" We are going to uniform the terminology of all associated items. Methods that may or may not have `self` are called "associated functions". Because `AssociatedFn` is a bit long, we rename `Associated` to `Assoc`. --- src/librustc/hir/def.rs | 18 ++-- src/librustc/hir/intravisit.rs | 4 +- src/librustc/hir/lowering.rs | 20 ++-- src/librustc/hir/map/mod.rs | 10 +- src/librustc/hir/mod.rs | 6 +- src/librustc/middle/dead.rs | 2 +- src/librustc/middle/expr_use_visitor.rs | 2 +- src/librustc/middle/mem_categorization.rs | 2 +- src/librustc/middle/reachable.rs | 2 +- src/librustc/middle/resolve_lifetime.rs | 4 +- src/librustc/middle/stability.rs | 4 +- src/librustc/query/mod.rs | 2 +- src/librustc/traits/mod.rs | 2 +- src/librustc/traits/object_safety.rs | 20 ++-- src/librustc/traits/project.rs | 24 ++--- src/librustc/traits/specialize/mod.rs | 2 +- .../traits/specialize/specialization_graph.rs | 8 +- src/librustc/traits/util.rs | 6 +- src/librustc/ty/adjustment.rs | 2 +- src/librustc/ty/instance.rs | 4 +- src/librustc/ty/mod.rs | 94 +++++++++---------- src/librustc/ty/sty.rs | 2 +- src/librustc_metadata/cstore_impl.rs | 2 +- src/librustc_metadata/decoder.rs | 32 +++---- src/librustc_metadata/encoder.rs | 40 ++++---- src/librustc_metadata/schema.rs | 32 +++---- src/librustc_mir/const_eval.rs | 2 +- src/librustc_mir/hair/cx/expr.rs | 4 +- src/librustc_mir/hair/cx/mod.rs | 2 +- src/librustc_mir/hair/pattern/check_match.rs | 2 +- src/librustc_mir/hair/pattern/mod.rs | 10 +- src/librustc_mir/interpret/eval_context.rs | 2 +- src/librustc_mir/lints.rs | 6 +- src/librustc_mir/monomorphize/mod.rs | 2 +- src/librustc_mir/shim.rs | 2 +- src/librustc_mir/transform/const_prop.rs | 2 +- src/librustc_mir/util/pretty.rs | 2 +- src/librustc_passes/rvalue_promotion.rs | 2 +- src/librustc_privacy/lib.rs | 22 ++--- src/librustc_resolve/build_reduced_graph.rs | 6 +- src/librustc_resolve/diagnostics.rs | 2 +- src/librustc_resolve/lib.rs | 16 ++-- src/librustc_save_analysis/dump_visitor.rs | 4 +- src/librustc_save_analysis/lib.rs | 6 +- src/librustc_save_analysis/sig.rs | 2 +- src/librustc_traits/lowering/mod.rs | 14 +-- src/librustc_typeck/astconv.rs | 14 +-- src/librustc_typeck/check/_match.rs | 6 +- src/librustc_typeck/check/compare_method.rs | 38 ++++---- src/librustc_typeck/check/demand.rs | 8 +- src/librustc_typeck/check/method/mod.rs | 6 +- src/librustc_typeck/check/method/probe.rs | 32 +++---- src/librustc_typeck/check/mod.rs | 20 ++-- src/librustc_typeck/check/wfcheck.rs | 10 +- src/librustc_typeck/impl_wf_check.rs | 2 +- src/librustc_typeck/namespace.rs | 12 +-- src/librustdoc/clean/mod.rs | 32 +++---- src/librustdoc/html/format.rs | 2 +- src/librustdoc/html/item_type.rs | 16 ++-- src/librustdoc/html/render.rs | 24 ++--- .../passes/collect_intra_doc_links.rs | 16 ++-- src/librustdoc/passes/mod.rs | 4 +- 62 files changed, 349 insertions(+), 349 deletions(-) diff --git a/src/librustc/hir/def.rs b/src/librustc/hir/def.rs index 91256385232a9..03f24dbb29025 100644 --- a/src/librustc/hir/def.rs +++ b/src/librustc/hir/def.rs @@ -61,9 +61,9 @@ pub enum DefKind { TyAlias, ForeignTy, TraitAlias, - AssociatedTy, + AssocTy, /// `existential type Foo: Bar;` - AssociatedExistential, + AssocExistential, TyParam, // Value namespace @@ -74,7 +74,7 @@ pub enum DefKind { /// Refers to the struct or enum variant's constructor. Ctor(CtorOf, CtorKind), Method, - AssociatedConst, + AssocConst, // Macro namespace Macro(MacroKind), @@ -99,14 +99,14 @@ impl DefKind { DefKind::Existential => "existential type", DefKind::TyAlias => "type alias", DefKind::TraitAlias => "trait alias", - DefKind::AssociatedTy => "associated type", - DefKind::AssociatedExistential => "associated existential type", + DefKind::AssocTy => "associated type", + DefKind::AssocExistential => "associated existential type", DefKind::Union => "union", DefKind::Trait => "trait", DefKind::ForeignTy => "foreign type", DefKind::Method => "method", DefKind::Const => "constant", - DefKind::AssociatedConst => "associated constant", + DefKind::AssocConst => "associated constant", DefKind::TyParam => "type parameter", DefKind::ConstParam => "const parameter", DefKind::Macro(macro_kind) => macro_kind.descr(), @@ -116,9 +116,9 @@ impl DefKind { /// An English article for the def. pub fn article(&self) -> &'static str { match *self { - DefKind::AssociatedTy - | DefKind::AssociatedConst - | DefKind::AssociatedExistential + DefKind::AssocTy + | DefKind::AssocConst + | DefKind::AssocExistential | DefKind::Enum | DefKind::Existential => "an", DefKind::Macro(macro_kind) => macro_kind.article(), diff --git a/src/librustc/hir/intravisit.rs b/src/librustc/hir/intravisit.rs index 517c99f99efea..8000666044a1a 100644 --- a/src/librustc/hir/intravisit.rs +++ b/src/librustc/hir/intravisit.rs @@ -370,7 +370,7 @@ pub trait Visitor<'v> : Sized { fn visit_vis(&mut self, vis: &'v Visibility) { walk_vis(self, vis) } - fn visit_associated_item_kind(&mut self, kind: &'v AssociatedItemKind) { + fn visit_associated_item_kind(&mut self, kind: &'v AssocItemKind) { walk_associated_item_kind(self, kind); } fn visit_defaultness(&mut self, defaultness: &'v Defaultness) { @@ -1120,7 +1120,7 @@ pub fn walk_vis<'v, V: Visitor<'v>>(visitor: &mut V, vis: &'v Visibility) { } } -pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssociatedItemKind) { +pub fn walk_associated_item_kind<'v, V: Visitor<'v>>(_: &mut V, _: &'v AssocItemKind) { // No visitable content here: this fn exists so you can call it if // the right thing to do, should content be added in the future, // would be to walk it. diff --git a/src/librustc/hir/lowering.rs b/src/librustc/hir/lowering.rs index 3d83918bd0a66..bed53355f4cd2 100644 --- a/src/librustc/hir/lowering.rs +++ b/src/librustc/hir/lowering.rs @@ -1862,7 +1862,7 @@ impl<'a> LoweringContext<'a> { index: this.def_key(def_id).parent.expect("missing parent"), }; let type_def_id = match partial_res.base_res() { - Res::Def(DefKind::AssociatedTy, def_id) if i + 2 == proj_start => { + Res::Def(DefKind::AssocTy, def_id) if i + 2 == proj_start => { Some(parent_def_id(self, def_id)) } Res::Def(DefKind::Variant, def_id) if i + 1 == proj_start => { @@ -1884,8 +1884,8 @@ impl<'a> LoweringContext<'a> { if i + 1 == proj_start => ParenthesizedGenericArgs::Ok, // `a::b::Trait(Args)::TraitItem` Res::Def(DefKind::Method, _) - | Res::Def(DefKind::AssociatedConst, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocConst, _) + | Res::Def(DefKind::AssocTy, _) if i + 2 == proj_start => { ParenthesizedGenericArgs::Ok @@ -3591,13 +3591,13 @@ impl<'a> LoweringContext<'a> { fn lower_trait_item_ref(&mut self, i: &TraitItem) -> hir::TraitItemRef { let (kind, has_default) = match i.node { TraitItemKind::Const(_, ref default) => { - (hir::AssociatedItemKind::Const, default.is_some()) + (hir::AssocItemKind::Const, default.is_some()) } TraitItemKind::Type(_, ref default) => { - (hir::AssociatedItemKind::Type, default.is_some()) + (hir::AssocItemKind::Type, default.is_some()) } TraitItemKind::Method(ref sig, ref default) => ( - hir::AssociatedItemKind::Method { + hir::AssocItemKind::Method { has_self: sig.decl.has_self(), }, default.is_some(), @@ -3697,10 +3697,10 @@ impl<'a> LoweringContext<'a> { vis: self.lower_visibility(&i.vis, Some(i.id)), defaultness: self.lower_defaultness(i.defaultness, true /* [1] */), kind: match i.node { - ImplItemKind::Const(..) => hir::AssociatedItemKind::Const, - ImplItemKind::Type(..) => hir::AssociatedItemKind::Type, - ImplItemKind::Existential(..) => hir::AssociatedItemKind::Existential, - ImplItemKind::Method(ref sig, _) => hir::AssociatedItemKind::Method { + ImplItemKind::Const(..) => hir::AssocItemKind::Const, + ImplItemKind::Type(..) => hir::AssocItemKind::Type, + ImplItemKind::Existential(..) => hir::AssocItemKind::Existential, + ImplItemKind::Method(ref sig, _) => hir::AssocItemKind::Method { has_self: sig.decl.has_self(), }, ImplItemKind::Macro(..) => unimplemented!(), diff --git a/src/librustc/hir/map/mod.rs b/src/librustc/hir/map/mod.rs index 0741d9322c653..fd42c6f469e1e 100644 --- a/src/librustc/hir/map/mod.rs +++ b/src/librustc/hir/map/mod.rs @@ -337,17 +337,17 @@ impl<'hir> Map<'hir> { } Node::TraitItem(item) => { match item.node { - TraitItemKind::Const(..) => DefKind::AssociatedConst, + TraitItemKind::Const(..) => DefKind::AssocConst, TraitItemKind::Method(..) => DefKind::Method, - TraitItemKind::Type(..) => DefKind::AssociatedTy, + TraitItemKind::Type(..) => DefKind::AssocTy, } } Node::ImplItem(item) => { match item.node { - ImplItemKind::Const(..) => DefKind::AssociatedConst, + ImplItemKind::Const(..) => DefKind::AssocConst, ImplItemKind::Method(..) => DefKind::Method, - ImplItemKind::Type(..) => DefKind::AssociatedTy, - ImplItemKind::Existential(..) => DefKind::AssociatedExistential, + ImplItemKind::Type(..) => DefKind::AssocTy, + ImplItemKind::Existential(..) => DefKind::AssocExistential, } } Node::Variant(_) => DefKind::Variant, diff --git a/src/librustc/hir/mod.rs b/src/librustc/hir/mod.rs index 2ae5f7a0b5531..1a6f5d3733e7a 100644 --- a/src/librustc/hir/mod.rs +++ b/src/librustc/hir/mod.rs @@ -2422,7 +2422,7 @@ pub struct TraitItemRef { pub id: TraitItemId, #[stable_hasher(project(name))] pub ident: Ident, - pub kind: AssociatedItemKind, + pub kind: AssocItemKind, pub span: Span, pub defaultness: Defaultness, } @@ -2438,14 +2438,14 @@ pub struct ImplItemRef { pub id: ImplItemId, #[stable_hasher(project(name))] pub ident: Ident, - pub kind: AssociatedItemKind, + pub kind: AssocItemKind, pub span: Span, pub vis: Visibility, pub defaultness: Defaultness, } #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, Debug, HashStable)] -pub enum AssociatedItemKind { +pub enum AssocItemKind { Const, Method { has_self: bool }, Type, diff --git a/src/librustc/middle/dead.rs b/src/librustc/middle/dead.rs index 2a9928567f4dc..14553a972b704 100644 --- a/src/librustc/middle/dead.rs +++ b/src/librustc/middle/dead.rs @@ -72,7 +72,7 @@ impl<'a, 'tcx> MarkSymbolVisitor<'a, 'tcx> { fn handle_res(&mut self, res: Res) { match res { Res::Def(DefKind::Const, _) - | Res::Def(DefKind::AssociatedConst, _) + | Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::TyAlias, _) => { self.check_def_id(res.def_id()); } diff --git a/src/librustc/middle/expr_use_visitor.rs b/src/librustc/middle/expr_use_visitor.rs index d46bba92f3fc9..35b6b76a39567 100644 --- a/src/librustc/middle/expr_use_visitor.rs +++ b/src/librustc/middle/expr_use_visitor.rs @@ -909,7 +909,7 @@ impl<'a, 'gcx, 'tcx> ExprUseVisitor<'a, 'gcx, 'tcx> { | Res::Def(DefKind::Ctor(..), _) | Res::Def(DefKind::Union, _) | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) => { debug!("struct cmt_pat={:?} pat={:?}", cmt_pat, pat); delegate.matched_pat(pat, &cmt_pat, match_mode); diff --git a/src/librustc/middle/mem_categorization.rs b/src/librustc/middle/mem_categorization.rs index c7f8cf684e6b1..184e371b7de75 100644 --- a/src/librustc/middle/mem_categorization.rs +++ b/src/librustc/middle/mem_categorization.rs @@ -703,7 +703,7 @@ impl<'a, 'gcx, 'tcx> MemCategorizationContext<'a, 'gcx, 'tcx> { Res::Def(DefKind::Ctor(..), _) | Res::Def(DefKind::Const, _) | Res::Def(DefKind::ConstParam, _) - | Res::Def(DefKind::AssociatedConst, _) + | Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Fn, _) | Res::Def(DefKind::Method, _) | Res::SelfCtor(..) => { diff --git a/src/librustc/middle/reachable.rs b/src/librustc/middle/reachable.rs index e58083b5b7626..c9835dbd5e78f 100644 --- a/src/librustc/middle/reachable.rs +++ b/src/librustc/middle/reachable.rs @@ -118,7 +118,7 @@ impl<'a, 'tcx> Visitor<'tcx> for ReachableContext<'a, 'tcx> { // If this path leads to a constant, then we need to // recurse into the constant to continue finding // items that are reachable. - Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssociatedConst, _) => { + Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => { self.worklist.push(hir_id); } diff --git a/src/librustc/middle/resolve_lifetime.rs b/src/librustc/middle/resolve_lifetime.rs index 775da1de313fa..736b4633b38f9 100644 --- a/src/librustc/middle/resolve_lifetime.rs +++ b/src/librustc/middle/resolve_lifetime.rs @@ -1924,7 +1924,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { } }; let type_def_id = match res { - Res::Def(DefKind::AssociatedTy, def_id) + Res::Def(DefKind::AssocTy, def_id) if depth == 1 => Some(parent_def_id(self, def_id)), Res::Def(DefKind::Variant, def_id) if depth == 0 => Some(parent_def_id(self, def_id)), @@ -2112,7 +2112,7 @@ impl<'a, 'tcx> LifetimeContext<'a, 'tcx> { }; let has_self = match assoc_item_kind { - Some(hir::AssociatedItemKind::Method { has_self }) => has_self, + Some(hir::AssocItemKind::Method { has_self }) => has_self, _ => false, }; diff --git a/src/librustc/middle/stability.rs b/src/librustc/middle/stability.rs index ac0e99137cbc3..6bc2b25722b1a 100644 --- a/src/librustc/middle/stability.rs +++ b/src/librustc/middle/stability.rs @@ -527,8 +527,8 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // Check if `def_id` is a trait method. match self.def_kind(def_id) { Some(DefKind::Method) | - Some(DefKind::AssociatedTy) | - Some(DefKind::AssociatedConst) => { + Some(DefKind::AssocTy) | + Some(DefKind::AssocConst) => { if let ty::TraitContainer(trait_def_id) = self.associated_item(def_id).container { // Trait methods do not declare visibility (even // for visibility info in cstore). Use containing diff --git a/src/librustc/query/mod.rs b/src/librustc/query/mod.rs index c03cd7e268ef5..ed363800d79de 100644 --- a/src/librustc/query/mod.rs +++ b/src/librustc/query/mod.rs @@ -265,7 +265,7 @@ rustc_queries! { query associated_item_def_ids(_: DefId) -> &'tcx [DefId] {} /// Maps from a trait item to the trait item "descriptor". - query associated_item(_: DefId) -> ty::AssociatedItem {} + query associated_item(_: DefId) -> ty::AssocItem {} query impl_trait_ref(_: DefId) -> Option> {} query impl_polarity(_: DefId) -> hir::ImplPolarity {} diff --git a/src/librustc/traits/mod.rs b/src/librustc/traits/mod.rs index a4b9ed0a206b9..4b555e54f397d 100644 --- a/src/librustc/traits/mod.rs +++ b/src/librustc/traits/mod.rs @@ -993,7 +993,7 @@ fn vtable_methods<'a, 'tcx>( tcx.arena.alloc_from_iter( supertraits(tcx, trait_ref).flat_map(move |trait_ref| { let trait_methods = tcx.associated_items(trait_ref.def_id()) - .filter(|item| item.kind == ty::AssociatedKind::Method); + .filter(|item| item.kind == ty::AssocKind::Method); // Now list each method's DefId and InternalSubsts (for within its trait). // If the method can never be called from this object, produce None. diff --git a/src/librustc/traits/object_safety.rs b/src/librustc/traits/object_safety.rs index 55216f644a180..5006ff75667e8 100644 --- a/src/librustc/traits/object_safety.rs +++ b/src/librustc/traits/object_safety.rs @@ -35,7 +35,7 @@ pub enum ObjectSafetyViolation { Method(ast::Name, MethodViolationCode), /// Associated const. - AssociatedConst(ast::Name), + AssocConst(ast::Name), } impl ObjectSafetyViolation { @@ -58,7 +58,7 @@ impl ObjectSafetyViolation { format!("method `{}` has generic type parameters", name).into(), ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver) => format!("method `{}`'s receiver cannot be dispatched on", name).into(), - ObjectSafetyViolation::AssociatedConst(name) => + ObjectSafetyViolation::AssocConst(name) => format!("the trait cannot contain associated consts like `{}`", name).into(), } } @@ -119,7 +119,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { { // Check methods for violations. let mut violations: Vec<_> = self.associated_items(trait_def_id) - .filter(|item| item.kind == ty::AssociatedKind::Method) + .filter(|item| item.kind == ty::AssocKind::Method) .filter_map(|item| self.object_safety_violation_for_method(trait_def_id, &item) .map(|code| ObjectSafetyViolation::Method(item.ident.name, code)) @@ -151,8 +151,8 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { } violations.extend(self.associated_items(trait_def_id) - .filter(|item| item.kind == ty::AssociatedKind::Const) - .map(|item| ObjectSafetyViolation::AssociatedConst(item.ident.name))); + .filter(|item| item.kind == ty::AssocKind::Const) + .map(|item| ObjectSafetyViolation::AssocConst(item.ident.name))); debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}", trait_def_id, @@ -251,7 +251,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { /// Returns `Some(_)` if this method makes the containing trait not object safe. fn object_safety_violation_for_method(self, trait_def_id: DefId, - method: &ty::AssociatedItem) + method: &ty::AssocItem) -> Option { debug!("object_safety_violation_for_method({:?}, {:?})", trait_def_id, method); @@ -270,7 +270,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { /// otherwise ensure that they cannot be used when `Self=Trait`. pub fn is_vtable_safe_method(self, trait_def_id: DefId, - method: &ty::AssociatedItem) + method: &ty::AssocItem) -> bool { debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method); @@ -291,7 +291,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { /// `Self:Sized`. fn virtual_call_violation_for_method(self, trait_def_id: DefId, - method: &ty::AssociatedItem) + method: &ty::AssocItem) -> Option { // The method's first parameter must be named `self` @@ -439,7 +439,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { self.associated_items(super_trait_ref.def_id()) .map(move |item| (super_trait_ref, item)) }) - .filter(|(_, item)| item.kind == ty::AssociatedKind::Type) + .filter(|(_, item)| item.kind == ty::AssocKind::Type) .collect::>(); // existential predicates need to be in a specific order @@ -520,7 +520,7 @@ impl<'a, 'tcx> TyCtxt<'a, 'tcx, 'tcx> { #[allow(dead_code)] fn receiver_is_dispatchable( self, - method: &ty::AssociatedItem, + method: &ty::AssocItem, receiver_ty: Ty<'tcx>, ) -> bool { debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty); diff --git a/src/librustc/traits/project.rs b/src/librustc/traits/project.rs index 67e76f7625cee..f735f8ee4c8d7 100644 --- a/src/librustc/traits/project.rs +++ b/src/librustc/traits/project.rs @@ -275,7 +275,7 @@ pub fn normalize_with_depth<'a, 'b, 'gcx, 'tcx, T>( where T : TypeFoldable<'tcx> { debug!("normalize_with_depth(depth={}, value={:?})", depth, value); - let mut normalizer = AssociatedTypeNormalizer::new(selcx, param_env, cause, depth); + let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth); let result = normalizer.fold(value); debug!("normalize_with_depth: depth={} result={:?} with {} obligations", depth, result, normalizer.obligations.len()); @@ -287,7 +287,7 @@ pub fn normalize_with_depth<'a, 'b, 'gcx, 'tcx, T>( } } -struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> { +struct AssocTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> { selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>, param_env: ty::ParamEnv<'tcx>, cause: ObligationCause<'tcx>, @@ -295,14 +295,14 @@ struct AssociatedTypeNormalizer<'a, 'b: 'a, 'gcx: 'b+'tcx, 'tcx: 'b> { depth: usize, } -impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> { +impl<'a, 'b, 'gcx, 'tcx> AssocTypeNormalizer<'a, 'b, 'gcx, 'tcx> { fn new(selcx: &'a mut SelectionContext<'b, 'gcx, 'tcx>, param_env: ty::ParamEnv<'tcx>, cause: ObligationCause<'tcx>, depth: usize) - -> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> + -> AssocTypeNormalizer<'a, 'b, 'gcx, 'tcx> { - AssociatedTypeNormalizer { + AssocTypeNormalizer { selcx, param_env, cause, @@ -322,7 +322,7 @@ impl<'a, 'b, 'gcx, 'tcx> AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> { } } -impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssociatedTypeNormalizer<'a, 'b, 'gcx, 'tcx> { +impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssocTypeNormalizer<'a, 'b, 'gcx, 'tcx> { fn tcx<'c>(&'c self) -> TyCtxt<'c, 'gcx, 'tcx> { self.selcx.tcx() } @@ -388,7 +388,7 @@ impl<'a, 'b, 'gcx, 'tcx> TypeFolder<'gcx, 'tcx> for AssociatedTypeNormalizer<'a, self.cause.clone(), self.depth, &mut self.obligations); - debug!("AssociatedTypeNormalizer: depth={} normalized {:?} to {:?}, \ + debug!("AssocTypeNormalizer: depth={} normalized {:?} to {:?}, \ now with {} obligations", self.depth, ty, normalized_ty, self.obligations.len()); normalized_ty @@ -636,7 +636,7 @@ fn opt_normalize_projection_type<'a, 'b, 'gcx, 'tcx>( projected_obligations); let result = if projected_ty.has_projections() { - let mut normalizer = AssociatedTypeNormalizer::new(selcx, + let mut normalizer = AssocTypeNormalizer::new(selcx, param_env, cause, depth+1); @@ -1497,7 +1497,7 @@ fn confirm_impl_candidate<'cx, 'gcx, 'tcx>( }; } let substs = translate_substs(selcx.infcx(), param_env, impl_def_id, substs, assoc_ty.node); - let ty = if let ty::AssociatedKind::Existential = assoc_ty.item.kind { + let ty = if let ty::AssocKind::Existential = assoc_ty.item.kind { let item_substs = InternalSubsts::identity_for_item(tcx, assoc_ty.item.def_id); tcx.mk_opaque(assoc_ty.item.def_id, item_substs) } else { @@ -1518,7 +1518,7 @@ fn assoc_ty_def<'cx, 'gcx, 'tcx>( selcx: &SelectionContext<'cx, 'gcx, 'tcx>, impl_def_id: DefId, assoc_ty_def_id: DefId) - -> specialization_graph::NodeItem + -> specialization_graph::NodeItem { let tcx = selcx.tcx(); let assoc_ty_name = tcx.associated_item(assoc_ty_def_id).ident; @@ -1533,7 +1533,7 @@ fn assoc_ty_def<'cx, 'gcx, 'tcx>( // cycle error if the specialization graph is currently being built. let impl_node = specialization_graph::Node::Impl(impl_def_id); for item in impl_node.items(tcx) { - if item.kind == ty::AssociatedKind::Type && + if item.kind == ty::AssocKind::Type && tcx.hygienic_eq(item.ident, assoc_ty_name, trait_def_id) { return specialization_graph::NodeItem { node: specialization_graph::Node::Impl(impl_def_id), @@ -1544,7 +1544,7 @@ fn assoc_ty_def<'cx, 'gcx, 'tcx>( if let Some(assoc_item) = trait_def .ancestors(tcx, impl_def_id) - .defs(tcx, assoc_ty_name, ty::AssociatedKind::Type, trait_def_id) + .defs(tcx, assoc_ty_name, ty::AssocKind::Type, trait_def_id) .next() { assoc_item } else { diff --git a/src/librustc/traits/specialize/mod.rs b/src/librustc/traits/specialize/mod.rs index fdd1a821e31b5..5da4a1b9c5f36 100644 --- a/src/librustc/traits/specialize/mod.rs +++ b/src/librustc/traits/specialize/mod.rs @@ -112,7 +112,7 @@ pub fn translate_substs<'a, 'gcx, 'tcx>(infcx: &InferCtxt<'a, 'gcx, 'tcx>, pub fn find_associated_item<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, param_env: ty::ParamEnv<'tcx>, - item: &ty::AssociatedItem, + item: &ty::AssocItem, substs: SubstsRef<'tcx>, impl_data: &super::VtableImplData<'tcx, ()>, ) -> (DefId, SubstsRef<'tcx>) { diff --git a/src/librustc/traits/specialize/specialization_graph.rs b/src/librustc/traits/specialize/specialization_graph.rs index dae1518d722db..9a90b9fdaeaaa 100644 --- a/src/librustc/traits/specialize/specialization_graph.rs +++ b/src/librustc/traits/specialize/specialization_graph.rs @@ -426,7 +426,7 @@ impl<'a, 'gcx, 'tcx> Node { pub fn items( &self, tcx: TyCtxt<'a, 'gcx, 'tcx>, - ) -> ty::AssociatedItemsIterator<'a, 'gcx, 'tcx> { + ) -> ty::AssocItemsIterator<'a, 'gcx, 'tcx> { tcx.associated_items(self.def_id()) } @@ -484,11 +484,11 @@ impl<'a, 'gcx, 'tcx> Ancestors<'gcx> { self, tcx: TyCtxt<'a, 'gcx, 'tcx>, trait_item_name: Ident, - trait_item_kind: ty::AssociatedKind, + trait_item_kind: ty::AssocKind, trait_def_id: DefId, - ) -> impl Iterator> + Captures<'gcx> + Captures<'tcx> + 'a { + ) -> impl Iterator> + Captures<'gcx> + Captures<'tcx> + 'a { self.flat_map(move |node| { - use crate::ty::AssociatedKind::*; + use crate::ty::AssocKind::*; node.items(tcx).filter(move |impl_item| match (trait_item_kind, impl_item.kind) { | (Const, Const) | (Method, Method) diff --git a/src/librustc/traits/util.rs b/src/librustc/traits/util.rs index 5ba23a9c45a4f..2f87a743a012c 100644 --- a/src/librustc/traits/util.rs +++ b/src/librustc/traits/util.rs @@ -594,7 +594,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { // Count number of methods and add them to the total offset. // Skip over associated types and constants. for trait_item in self.associated_items(trait_ref.def_id()) { - if trait_item.kind == ty::AssociatedKind::Method { + if trait_item.kind == ty::AssocKind::Method { entries += 1; } } @@ -614,10 +614,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { for trait_item in self.associated_items(object.upcast_trait_ref.def_id()) { if trait_item.def_id == method_def_id { // The item with the ID we were given really ought to be a method. - assert_eq!(trait_item.kind, ty::AssociatedKind::Method); + assert_eq!(trait_item.kind, ty::AssocKind::Method); return entries; } - if trait_item.kind == ty::AssociatedKind::Method { + if trait_item.kind == ty::AssocKind::Method { entries += 1; } } diff --git a/src/librustc/ty/adjustment.rs b/src/librustc/ty/adjustment.rs index 0843a3a55fc41..11aad87b70dd3 100644 --- a/src/librustc/ty/adjustment.rs +++ b/src/librustc/ty/adjustment.rs @@ -111,7 +111,7 @@ impl<'a, 'gcx, 'tcx> OverloadedDeref<'tcx> { hir::MutMutable => tcx.lang_items().deref_mut_trait() }; let method_def_id = tcx.associated_items(trait_def_id.unwrap()) - .find(|m| m.kind == ty::AssociatedKind::Method).unwrap().def_id; + .find(|m| m.kind == ty::AssocKind::Method).unwrap().def_id; (method_def_id, tcx.mk_substs_trait(source, &[])) } } diff --git a/src/librustc/ty/instance.rs b/src/librustc/ty/instance.rs index f54e69f352a4e..be15b1e3cc9e4 100644 --- a/src/librustc/ty/instance.rs +++ b/src/librustc/ty/instance.rs @@ -341,7 +341,7 @@ impl<'a, 'b, 'tcx> Instance<'tcx> { fn resolve_associated_item<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, - trait_item: &ty::AssociatedItem, + trait_item: &ty::AssocItem, param_env: ty::ParamEnv<'tcx>, trait_id: DefId, rcvr_substs: SubstsRef<'tcx>, @@ -450,7 +450,7 @@ fn fn_once_adapter_instance<'a, 'tcx>( substs); let fn_once = tcx.lang_items().fn_once_trait().unwrap(); let call_once = tcx.associated_items(fn_once) - .find(|it| it.kind == ty::AssociatedKind::Method) + .find(|it| it.kind == ty::AssocKind::Method) .unwrap().def_id; let def = ty::InstanceDef::ClosureOnceShim { call_once }; diff --git a/src/librustc/ty/mod.rs b/src/librustc/ty/mod.rs index 99c3293168754..f1d1abfa0fb4b 100644 --- a/src/librustc/ty/mod.rs +++ b/src/librustc/ty/mod.rs @@ -3,7 +3,7 @@ #![allow(usage_of_ty_tykind)] pub use self::Variance::*; -pub use self::AssociatedItemContainer::*; +pub use self::AssocItemContainer::*; pub use self::BorrowKind::*; pub use self::IntVarValue::*; pub use self::fold::TypeFoldable; @@ -134,12 +134,12 @@ pub struct Resolutions { } #[derive(Clone, Copy, PartialEq, Eq, Debug, HashStable)] -pub enum AssociatedItemContainer { +pub enum AssocItemContainer { TraitContainer(DefId), ImplContainer(DefId), } -impl AssociatedItemContainer { +impl AssocItemContainer { /// Asserts that this is the `DefId` of an associated item declared /// in a trait, and returns the trait `DefId`. pub fn assert_trait(&self) -> DefId { @@ -169,14 +169,14 @@ pub struct ImplHeader<'tcx> { } #[derive(Copy, Clone, Debug, PartialEq, HashStable)] -pub struct AssociatedItem { +pub struct AssocItem { pub def_id: DefId, #[stable_hasher(project(name))] pub ident: Ident, - pub kind: AssociatedKind, + pub kind: AssocKind, pub vis: Visibility, pub defaultness: hir::Defaultness, - pub container: AssociatedItemContainer, + pub container: AssocItemContainer, /// Whether this is a method with an explicit self /// as its first argument, allowing method calls. @@ -184,20 +184,20 @@ pub struct AssociatedItem { } #[derive(Copy, Clone, PartialEq, Eq, Debug, Hash, RustcEncodable, RustcDecodable, HashStable)] -pub enum AssociatedKind { +pub enum AssocKind { Const, Method, Existential, Type } -impl AssociatedItem { +impl AssocItem { pub fn def_kind(&self) -> DefKind { match self.kind { - AssociatedKind::Const => DefKind::AssociatedConst, - AssociatedKind::Method => DefKind::Method, - AssociatedKind::Type => DefKind::AssociatedTy, - AssociatedKind::Existential => DefKind::AssociatedExistential, + AssocKind::Const => DefKind::AssocConst, + AssocKind::Method => DefKind::Method, + AssocKind::Type => DefKind::AssocTy, + AssocKind::Existential => DefKind::AssocExistential, } } @@ -205,26 +205,26 @@ impl AssociatedItem { /// for ! pub fn relevant_for_never<'tcx>(&self) -> bool { match self.kind { - AssociatedKind::Existential | - AssociatedKind::Const | - AssociatedKind::Type => true, + AssocKind::Existential | + AssocKind::Const | + AssocKind::Type => true, // FIXME(canndrew): Be more thorough here, check if any argument is uninhabited. - AssociatedKind::Method => !self.method_has_self_argument, + AssocKind::Method => !self.method_has_self_argument, } } pub fn signature<'a, 'tcx>(&self, tcx: TyCtxt<'a, 'tcx, 'tcx>) -> String { match self.kind { - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { // We skip the binder here because the binder would deanonymize all // late-bound regions, and we don't want method signatures to show up // `as for<'r> fn(&'r MyType)`. Pretty-printing handles late-bound // regions just fine, showing `fn(&MyType)`. tcx.fn_sig(self.def_id).skip_binder().to_string() } - ty::AssociatedKind::Type => format!("type {};", self.ident), - ty::AssociatedKind::Existential => format!("existential type {};", self.ident), - ty::AssociatedKind::Const => { + ty::AssocKind::Type => format!("type {};", self.ident), + ty::AssocKind::Existential => format!("existential type {};", self.ident), + ty::AssocKind::Const => { format!("const {}: {:?};", self.ident, tcx.type_of(self.def_id)) } } @@ -2343,7 +2343,7 @@ impl<'a, 'gcx, 'tcx> AdtDef { Res::Def(DefKind::Variant, vid) => self.variant_with_id(vid), Res::Def(DefKind::Ctor(..), cid) => self.variant_with_ctor_id(cid), Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) | - Res::Def(DefKind::TyAlias, _) | Res::Def(DefKind::AssociatedTy, _) | Res::SelfTy(..) | + Res::Def(DefKind::TyAlias, _) | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) | Res::SelfCtor(..) => self.non_enum_variant(), _ => bug!("unexpected res {:?} in variant_of_res", res) } @@ -2793,9 +2793,9 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } } - pub fn provided_trait_methods(self, id: DefId) -> Vec { + pub fn provided_trait_methods(self, id: DefId) -> Vec { self.associated_items(id) - .filter(|item| item.kind == AssociatedKind::Method && item.defaultness.has_value()) + .filter(|item| item.kind == AssocKind::Method && item.defaultness.has_value()) .collect() } @@ -2805,7 +2805,7 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { }) } - pub fn opt_associated_item(self, def_id: DefId) -> Option { + pub fn opt_associated_item(self, def_id: DefId) -> Option { let is_associated_item = if let Some(hir_id) = self.hir().as_local_hir_id(def_id) { match self.hir().get_by_hir_id(hir_id) { Node::TraitItem(_) | Node::ImplItem(_) => true, @@ -2813,9 +2813,9 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } } else { match self.def_kind(def_id).expect("no def for def-id") { - DefKind::AssociatedConst + DefKind::AssocConst | DefKind::Method - | DefKind::AssociatedTy => true, + | DefKind::AssocTy => true, _ => false, } }; @@ -2831,18 +2831,18 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { parent_def_id: DefId, parent_vis: &hir::Visibility, trait_item_ref: &hir::TraitItemRef) - -> AssociatedItem { + -> AssocItem { let def_id = self.hir().local_def_id_from_hir_id(trait_item_ref.id.hir_id); let (kind, has_self) = match trait_item_ref.kind { - hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false), - hir::AssociatedItemKind::Method { has_self } => { - (ty::AssociatedKind::Method, has_self) + hir::AssocItemKind::Const => (ty::AssocKind::Const, false), + hir::AssocItemKind::Method { has_self } => { + (ty::AssocKind::Method, has_self) } - hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false), - hir::AssociatedItemKind::Existential => bug!("only impls can have existentials"), + hir::AssocItemKind::Type => (ty::AssocKind::Type, false), + hir::AssocItemKind::Existential => bug!("only impls can have existentials"), }; - AssociatedItem { + AssocItem { ident: trait_item_ref.ident, kind, // Visibility of trait items is inherited from their traits. @@ -2857,18 +2857,18 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { fn associated_item_from_impl_item_ref(self, parent_def_id: DefId, impl_item_ref: &hir::ImplItemRef) - -> AssociatedItem { + -> AssocItem { let def_id = self.hir().local_def_id_from_hir_id(impl_item_ref.id.hir_id); let (kind, has_self) = match impl_item_ref.kind { - hir::AssociatedItemKind::Const => (ty::AssociatedKind::Const, false), - hir::AssociatedItemKind::Method { has_self } => { - (ty::AssociatedKind::Method, has_self) + hir::AssocItemKind::Const => (ty::AssocKind::Const, false), + hir::AssocItemKind::Method { has_self } => { + (ty::AssocKind::Method, has_self) } - hir::AssociatedItemKind::Type => (ty::AssociatedKind::Type, false), - hir::AssociatedItemKind::Existential => (ty::AssociatedKind::Existential, false), + hir::AssocItemKind::Type => (ty::AssocKind::Type, false), + hir::AssocItemKind::Existential => (ty::AssocKind::Existential, false), }; - AssociatedItem { + AssocItem { ident: impl_item_ref.ident, kind, // Visibility of trait impl items doesn't matter. @@ -2893,13 +2893,13 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { pub fn associated_items( self, def_id: DefId, - ) -> AssociatedItemsIterator<'a, 'gcx, 'tcx> { + ) -> AssocItemsIterator<'a, 'gcx, 'tcx> { // Ideally, we would use `-> impl Iterator` here, but it falls // afoul of the conservative "capture [restrictions]" we put // in place, so we use a hand-written iterator. // // [restrictions]: https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999 - AssociatedItemsIterator { + AssocItemsIterator { tcx: self, def_ids: self.associated_item_def_ids(def_id), next_index: 0, @@ -3104,23 +3104,23 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> { } } -pub struct AssociatedItemsIterator<'a, 'gcx: 'tcx, 'tcx: 'a> { +pub struct AssocItemsIterator<'a, 'gcx: 'tcx, 'tcx: 'a> { tcx: TyCtxt<'a, 'gcx, 'tcx>, def_ids: &'gcx [DefId], next_index: usize, } -impl Iterator for AssociatedItemsIterator<'_, '_, '_> { - type Item = AssociatedItem; +impl Iterator for AssocItemsIterator<'_, '_, '_> { + type Item = AssocItem; - fn next(&mut self) -> Option { + fn next(&mut self) -> Option { let def_id = self.def_ids.get(self.next_index)?; self.next_index += 1; Some(self.tcx.associated_item(*def_id)) } } -fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> AssociatedItem { +fn associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> AssocItem { let id = tcx.hir().as_local_hir_id(def_id).unwrap(); let parent_id = tcx.hir().get_parent_item(id); let parent_def_id = tcx.hir().local_def_id_from_hir_id(parent_id); diff --git a/src/librustc/ty/sty.rs b/src/librustc/ty/sty.rs index 0b5a6fce5cb87..5ada7c0bed094 100644 --- a/src/librustc/ty/sty.rs +++ b/src/librustc/ty/sty.rs @@ -998,7 +998,7 @@ impl<'a, 'tcx> ProjectionTy<'tcx> { tcx: TyCtxt<'_, '_, '_>, trait_ref: ty::TraitRef<'tcx>, item_name: Ident ) -> ProjectionTy<'tcx> { let item_def_id = tcx.associated_items(trait_ref.def_id).find(|item| { - item.kind == ty::AssociatedKind::Type && + item.kind == ty::AssocKind::Type && tcx.hygienic_eq(item_name, item.ident, trait_ref.def_id) }).unwrap().def_id; diff --git a/src/librustc_metadata/cstore_impl.rs b/src/librustc_metadata/cstore_impl.rs index fae4c244d6e14..2ef553c159c51 100644 --- a/src/librustc_metadata/cstore_impl.rs +++ b/src/librustc_metadata/cstore_impl.rs @@ -473,7 +473,7 @@ impl cstore::CStore { }) } - pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssociatedItem { + pub fn associated_item_cloned_untracked(&self, def: DefId) -> ty::AssocItem { self.get_crate_data(def.krate).get_associated_item(def.index) } } diff --git a/src/librustc_metadata/decoder.rs b/src/librustc_metadata/decoder.rs index 958c81989ffd6..a484928ce6c36 100644 --- a/src/librustc_metadata/decoder.rs +++ b/src/librustc_metadata/decoder.rs @@ -401,7 +401,7 @@ impl<'tcx> EntryKind<'tcx> { fn def_kind(&self) -> Option { Some(match *self { EntryKind::Const(..) => DefKind::Const, - EntryKind::AssociatedConst(..) => DefKind::AssociatedConst, + EntryKind::AssocConst(..) => DefKind::AssocConst, EntryKind::ImmStatic | EntryKind::MutStatic | EntryKind::ForeignImmStatic | @@ -415,8 +415,8 @@ impl<'tcx> EntryKind<'tcx> { EntryKind::TypeParam => DefKind::TyParam, EntryKind::ConstParam => DefKind::ConstParam, EntryKind::Existential => DefKind::Existential, - EntryKind::AssociatedType(_) => DefKind::AssociatedTy, - EntryKind::AssociatedExistential(_) => DefKind::AssociatedExistential, + EntryKind::AssocType(_) => DefKind::AssocTy, + EntryKind::AssocExistential(_) => DefKind::AssocExistential, EntryKind::Mod(_) => DefKind::Mod, EntryKind::Variant(_) => DefKind::Variant, EntryKind::Trait(_) => DefKind::Trait, @@ -873,7 +873,7 @@ impl<'a, 'tcx> CrateMetadata { pub fn const_is_rvalue_promotable_to_static(&self, id: DefIndex) -> bool { match self.entry(id).kind { - EntryKind::AssociatedConst(_, data, _) | + EntryKind::AssocConst(_, data, _) | EntryKind::Const(data, _) => data.ast_promotable, _ => bug!(), } @@ -897,38 +897,38 @@ impl<'a, 'tcx> CrateMetadata { pub fn mir_const_qualif(&self, id: DefIndex) -> u8 { match self.entry(id).kind { EntryKind::Const(qualif, _) | - EntryKind::AssociatedConst(AssociatedContainer::ImplDefault, qualif, _) | - EntryKind::AssociatedConst(AssociatedContainer::ImplFinal, qualif, _) => { + EntryKind::AssocConst(AssocContainer::ImplDefault, qualif, _) | + EntryKind::AssocConst(AssocContainer::ImplFinal, qualif, _) => { qualif.mir } _ => bug!(), } } - pub fn get_associated_item(&self, id: DefIndex) -> ty::AssociatedItem { + pub fn get_associated_item(&self, id: DefIndex) -> ty::AssocItem { let item = self.entry(id); let def_key = self.def_key(id); let parent = self.local_def_id(def_key.parent.unwrap()); let name = def_key.disambiguated_data.data.get_opt_name().unwrap(); let (kind, container, has_self) = match item.kind { - EntryKind::AssociatedConst(container, _, _) => { - (ty::AssociatedKind::Const, container, false) + EntryKind::AssocConst(container, _, _) => { + (ty::AssocKind::Const, container, false) } EntryKind::Method(data) => { let data = data.decode(self); - (ty::AssociatedKind::Method, data.container, data.has_self) + (ty::AssocKind::Method, data.container, data.has_self) } - EntryKind::AssociatedType(container) => { - (ty::AssociatedKind::Type, container, false) + EntryKind::AssocType(container) => { + (ty::AssocKind::Type, container, false) } - EntryKind::AssociatedExistential(container) => { - (ty::AssociatedKind::Existential, container, false) + EntryKind::AssocExistential(container) => { + (ty::AssocKind::Existential, container, false) } _ => bug!("cannot get associated-item of `{:?}`", def_key) }; - ty::AssociatedItem { + ty::AssocItem { ident: Ident::from_interned_str(name), kind, vis: item.visibility.decode(self), @@ -1150,7 +1150,7 @@ impl<'a, 'tcx> CrateMetadata { pub fn get_rendered_const(&self, id: DefIndex) -> String { match self.entry(id).kind { EntryKind::Const(_, data) | - EntryKind::AssociatedConst(_, _, data) => data.decode(self).0, + EntryKind::AssocConst(_, _, data) => data.decode(self).0, _ => bug!(), } } diff --git a/src/librustc_metadata/encoder.rs b/src/librustc_metadata/encoder.rs index 1a9d996131dc0..5d080de2645e3 100644 --- a/src/librustc_metadata/encoder.rs +++ b/src/librustc_metadata/encoder.rs @@ -822,15 +822,15 @@ impl EncodeContext<'_, 'tcx> { let container = match trait_item.defaultness { hir::Defaultness::Default { has_value: true } => - AssociatedContainer::TraitWithDefault, + AssocContainer::TraitWithDefault, hir::Defaultness::Default { has_value: false } => - AssociatedContainer::TraitRequired, + AssocContainer::TraitRequired, hir::Defaultness::Final => span_bug!(ast_item.span, "traits cannot have final items"), }; let kind = match trait_item.kind { - ty::AssociatedKind::Const => { + ty::AssocKind::Const => { let const_qualif = if let hir::TraitItemKind::Const(_, Some(body)) = ast_item.node { self.const_qualif(0, body) @@ -842,9 +842,9 @@ impl EncodeContext<'_, 'tcx> { hir::print::to_string(self.tcx.hir(), |s| s.print_trait_item(ast_item)); let rendered_const = self.lazy(&RenderedConst(rendered)); - EntryKind::AssociatedConst(container, const_qualif, rendered_const) + EntryKind::AssocConst(container, const_qualif, rendered_const) } - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { let fn_data = if let hir::TraitItemKind::Method(_, ref m) = ast_item.node { let arg_names = match *m { hir::TraitMethod::Required(ref names) => { @@ -868,8 +868,8 @@ impl EncodeContext<'_, 'tcx> { has_self: trait_item.method_has_self_argument, })) } - ty::AssociatedKind::Type => EntryKind::AssociatedType(container), - ty::AssociatedKind::Existential => + ty::AssocKind::Type => EntryKind::AssocType(container), + ty::AssocKind::Existential => span_bug!(ast_item.span, "existential type in trait"), }; @@ -883,21 +883,21 @@ impl EncodeContext<'_, 'tcx> { deprecation: self.encode_deprecation(def_id), ty: match trait_item.kind { - ty::AssociatedKind::Const | - ty::AssociatedKind::Method => { + ty::AssocKind::Const | + ty::AssocKind::Method => { Some(self.encode_item_type(def_id)) } - ty::AssociatedKind::Type => { + ty::AssocKind::Type => { if trait_item.defaultness.has_value() { Some(self.encode_item_type(def_id)) } else { None } } - ty::AssociatedKind::Existential => unreachable!(), + ty::AssocKind::Existential => unreachable!(), }, inherent_impls: LazySeq::empty(), - variances: if trait_item.kind == ty::AssociatedKind::Method { + variances: if trait_item.kind == ty::AssocKind::Method { self.encode_variances_of(def_id) } else { LazySeq::empty() @@ -931,25 +931,25 @@ impl EncodeContext<'_, 'tcx> { let impl_item = self.tcx.associated_item(def_id); let container = match impl_item.defaultness { - hir::Defaultness::Default { has_value: true } => AssociatedContainer::ImplDefault, - hir::Defaultness::Final => AssociatedContainer::ImplFinal, + hir::Defaultness::Default { has_value: true } => AssocContainer::ImplDefault, + hir::Defaultness::Final => AssocContainer::ImplFinal, hir::Defaultness::Default { has_value: false } => span_bug!(ast_item.span, "impl items always have values (currently)"), }; let kind = match impl_item.kind { - ty::AssociatedKind::Const => { + ty::AssocKind::Const => { if let hir::ImplItemKind::Const(_, body_id) = ast_item.node { let mir = self.tcx.at(ast_item.span).mir_const_qualif(def_id).0; - EntryKind::AssociatedConst(container, + EntryKind::AssocConst(container, self.const_qualif(mir, body_id), self.encode_rendered_const_for_body(body_id)) } else { bug!() } } - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { let fn_data = if let hir::ImplItemKind::Method(ref sig, body) = ast_item.node { FnData { constness: sig.header.constness, @@ -965,8 +965,8 @@ impl EncodeContext<'_, 'tcx> { has_self: impl_item.method_has_self_argument, })) } - ty::AssociatedKind::Existential => EntryKind::AssociatedExistential(container), - ty::AssociatedKind::Type => EntryKind::AssociatedType(container) + ty::AssocKind::Existential => EntryKind::AssocExistential(container), + ty::AssocKind::Type => EntryKind::AssocType(container) }; let mir = @@ -996,7 +996,7 @@ impl EncodeContext<'_, 'tcx> { ty: Some(self.encode_item_type(def_id)), inherent_impls: LazySeq::empty(), - variances: if impl_item.kind == ty::AssociatedKind::Method { + variances: if impl_item.kind == ty::AssocKind::Method { self.encode_variances_of(def_id) } else { LazySeq::empty() diff --git a/src/librustc_metadata/schema.rs b/src/librustc_metadata/schema.rs index 0ad3251540716..b9e5bdef27ab4 100644 --- a/src/librustc_metadata/schema.rs +++ b/src/librustc_metadata/schema.rs @@ -253,13 +253,13 @@ pub enum EntryKind<'tcx> { Trait(Lazy>), Impl(Lazy>), Method(Lazy>), - AssociatedType(AssociatedContainer), - AssociatedExistential(AssociatedContainer), - AssociatedConst(AssociatedContainer, ConstQualif, Lazy), + AssocType(AssocContainer), + AssocExistential(AssocContainer), + AssocConst(AssocContainer, ConstQualif, Lazy), TraitAlias(Lazy>), } -/// Additional data for EntryKind::Const and EntryKind::AssociatedConst +/// Additional data for EntryKind::Const and EntryKind::AssocConst #[derive(Clone, Copy, RustcEncodable, RustcDecodable)] pub struct ConstQualif { pub mir: u8, @@ -330,36 +330,36 @@ pub struct ImplData<'tcx> { /// is a trait or an impl and whether, in a trait, it has /// a default, or an in impl, whether it's marked "default". #[derive(Copy, Clone, RustcEncodable, RustcDecodable)] -pub enum AssociatedContainer { +pub enum AssocContainer { TraitRequired, TraitWithDefault, ImplDefault, ImplFinal, } -impl AssociatedContainer { - pub fn with_def_id(&self, def_id: DefId) -> ty::AssociatedItemContainer { +impl AssocContainer { + pub fn with_def_id(&self, def_id: DefId) -> ty::AssocItemContainer { match *self { - AssociatedContainer::TraitRequired | - AssociatedContainer::TraitWithDefault => ty::TraitContainer(def_id), + AssocContainer::TraitRequired | + AssocContainer::TraitWithDefault => ty::TraitContainer(def_id), - AssociatedContainer::ImplDefault | - AssociatedContainer::ImplFinal => ty::ImplContainer(def_id), + AssocContainer::ImplDefault | + AssocContainer::ImplFinal => ty::ImplContainer(def_id), } } pub fn defaultness(&self) -> hir::Defaultness { match *self { - AssociatedContainer::TraitRequired => hir::Defaultness::Default { + AssocContainer::TraitRequired => hir::Defaultness::Default { has_value: false, }, - AssociatedContainer::TraitWithDefault | - AssociatedContainer::ImplDefault => hir::Defaultness::Default { + AssocContainer::TraitWithDefault | + AssocContainer::ImplDefault => hir::Defaultness::Default { has_value: true, }, - AssociatedContainer::ImplFinal => hir::Defaultness::Final, + AssocContainer::ImplFinal => hir::Defaultness::Final, } } } @@ -367,7 +367,7 @@ impl AssociatedContainer { #[derive(RustcEncodable, RustcDecodable)] pub struct MethodData<'tcx> { pub fn_data: FnData<'tcx>, - pub container: AssociatedContainer, + pub container: AssocContainer, pub has_self: bool, } diff --git a/src/librustc_mir/const_eval.rs b/src/librustc_mir/const_eval.rs index 866b6492d10bc..9355c1c88dbba 100644 --- a/src/librustc_mir/const_eval.rs +++ b/src/librustc_mir/const_eval.rs @@ -641,7 +641,7 @@ pub fn const_eval_raw_provider<'a, 'tcx>( // note that validation may still cause a hard error on this very same constant, // because any code that existed before validation could not have failed validation // thus preventing such a hard error from being a backwards compatibility hazard - Some(DefKind::Const) | Some(DefKind::AssociatedConst) => { + Some(DefKind::Const) | Some(DefKind::AssocConst) => { let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap(); err.report_as_lint( tcx.at(tcx.def_span(def_id)), diff --git a/src/librustc_mir/hair/cx/expr.rs b/src/librustc_mir/hair/cx/expr.rs index d623f149988c7..851eb8f41ca8a 100644 --- a/src/librustc_mir/hair/cx/expr.rs +++ b/src/librustc_mir/hair/cx/expr.rs @@ -791,7 +791,7 @@ fn user_substs_applied_to_res( Res::Def(DefKind::Method, _) | Res::Def(DefKind::Ctor(_, CtorKind::Fn), _) | Res::Def(DefKind::Const, _) | - Res::Def(DefKind::AssociatedConst, _) => + Res::Def(DefKind::AssocConst, _) => cx.tables().user_provided_types().get(hir_id).map(|u_ty| *u_ty), // A unit struct/variant which is used as a value (e.g., @@ -929,7 +929,7 @@ fn convert_path_expr<'a, 'gcx, 'tcx>(cx: &mut Cx<'a, 'gcx, 'tcx>, } Res::Def(DefKind::Const, def_id) | - Res::Def(DefKind::AssociatedConst, def_id) => { + Res::Def(DefKind::AssocConst, def_id) => { let user_ty = user_substs_applied_to_res(cx, expr.hir_id, res); debug!("convert_path_expr: (const) user_ty={:?}", user_ty); ExprKind::Literal { diff --git a/src/librustc_mir/hair/cx/mod.rs b/src/librustc_mir/hair/cx/mod.rs index e8070b21bb8c7..8382f6a2f9660 100644 --- a/src/librustc_mir/hair/cx/mod.rs +++ b/src/librustc_mir/hair/cx/mod.rs @@ -170,7 +170,7 @@ impl<'a, 'gcx, 'tcx> Cx<'a, 'gcx, 'tcx> { let method_name = Symbol::intern(method_name); let substs = self.tcx.mk_substs_trait(self_ty, params); for item in self.tcx.associated_items(trait_def_id) { - if item.kind == ty::AssociatedKind::Method && item.ident.name == method_name { + if item.kind == ty::AssocKind::Method && item.ident.name == method_name { let method_ty = self.tcx.type_of(item.def_id); let method_ty = method_ty.subst(self.tcx, substs); return (method_ty, ty::Const::zero_sized(method_ty)); diff --git a/src/librustc_mir/hair/pattern/check_match.rs b/src/librustc_mir/hair/pattern/check_match.rs index a1b2e6461e5ba..0edf32d3a306c 100644 --- a/src/librustc_mir/hair/pattern/check_match.rs +++ b/src/librustc_mir/hair/pattern/check_match.rs @@ -102,7 +102,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { PatternError::StaticInPattern(span) => { self.span_e0158(span, "statics cannot be referenced in patterns") } - PatternError::AssociatedConstInPattern(span) => { + PatternError::AssocConstInPattern(span) => { self.span_e0158(span, "associated consts cannot be referenced in patterns") } PatternError::FloatBug => { diff --git a/src/librustc_mir/hair/pattern/mod.rs b/src/librustc_mir/hair/pattern/mod.rs index 0576bb53d8f42..142966b900e4f 100644 --- a/src/librustc_mir/hair/pattern/mod.rs +++ b/src/librustc_mir/hair/pattern/mod.rs @@ -32,7 +32,7 @@ use syntax_pos::Span; #[derive(Clone, Debug)] pub enum PatternError { - AssociatedConstInPattern(Span), + AssocConstInPattern(Span), StaticInPattern(Span), FloatBug, NonConstPath(Span), @@ -769,7 +769,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { | Res::Def(DefKind::Ctor(CtorOf::Struct, ..), _) | Res::Def(DefKind::Union, _) | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) | Res::SelfCtor(..) => { PatternKind::Leaf { subpatterns } @@ -811,11 +811,11 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { let ty = self.tables.node_type(id); let res = self.tables.qpath_res(qpath, id); let is_associated_const = match res { - Res::Def(DefKind::AssociatedConst, _) => true, + Res::Def(DefKind::AssocConst, _) => true, _ => false, }; let kind = match res { - Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssociatedConst, def_id) => { + Res::Def(DefKind::Const, def_id) | Res::Def(DefKind::AssocConst, def_id) => { let substs = self.tables.node_substs(id); match ty::Instance::resolve( self.tcx, @@ -869,7 +869,7 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> { }, None => { self.errors.push(if is_associated_const { - PatternError::AssociatedConstInPattern(span) + PatternError::AssocConstInPattern(span) } else { PatternError::StaticInPattern(span) }); diff --git a/src/librustc_mir/interpret/eval_context.rs b/src/librustc_mir/interpret/eval_context.rs index d4c1e5416d565..2f89740876db1 100644 --- a/src/librustc_mir/interpret/eval_context.rs +++ b/src/librustc_mir/interpret/eval_context.rs @@ -513,7 +513,7 @@ impl<'a, 'mir, 'tcx: 'mir, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tc // statics and constants don't have `Storage*` statements, no need to look for them Some(DefKind::Static) | Some(DefKind::Const) - | Some(DefKind::AssociatedConst) => {}, + | Some(DefKind::AssocConst) => {}, _ => { trace!("push_stack_frame: {:?}: num_bbs: {}", span, mir.basic_blocks().len()); for block in mir.basic_blocks() { diff --git a/src/librustc_mir/lints.rs b/src/librustc_mir/lints.rs index 572f7133cad84..51ceb2a01c3a4 100644 --- a/src/librustc_mir/lints.rs +++ b/src/librustc_mir/lints.rs @@ -4,7 +4,7 @@ use rustc::hir::intravisit::FnKind; use rustc::hir::map::blocks::FnLikeNode; use rustc::lint::builtin::UNCONDITIONAL_RECURSION; use rustc::mir::{self, Mir, TerminatorKind}; -use rustc::ty::{self, AssociatedItem, AssociatedItemContainer, Instance, TyCtxt}; +use rustc::ty::{self, AssocItem, AssocItemContainer, Instance, TyCtxt}; use rustc::ty::subst::InternalSubsts; pub fn check(tcx: TyCtxt<'a, 'tcx, 'tcx>, @@ -63,8 +63,8 @@ fn check_fn_for_unconditional_recursion(tcx: TyCtxt<'a, 'tcx, 'tcx>, let param_env = tcx.param_env(def_id); let trait_substs_count = match tcx.opt_associated_item(def_id) { - Some(AssociatedItem { - container: AssociatedItemContainer::TraitContainer(trait_def_id), + Some(AssocItem { + container: AssocItemContainer::TraitContainer(trait_def_id), .. }) => tcx.generics_of(trait_def_id).count(), _ => 0 diff --git a/src/librustc_mir/monomorphize/mod.rs b/src/librustc_mir/monomorphize/mod.rs index 7fa904d32cbb4..ff48c86817b49 100644 --- a/src/librustc_mir/monomorphize/mod.rs +++ b/src/librustc_mir/monomorphize/mod.rs @@ -65,7 +65,7 @@ fn fn_once_adapter_instance<'a, 'tcx>( substs); let fn_once = tcx.lang_items().fn_once_trait().unwrap(); let call_once = tcx.associated_items(fn_once) - .find(|it| it.kind == ty::AssociatedKind::Method) + .find(|it| it.kind == ty::AssocKind::Method) .unwrap().def_id; let def = ty::InstanceDef::ClosureOnceShim { call_once }; diff --git a/src/librustc_mir/shim.rs b/src/librustc_mir/shim.rs index b9224d973fe7b..107c23090054e 100644 --- a/src/librustc_mir/shim.rs +++ b/src/librustc_mir/shim.rs @@ -84,7 +84,7 @@ fn make_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let fn_mut = tcx.lang_items().fn_mut_trait().unwrap(); let call_mut = tcx.global_tcx() .associated_items(fn_mut) - .find(|it| it.kind == ty::AssociatedKind::Method) + .find(|it| it.kind == ty::AssocKind::Method) .unwrap().def_id; build_call_shim( diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 8f3dd72c4f245..271d660a0d09f 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -45,7 +45,7 @@ impl MirPass for ConstProp { let is_fn_like = FnLikeNode::from_node(tcx.hir().get_by_hir_id(hir_id)).is_some(); let is_assoc_const = match tcx.def_kind(source.def_id()) { - Some(DefKind::AssociatedConst) => true, + Some(DefKind::AssocConst) => true, _ => false, }; diff --git a/src/librustc_mir/util/pretty.rs b/src/librustc_mir/util/pretty.rs index 94259fa523ccd..cf90f44e6707f 100644 --- a/src/librustc_mir/util/pretty.rs +++ b/src/librustc_mir/util/pretty.rs @@ -588,7 +588,7 @@ fn write_mir_sig( match (kind, src.promoted) { (_, Some(i)) => write!(w, "{:?} in ", i)?, (Some(DefKind::Const), _) - | (Some(DefKind::AssociatedConst), _) => write!(w, "const ")?, + | (Some(DefKind::AssocConst), _) => write!(w, "const ")?, (Some(DefKind::Static), _) => write!(w, "static {}", if tcx.is_mutable_static(src.def_id()) { "mut " } else { "" })?, (_, _) if is_function => write!(w, "fn ")?, diff --git a/src/librustc_passes/rvalue_promotion.rs b/src/librustc_passes/rvalue_promotion.rs index 37917aaa4a80f..85cd602db591f 100644 --- a/src/librustc_passes/rvalue_promotion.rs +++ b/src/librustc_passes/rvalue_promotion.rs @@ -351,7 +351,7 @@ fn check_expr_kind<'a, 'tcx>( } Res::Def(DefKind::Const, did) | - Res::Def(DefKind::AssociatedConst, did) => { + Res::Def(DefKind::AssocConst, did) => { let promotable = if v.tcx.trait_of_item(did).is_some() { // Don't peek inside trait associated constants. NotPromotable diff --git a/src/librustc_privacy/lib.rs b/src/librustc_privacy/lib.rs index 65b6a89aa0b4d..68930533a285c 100644 --- a/src/librustc_privacy/lib.rs +++ b/src/librustc_privacy/lib.rs @@ -11,7 +11,7 @@ #[macro_use] extern crate syntax; use rustc::bug; -use rustc::hir::{self, Node, PatKind, AssociatedItemKind}; +use rustc::hir::{self, Node, PatKind, AssocItemKind}; use rustc::hir::def::{Res, DefKind}; use rustc::hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE, CrateNum, DefId}; use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap}; @@ -624,7 +624,7 @@ impl<'a, 'tcx> Visitor<'tcx> for EmbargoVisitor<'a, 'tcx> { let mut reach = self.reach(trait_item_ref.id.hir_id, item_level); reach.generics().predicates(); - if trait_item_ref.kind == AssociatedItemKind::Type && + if trait_item_ref.kind == AssocItemKind::Type && !trait_item_ref.defaultness.has_value() { // No type to visit. } else { @@ -1112,9 +1112,9 @@ impl<'a, 'tcx> Visitor<'tcx> for TypePrivacyVisitor<'a, 'tcx> { let def = def.filter(|(kind, _)| { match kind { DefKind::Method - | DefKind::AssociatedConst - | DefKind::AssociatedTy - | DefKind::AssociatedExistential + | DefKind::AssocConst + | DefKind::AssocTy + | DefKind::AssocExistential | DefKind::Static => true, _ => false, } @@ -1448,11 +1448,11 @@ impl<'a, 'tcx> Visitor<'tcx> for ObsoleteVisiblePrivateTypesVisitor<'a, 'tcx> { if self.item_is_public(&impl_item_ref.id.hir_id, &impl_item_ref.vis) { let impl_item = self.tcx.hir().impl_item(impl_item_ref.id); match impl_item_ref.kind { - AssociatedItemKind::Const => { + AssocItemKind::Const => { found_pub_static = true; intravisit::walk_impl_item(self, impl_item); } - AssociatedItemKind::Method { has_self: false } => { + AssocItemKind::Method { has_self: false } => { found_pub_static = true; intravisit::walk_impl_item(self, impl_item); } @@ -1703,16 +1703,16 @@ impl<'a, 'tcx> PrivateItemsInPublicInterfacesVisitor<'a, 'tcx> { } } - fn check_trait_or_impl_item(&self, hir_id: hir::HirId, assoc_item_kind: AssociatedItemKind, + fn check_trait_or_impl_item(&self, hir_id: hir::HirId, assoc_item_kind: AssocItemKind, defaultness: hir::Defaultness, vis: ty::Visibility) { let mut check = self.check(hir_id, vis); let (check_ty, is_assoc_ty) = match assoc_item_kind { - AssociatedItemKind::Const | AssociatedItemKind::Method { .. } => (true, false), - AssociatedItemKind::Type => (defaultness.has_value(), true), + AssocItemKind::Const | AssocItemKind::Method { .. } => (true, false), + AssocItemKind::Type => (defaultness.has_value(), true), // `ty()` for existential types is the underlying type, // it's not a part of interface, so we skip it. - AssociatedItemKind::Existential => (false, true), + AssocItemKind::Existential => (false, true), }; check.in_assoc_ty = is_assoc_ty; check.generics().predicates(); diff --git a/src/librustc_resolve/build_reduced_graph.rs b/src/librustc_resolve/build_reduced_graph.rs index 8c516a4da4e5f..92faab192fa9e 100644 --- a/src/librustc_resolve/build_reduced_graph.rs +++ b/src/librustc_resolve/build_reduced_graph.rs @@ -705,7 +705,7 @@ impl<'a> Resolver<'a> { for child in self.cstore.item_children_untracked(def_id, self.session) { let res = child.res.map_id(|_| panic!("unexpected id")); - let ns = if let Res::Def(DefKind::AssociatedTy, _) = res { + let ns = if let Res::Def(DefKind::AssocTy, _) = res { TypeNS } else { ValueNS }; self.define(module, child.ident, ns, @@ -1033,14 +1033,14 @@ impl<'a, 'b> Visitor<'a> for BuildReducedGraphVisitor<'a, 'b> { // Add the item to the trait info. let item_def_id = self.resolver.definitions.local_def_id(item.id); let (res, ns) = match item.node { - TraitItemKind::Const(..) => (Res::Def(DefKind::AssociatedConst, item_def_id), ValueNS), + TraitItemKind::Const(..) => (Res::Def(DefKind::AssocConst, item_def_id), ValueNS), TraitItemKind::Method(ref sig, _) => { if sig.decl.has_self() { self.resolver.has_self.insert(item_def_id); } (Res::Def(DefKind::Method, item_def_id), ValueNS) } - TraitItemKind::Type(..) => (Res::Def(DefKind::AssociatedTy, item_def_id), TypeNS), + TraitItemKind::Type(..) => (Res::Def(DefKind::AssocTy, item_def_id), TypeNS), TraitItemKind::Macro(_) => bug!(), // handled above }; diff --git a/src/librustc_resolve/diagnostics.rs b/src/librustc_resolve/diagnostics.rs index 8b5e2b86d5ee8..d8292eebce799 100644 --- a/src/librustc_resolve/diagnostics.rs +++ b/src/librustc_resolve/diagnostics.rs @@ -432,7 +432,7 @@ impl<'a> Resolver<'a> { err.note("can't use `Self` as a constructor, you must use the implemented struct"); } (Res::Def(DefKind::TyAlias, _), _) - | (Res::Def(DefKind::AssociatedTy, _), _) if ns == ValueNS => { + | (Res::Def(DefKind::AssocTy, _), _) if ns == ValueNS => { err.note("can't use a type alias as a constructor"); } _ => return false, diff --git a/src/librustc_resolve/lib.rs b/src/librustc_resolve/lib.rs index a7097a9475ede..c05b69ab44f42 100644 --- a/src/librustc_resolve/lib.rs +++ b/src/librustc_resolve/lib.rs @@ -589,7 +589,7 @@ impl<'a> PathSource<'a> { | Res::Def(DefKind::Trait, _) | Res::Def(DefKind::TraitAlias, _) | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocTy, _) | Res::PrimTy(..) | Res::Def(DefKind::TyParam, _) | Res::SelfTy(..) @@ -615,14 +615,14 @@ impl<'a> PathSource<'a> { | Res::Upvar(..) | Res::Def(DefKind::Fn, _) | Res::Def(DefKind::Method, _) - | Res::Def(DefKind::AssociatedConst, _) + | Res::Def(DefKind::AssocConst, _) | Res::SelfCtor(..) | Res::Def(DefKind::ConstParam, _) => true, _ => false, }, PathSource::Pat => match res { Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | - Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssociatedConst, _) | + Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) | Res::SelfCtor(..) => true, _ => false, }, @@ -635,14 +635,14 @@ impl<'a> PathSource<'a> { | Res::Def(DefKind::Union, _) | Res::Def(DefKind::Variant, _) | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) => true, _ => false, }, PathSource::TraitItem(ns) => match res { - Res::Def(DefKind::AssociatedConst, _) + Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Method, _) if ns == ValueNS => true, - Res::Def(DefKind::AssociatedTy, _) if ns == TypeNS => true, + Res::Def(DefKind::AssocTy, _) if ns == TypeNS => true, _ => false, }, PathSource::Visibility => match res { @@ -1511,9 +1511,9 @@ impl<'a> NameBinding<'a> { fn is_importable(&self) -> bool { match self.res() { - Res::Def(DefKind::AssociatedConst, _) + Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Method, _) - | Res::Def(DefKind::AssociatedTy, _) => false, + | Res::Def(DefKind::AssocTy, _) => false, _ => true, } } diff --git a/src/librustc_save_analysis/dump_visitor.rs b/src/librustc_save_analysis/dump_visitor.rs index 1fdfcc84926f6..06758044a2166 100644 --- a/src/librustc_save_analysis/dump_visitor.rs +++ b/src/librustc_save_analysis/dump_visitor.rs @@ -961,11 +961,11 @@ impl<'l, 'tcx: 'l, 'll, O: DumpOutput + 'll> DumpVisitor<'l, 'tcx, 'll, O> { } Res::Def(HirDefKind::Ctor(..), _) | Res::Def(HirDefKind::Const, _) | - Res::Def(HirDefKind::AssociatedConst, _) | + Res::Def(HirDefKind::AssocConst, _) | Res::Def(HirDefKind::Struct, _) | Res::Def(HirDefKind::Variant, _) | Res::Def(HirDefKind::TyAlias, _) | - Res::Def(HirDefKind::AssociatedTy, _) | + Res::Def(HirDefKind::AssocTy, _) | Res::SelfTy(..) => { self.dump_path_ref(id, &ast::Path::from_ident(ident)); } diff --git a/src/librustc_save_analysis/lib.rs b/src/librustc_save_analysis/lib.rs index 55471dbc00be5..8faa4c7180780 100644 --- a/src/librustc_save_analysis/lib.rs +++ b/src/librustc_save_analysis/lib.rs @@ -723,8 +723,8 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { Res::Def(HirDefKind::TyAlias, def_id) | Res::Def(HirDefKind::ForeignTy, def_id) | Res::Def(HirDefKind::TraitAlias, def_id) | - Res::Def(HirDefKind::AssociatedExistential, def_id) | - Res::Def(HirDefKind::AssociatedTy, def_id) | + Res::Def(HirDefKind::AssocExistential, def_id) | + Res::Def(HirDefKind::AssocTy, def_id) | Res::Def(HirDefKind::Trait, def_id) | Res::Def(HirDefKind::Existential, def_id) | Res::Def(HirDefKind::TyParam, def_id) => { @@ -754,7 +754,7 @@ impl<'l, 'tcx: 'l> SaveContext<'l, 'tcx> { } Res::Def(HirDefKind::Static, _) | Res::Def(HirDefKind::Const, _) | - Res::Def(HirDefKind::AssociatedConst, _) | + Res::Def(HirDefKind::AssocConst, _) | Res::Def(HirDefKind::Ctor(..), _) => { Some(Ref { kind: RefKind::Variable, diff --git a/src/librustc_save_analysis/sig.rs b/src/librustc_save_analysis/sig.rs index fa12d9c49dfc3..109863f8a56b2 100644 --- a/src/librustc_save_analysis/sig.rs +++ b/src/librustc_save_analysis/sig.rs @@ -586,7 +586,7 @@ impl Sig for ast::Path { refs: vec![], }) } - Res::Def(DefKind::AssociatedConst, _) + Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Variant, _) | Res::Def(DefKind::Ctor(..), _) => { let len = self.segments.len(); diff --git a/src/librustc_traits/lowering/mod.rs b/src/librustc_traits/lowering/mod.rs index 580b1571e52bb..80b0868a55134 100644 --- a/src/librustc_traits/lowering/mod.rs +++ b/src/librustc_traits/lowering/mod.rs @@ -166,10 +166,10 @@ crate fn program_clauses_for<'a, 'tcx>( | Some(DefKind::TraitAlias) => program_clauses_for_trait(tcx, def_id), // FIXME(eddyb) deduplicate this `associated_item` call with // `program_clauses_for_associated_type_{value,def}`. - Some(DefKind::AssociatedTy) => match tcx.associated_item(def_id).container { - ty::AssociatedItemContainer::ImplContainer(_) => + Some(DefKind::AssocTy) => match tcx.associated_item(def_id).container { + ty::AssocItemContainer::ImplContainer(_) => program_clauses_for_associated_type_value(tcx, def_id), - ty::AssociatedItemContainer::TraitContainer(_) => + ty::AssocItemContainer::TraitContainer(_) => program_clauses_for_associated_type_def(tcx, def_id) }, Some(DefKind::Struct) @@ -444,9 +444,9 @@ pub fn program_clauses_for_associated_type_def<'a, 'tcx>( // ``` let item = tcx.associated_item(item_id); - debug_assert_eq!(item.kind, ty::AssociatedKind::Type); + debug_assert_eq!(item.kind, ty::AssocKind::Type); let trait_id = match item.container { - ty::AssociatedItemContainer::TraitContainer(trait_id) => trait_id, + ty::AssocItemContainer::TraitContainer(trait_id) => trait_id, _ => bug!("not an trait container"), }; @@ -582,9 +582,9 @@ pub fn program_clauses_for_associated_type_value<'a, 'tcx>( // ``` let item = tcx.associated_item(item_id); - debug_assert_eq!(item.kind, ty::AssociatedKind::Type); + debug_assert_eq!(item.kind, ty::AssocKind::Type); let impl_id = match item.container { - ty::AssociatedItemContainer::ImplContainer(impl_id) => impl_id, + ty::AssocItemContainer::ImplContainer(impl_id) => impl_id, _ => bug!("not an impl container"), }; diff --git a/src/librustc_typeck/astconv.rs b/src/librustc_typeck/astconv.rs index 3a2b0178ce4d0..5b1a2e29c7642 100644 --- a/src/librustc_typeck/astconv.rs +++ b/src/librustc_typeck/astconv.rs @@ -823,7 +823,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { -> bool { self.tcx().associated_items(trait_def_id).any(|item| { - item.kind == ty::AssociatedKind::Type && + item.kind == ty::AssocKind::Type && self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id) }) } @@ -905,7 +905,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { let (assoc_ident, def_scope) = tcx.adjust_ident(binding.item_name, candidate.def_id(), hir_ref_id); let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| { - i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident + i.kind == ty::AssocKind::Type && i.ident.modern() == assoc_ident }).expect("missing associated type"); if !assoc_ty.vis.is_accessible_from(def_scope, tcx) { @@ -1045,7 +1045,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { ty::Predicate::Trait(pred) => { associated_types .extend(tcx.associated_items(pred.def_id()) - .filter(|item| item.kind == ty::AssociatedKind::Type) + .filter(|item| item.kind == ty::AssocKind::Type) .map(|item| item.def_id)); } ty::Predicate::Projection(pred) => { @@ -1300,7 +1300,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { for bound in bounds { let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| { - item.kind == ty::AssociatedKind::Type && + item.kind == ty::AssocKind::Type && self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id()) }) .and_then(|item| self.tcx().hir().span_if_local(item.def_id)); @@ -1442,7 +1442,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound); let ty = self.normalize_ty(span, ty); - let kind = DefKind::AssociatedTy; + let kind = DefKind::AssocTy; if !item.vis.is_accessible_from(def_scope, tcx) { let msg = format!("{} `{}` is private", kind.descr(), assoc_ident); tcx.sess.span_err(span, &msg); @@ -1685,7 +1685,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { // Case 4. Reference to a method or associated const. DefKind::Method - | DefKind::AssociatedConst => { + | DefKind::AssocConst => { if segments.len() >= 2 { let generics = tcx.generics_of(def_id); path_segs.push(PathSeg(generics.parent.unwrap(), last - 1)); @@ -1779,7 +1779,7 @@ impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o { self.prohibit_generics(&path.segments); tcx.mk_self_type() } - Res::Def(DefKind::AssociatedTy, def_id) => { + Res::Def(DefKind::AssocTy, def_id) => { debug_assert!(path.segments.len() >= 2); self.prohibit_generics(&path.segments[..path.segments.len() - 2]); self.qpath_to_ty(span, diff --git a/src/librustc_typeck/check/_match.rs b/src/librustc_typeck/check/_match.rs index e4b431e6e68f1..a74a33b7448e2 100644 --- a/src/librustc_typeck/check/_match.rs +++ b/src/librustc_typeck/check/_match.rs @@ -67,7 +67,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { PatKind::Path(ref qpath) => { let (def, _, _) = self.resolve_ty_and_res_ufcs(qpath, pat.hir_id, pat.span); match def { - Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssociatedConst, _) => false, + Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => false, _ => true, } } @@ -1050,7 +1050,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); return tcx.types.err; } Res::Def(DefKind::Ctor(_, CtorKind::Const), _) | Res::SelfCtor(..) | - Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssociatedConst, _) => {} // OK + Res::Def(DefKind::Const, _) | Res::Def(DefKind::AssocConst, _) => {} // OK _ => bug!("unexpected pattern resolution: {:?}", res) } @@ -1107,7 +1107,7 @@ https://doc.rust-lang.org/reference/types.html#trait-objects"); on_error(); return tcx.types.err; } - Res::Def(DefKind::AssociatedConst, _) | Res::Def(DefKind::Method, _) => { + Res::Def(DefKind::AssocConst, _) | Res::Def(DefKind::Method, _) => { report_unexpected_res(res); return tcx.types.err; } diff --git a/src/librustc_typeck/check/compare_method.rs b/src/librustc_typeck/check/compare_method.rs index 647d947485e68..1165890fe6432 100644 --- a/src/librustc_typeck/check/compare_method.rs +++ b/src/librustc_typeck/check/compare_method.rs @@ -24,9 +24,9 @@ use super::{Inherited, FnCtxt, potentially_plural_count}; /// - `impl_trait_ref`: the TraitRef corresponding to the trait implementation pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, impl_m_span: Span, - trait_m: &ty::AssociatedItem, + trait_m: &ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>, trait_item_span: Option) { debug!("compare_impl_method(impl_trait_ref={:?})", @@ -74,9 +74,9 @@ pub fn compare_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, impl_m_span: Span, - trait_m: &ty::AssociatedItem, + trait_m: &ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>) -> Result<(), ErrorReported> { let trait_to_impl_substs = impl_trait_ref.substs; @@ -357,8 +357,8 @@ fn compare_predicate_entailment<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn check_region_bounds_on_impl_method<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, - impl_m: &ty::AssociatedItem, - trait_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, + trait_m: &ty::AssocItem, trait_generics: &ty::Generics, impl_generics: &ty::Generics, trait_to_skol_substs: SubstsRef<'tcx>) @@ -410,9 +410,9 @@ fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a param_env: ty::ParamEnv<'tcx>, terr: &TypeError<'_>, cause: &ObligationCause<'tcx>, - impl_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, impl_sig: ty::FnSig<'tcx>, - trait_m: &ty::AssociatedItem, + trait_m: &ty::AssocItem, trait_sig: ty::FnSig<'tcx>) -> (Span, Option) { let tcx = infcx.tcx; @@ -496,9 +496,9 @@ fn extract_spans_for_error_reporting<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a } fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, impl_m_span: Span, - trait_m: &ty::AssociatedItem, + trait_m: &ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>) -> Result<(), ErrorReported> { @@ -510,7 +510,7 @@ fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, // inscrutable, particularly for cases where one method has no // self. - let self_string = |method: &ty::AssociatedItem| { + let self_string = |method: &ty::AssocItem| { let untransformed_self_ty = match method.container { ty::ImplContainer(_) => impl_trait_ref.self_ty(), ty::TraitContainer(_) => tcx.mk_self_type() @@ -582,9 +582,9 @@ fn compare_self_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn compare_number_of_generics<'a, 'tcx>( tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_: &ty::AssociatedItem, + impl_: &ty::AssocItem, impl_span: Span, - trait_: &ty::AssociatedItem, + trait_: &ty::AssocItem, trait_span: Option, ) -> Result<(), ErrorReported> { let trait_own_counts = tcx.generics_of(trait_.def_id).own_counts(); @@ -655,9 +655,9 @@ fn compare_number_of_generics<'a, 'tcx>( } fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, + impl_m: &ty::AssocItem, impl_m_span: Span, - trait_m: &ty::AssociatedItem, + trait_m: &ty::AssocItem, trait_item_span: Option) -> Result<(), ErrorReported> { let impl_m_fty = tcx.fn_sig(impl_m.def_id); @@ -739,8 +739,8 @@ fn compare_number_of_method_arguments<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_m: &ty::AssociatedItem, - trait_m: &ty::AssociatedItem) + impl_m: &ty::AssocItem, + trait_m: &ty::AssocItem) -> Result<(), ErrorReported> { // FIXME(chrisvittal) Clean up this function, list of FIXME items: // 1. Better messages for the span labels @@ -911,9 +911,9 @@ fn compare_synthetic_generics<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } pub fn compare_const_impl<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, - impl_c: &ty::AssociatedItem, + impl_c: &ty::AssocItem, impl_c_span: Span, - trait_c: &ty::AssociatedItem, + trait_c: &ty::AssocItem, impl_trait_ref: ty::TraitRef<'tcx>) { debug!("compare_const_impl(impl_trait_ref={:?})", impl_trait_ref); diff --git a/src/librustc_typeck/check/demand.rs b/src/librustc_typeck/check/demand.rs index a4e687b8f9080..724f8d886e8a7 100644 --- a/src/librustc_typeck/check/demand.rs +++ b/src/librustc_typeck/check/demand.rs @@ -8,7 +8,7 @@ use syntax_pos::Span; use rustc::hir; use rustc::hir::Node; use rustc::hir::{print, lowering::is_range_literal}; -use rustc::ty::{self, Ty, AssociatedItem}; +use rustc::ty::{self, Ty, AssocItem}; use rustc::ty::adjustment::AllowTwoPhase; use errors::{Applicability, DiagnosticBuilder}; @@ -179,7 +179,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } pub fn get_conversion_methods(&self, span: Span, expected: Ty<'tcx>, checked_ty: Ty<'tcx>) - -> Vec { + -> Vec { let mut methods = self.probe_for_return_type(span, probe::Mode::MethodCall, expected, @@ -205,9 +205,9 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } // This function checks if the method isn't static and takes other arguments than `self`. - fn has_no_input_arg(&self, method: &AssociatedItem) -> bool { + fn has_no_input_arg(&self, method: &AssocItem) -> bool { match method.kind { - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { self.tcx.fn_sig(method.def_id).inputs().skip_binder().len() == 1 } _ => false, diff --git a/src/librustc_typeck/check/method/mod.rs b/src/librustc_typeck/check/method/mod.rs index a4b1687ea5301..65bc06b65e1fc 100644 --- a/src/librustc_typeck/check/method/mod.rs +++ b/src/librustc_typeck/check/method/mod.rs @@ -71,7 +71,7 @@ pub struct NoMatchData<'tcx> { pub static_candidates: Vec, pub unsatisfied_predicates: Vec>, pub out_of_scope_traits: Vec, - pub lev_candidate: Option, + pub lev_candidate: Option, pub mode: probe::Mode, } @@ -79,7 +79,7 @@ impl<'tcx> NoMatchData<'tcx> { pub fn new(static_candidates: Vec, unsatisfied_predicates: Vec>, out_of_scope_traits: Vec, - lev_candidate: Option, + lev_candidate: Option, mode: probe::Mode) -> Self { NoMatchData { @@ -450,7 +450,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { /// Finds item with name `item_name` defined in impl/trait `def_id` /// and return it, or `None`, if no such item was defined there. pub fn associated_item(&self, def_id: DefId, item_name: ast::Ident, ns: Namespace) - -> Option { + -> Option { self.tcx.associated_items(def_id).find(|item| { Namespace::from(item.kind) == ns && self.tcx.hygienic_eq(item_name, item.ident, def_id) diff --git a/src/librustc_typeck/check/method/probe.rs b/src/librustc_typeck/check/method/probe.rs index 590ae9d46e8db..596ce008099a6 100644 --- a/src/librustc_typeck/check/method/probe.rs +++ b/src/librustc_typeck/check/method/probe.rs @@ -89,7 +89,7 @@ impl<'a, 'gcx, 'tcx> Deref for ProbeContext<'a, 'gcx, 'tcx> { #[derive(Debug)] struct Candidate<'tcx> { // Candidates are (I'm not quite sure, but they are mostly) basically - // some metadata on top of a `ty::AssociatedItem` (without substs). + // some metadata on top of a `ty::AssocItem` (without substs). // // However, method probing wants to be able to evaluate the predicates // for a function with the substs applied - for example, if a function @@ -121,7 +121,7 @@ struct Candidate<'tcx> { // if `T: Sized`. xform_self_ty: Ty<'tcx>, xform_ret_ty: Option>, - item: ty::AssociatedItem, + item: ty::AssocItem, kind: CandidateKind<'tcx>, import_ids: SmallVec<[hir::HirId; 1]>, } @@ -146,7 +146,7 @@ enum ProbeResult { #[derive(Debug, PartialEq, Clone)] pub struct Pick<'tcx> { - pub item: ty::AssociatedItem, + pub item: ty::AssocItem, pub kind: PickKind<'tcx>, pub import_ids: SmallVec<[hir::HirId; 1]>, @@ -213,7 +213,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { return_type: Ty<'tcx>, self_ty: Ty<'tcx>, scope_expr_id: hir::HirId) - -> Vec { + -> Vec { debug!("probe(self_ty={:?}, return_type={}, scope_expr_id={})", self_ty, return_type, @@ -812,7 +812,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { mut mk_cand: F) where F: for<'b> FnMut(&mut ProbeContext<'b, 'gcx, 'tcx>, ty::PolyTraitRef<'tcx>, - ty::AssociatedItem) + ty::AssocItem) { let tcx = self.tcx; for bound_trait_ref in traits::transitive_bounds(tcx, bounds) { @@ -861,11 +861,11 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { } pub fn matches_return_type(&self, - method: &ty::AssociatedItem, + method: &ty::AssocItem, self_ty: Option>, expected: Ty<'tcx>) -> bool { match method.kind { - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { let fty = self.tcx.fn_sig(method.def_id); self.probe(|_| { let substs = self.fresh_substs_for_item(self.span, method.def_id); @@ -1425,7 +1425,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { /// Similarly to `probe_for_return_type`, this method attempts to find the best matching /// candidate method where the method name may have been misspelt. Similarly to other /// Levenshtein based suggestions, we provide at most one such suggestion. - fn probe_for_lev_candidate(&mut self) -> Result, MethodError<'tcx>> { + fn probe_for_lev_candidate(&mut self) -> Result, MethodError<'tcx>> { debug!("Probing for method names similar to {:?}", self.method_name); @@ -1441,7 +1441,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { let method_names = pcx.candidate_method_names(); pcx.allow_similar_names = false; - let applicable_close_candidates: Vec = method_names + let applicable_close_candidates: Vec = method_names .iter() .filter_map(|&method_name| { pcx.reset(); @@ -1474,7 +1474,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { /////////////////////////////////////////////////////////////////////////// // MISCELLANY - fn has_applicable_self(&self, item: &ty::AssociatedItem) -> bool { + fn has_applicable_self(&self, item: &ty::AssocItem) -> bool { // "Fast track" -- check for usage of sugar when in method call // mode. // @@ -1483,9 +1483,9 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { match self.mode { Mode::MethodCall => item.method_has_self_argument, Mode::Path => match item.kind { - ty::AssociatedKind::Existential | - ty::AssociatedKind::Type => false, - ty::AssociatedKind::Method | ty::AssociatedKind::Const => true + ty::AssocKind::Existential | + ty::AssocKind::Type => false, + ty::AssocKind::Method | ty::AssocKind::Const => true }, } // FIXME -- check for types that deref to `Self`, @@ -1501,11 +1501,11 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { } fn xform_self_ty(&self, - item: &ty::AssociatedItem, + item: &ty::AssocItem, impl_ty: Ty<'tcx>, substs: SubstsRef<'tcx>) -> (Ty<'tcx>, Option>) { - if item.kind == ty::AssociatedKind::Method && self.mode == Mode::MethodCall { + if item.kind == ty::AssocKind::Method && self.mode == Mode::MethodCall { let sig = self.xform_method_sig(item.def_id, substs); (sig.inputs()[0], Some(sig.output())) } else { @@ -1610,7 +1610,7 @@ impl<'a, 'gcx, 'tcx> ProbeContext<'a, 'gcx, 'tcx> { /// Finds the method with the appropriate name (or return type, as the case may be). If /// `allow_similar_names` is set, find methods with close-matching names. - fn impl_or_trait_item(&self, def_id: DefId) -> Vec { + fn impl_or_trait_item(&self, def_id: DefId) -> Vec { if let Some(name) = self.method_name { if self.allow_similar_names { let max_dist = max(name.as_str().len(), 3) / 3; diff --git a/src/librustc_typeck/check/mod.rs b/src/librustc_typeck/check/mod.rs index 655bf5722ae5a..a22e3d4d7066d 100644 --- a/src/librustc_typeck/check/mod.rs +++ b/src/librustc_typeck/check/mod.rs @@ -1499,17 +1499,17 @@ fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, trait_def: &ty::TraitDef, - trait_item: &ty::AssociatedItem, + trait_item: &ty::AssocItem, impl_id: DefId, impl_item: &hir::ImplItem) { let ancestors = trait_def.ancestors(tcx, impl_id); let kind = match impl_item.node { - hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const, - hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method, - hir::ImplItemKind::Existential(..) => ty::AssociatedKind::Existential, - hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type + hir::ImplItemKind::Const(..) => ty::AssocKind::Const, + hir::ImplItemKind::Method(..) => ty::AssocKind::Method, + hir::ImplItemKind::Existential(..) => ty::AssocKind::Existential, + hir::ImplItemKind::Type(_) => ty::AssocKind::Type }; let parent = ancestors.defs(tcx, trait_item.ident, kind, trait_def.def_id).nth(1) @@ -1560,7 +1560,7 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, match impl_item.node { hir::ImplItemKind::Const(..) => { // Find associated const definition. - if ty_trait_item.kind == ty::AssociatedKind::Const { + if ty_trait_item.kind == ty::AssocKind::Const { compare_const_impl(tcx, &ty_impl_item, impl_item.span, @@ -1583,7 +1583,7 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } hir::ImplItemKind::Method(..) => { let trait_span = tcx.hir().span_if_local(ty_trait_item.def_id); - if ty_trait_item.kind == ty::AssociatedKind::Method { + if ty_trait_item.kind == ty::AssocKind::Method { compare_impl_method(tcx, &ty_impl_item, impl_item.span, @@ -1605,7 +1605,7 @@ fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, } hir::ImplItemKind::Existential(..) | hir::ImplItemKind::Type(_) => { - if ty_trait_item.kind == ty::AssociatedKind::Type { + if ty_trait_item.kind == ty::AssocKind::Type { if ty_trait_item.defaultness.has_value() { overridden_associated_type = Some(impl_item); } @@ -3746,7 +3746,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { Res::Def(DefKind::Struct, _) | Res::Def(DefKind::Union, _) | Res::Def(DefKind::TyAlias, _) - | Res::Def(DefKind::AssociatedTy, _) + | Res::Def(DefKind::AssocTy, _) | Res::SelfTy(..) => { match ty.sty { ty::Adt(adt, substs) if !adt.is_enum() => { @@ -5297,7 +5297,7 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> { } } DefKind::Method - | DefKind::AssociatedConst => { + | DefKind::AssocConst => { let container = tcx.associated_item(def_id).container; debug!("instantiate_value_path: def_id={:?} container={:?}", def_id, container); match container { diff --git a/src/librustc_typeck/check/wfcheck.rs b/src/librustc_typeck/check/wfcheck.rs index 7e7a8d5926673..e11172ae36d9b 100644 --- a/src/librustc_typeck/check/wfcheck.rs +++ b/src/librustc_typeck/check/wfcheck.rs @@ -190,12 +190,12 @@ fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, }; match item.kind { - ty::AssociatedKind::Const => { + ty::AssocKind::Const => { let ty = fcx.tcx.type_of(item.def_id); let ty = fcx.normalize_associated_types_in(span, &ty); fcx.register_wf_obligation(ty, span, code.clone()); } - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { reject_shadowing_parameters(fcx.tcx, item.def_id); let sig = fcx.tcx.fn_sig(item.def_id); let sig = fcx.normalize_associated_types_in(span, &sig); @@ -204,14 +204,14 @@ fn check_associated_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, let sig_if_method = sig_if_method.expect("bad signature for method"); check_method_receiver(fcx, sig_if_method, &item, self_ty); } - ty::AssociatedKind::Type => { + ty::AssocKind::Type => { if item.defaultness.has_value() { let ty = fcx.tcx.type_of(item.def_id); let ty = fcx.normalize_associated_types_in(span, &ty); fcx.register_wf_obligation(ty, span, code.clone()); } } - ty::AssociatedKind::Existential => { + ty::AssocKind::Existential => { // do nothing, existential types check themselves } } @@ -748,7 +748,7 @@ fn check_existential_types<'a, 'fcx, 'gcx, 'tcx>( fn check_method_receiver<'fcx, 'gcx, 'tcx>(fcx: &FnCtxt<'fcx, 'gcx, 'tcx>, method_sig: &hir::MethodSig, - method: &ty::AssociatedItem, + method: &ty::AssocItem, self_ty: Ty<'tcx>) { // check that the method has a valid receiver type, given the type `Self` diff --git a/src/librustc_typeck/impl_wf_check.rs b/src/librustc_typeck/impl_wf_check.rs index e7ec5bc81c769..87476d37b35e7 100644 --- a/src/librustc_typeck/impl_wf_check.rs +++ b/src/librustc_typeck/impl_wf_check.rs @@ -111,7 +111,7 @@ fn enforce_impl_params_are_constrained<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, .map(|item_ref| tcx.hir().local_def_id_from_hir_id(item_ref.id.hir_id)) .filter(|&def_id| { let item = tcx.associated_item(def_id); - item.kind == ty::AssociatedKind::Type && item.defaultness.has_value() + item.kind == ty::AssocKind::Type && item.defaultness.has_value() }) .flat_map(|def_id| { cgp::parameters_for(&tcx.type_of(def_id), true) diff --git a/src/librustc_typeck/namespace.rs b/src/librustc_typeck/namespace.rs index e8f6272810a37..9b6c5bd9f429f 100644 --- a/src/librustc_typeck/namespace.rs +++ b/src/librustc_typeck/namespace.rs @@ -8,13 +8,13 @@ pub enum Namespace { Value, } -impl From for Namespace { - fn from(a_kind: ty::AssociatedKind) -> Self { +impl From for Namespace { + fn from(a_kind: ty::AssocKind) -> Self { match a_kind { - ty::AssociatedKind::Existential | - ty::AssociatedKind::Type => Namespace::Type, - ty::AssociatedKind::Const | - ty::AssociatedKind::Method => Namespace::Value, + ty::AssocKind::Existential | + ty::AssocKind::Type => Namespace::Type, + ty::AssocKind::Const | + ty::AssocKind::Method => Namespace::Value, } } } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index 9c3f522d8470f..5dca91d27bbe8 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -428,10 +428,10 @@ impl Item { self.type_() == ItemType::Variant } pub fn is_associated_type(&self) -> bool { - self.type_() == ItemType::AssociatedType + self.type_() == ItemType::AssocType } pub fn is_associated_const(&self) -> bool { - self.type_() == ItemType::AssociatedConst + self.type_() == ItemType::AssocConst } pub fn is_method(&self) -> bool { self.type_() == ItemType::Method @@ -560,8 +560,8 @@ pub enum ItemEnum { MacroItem(Macro), ProcMacroItem(ProcMacro), PrimitiveItem(PrimitiveType), - AssociatedConstItem(Type, Option), - AssociatedTypeItem(Vec, Option), + AssocConstItem(Type, Option), + AssocTypeItem(Vec, Option), /// An item that has been stripped by a rustdoc pass StrippedItem(Box), KeywordItem(String), @@ -588,7 +588,7 @@ impl ItemEnum { pub fn is_associated(&self) -> bool { match *self { ItemEnum::TypedefItem(_, _) | - ItemEnum::AssociatedTypeItem(_, _) => true, + ItemEnum::AssocTypeItem(_, _) => true, _ => false, } } @@ -2206,7 +2206,7 @@ impl Clean for hir::TraitItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.node { hir::TraitItemKind::Const(ref ty, default) => { - AssociatedConstItem(ty.clean(cx), + AssocConstItem(ty.clean(cx), default.map(|e| print_const_expr(cx, e))) } hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) => { @@ -2226,7 +2226,7 @@ impl Clean for hir::TraitItem { }) } hir::TraitItemKind::Type(ref bounds, ref default) => { - AssociatedTypeItem(bounds.clean(cx), default.clean(cx)) + AssocTypeItem(bounds.clean(cx), default.clean(cx)) } }; let local_did = cx.tcx.hir().local_def_id_from_hir_id(self.hir_id); @@ -2247,7 +2247,7 @@ impl Clean for hir::ImplItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.node { hir::ImplItemKind::Const(ref ty, expr) => { - AssociatedConstItem(ty.clean(cx), + AssocConstItem(ty.clean(cx), Some(print_const_expr(cx, expr))) } hir::ImplItemKind::Method(ref sig, body) => { @@ -2276,19 +2276,19 @@ impl Clean for hir::ImplItem { } } -impl<'tcx> Clean for ty::AssociatedItem { +impl<'tcx> Clean for ty::AssocItem { fn clean(&self, cx: &DocContext<'_>) -> Item { let inner = match self.kind { - ty::AssociatedKind::Const => { + ty::AssocKind::Const => { let ty = cx.tcx.type_of(self.def_id); let default = if self.defaultness.has_value() { Some(inline::print_inlined_const(cx, self.def_id)) } else { None }; - AssociatedConstItem(ty.clean(cx), default) + AssocConstItem(ty.clean(cx), default) } - ty::AssociatedKind::Method => { + ty::AssocKind::Method => { let generics = (cx.tcx.generics_of(self.def_id), &cx.tcx.explicit_predicates_of(self.def_id)).clean(cx); let sig = cx.tcx.fn_sig(self.def_id); @@ -2359,7 +2359,7 @@ impl<'tcx> Clean for ty::AssociatedItem { }) } } - ty::AssociatedKind::Type => { + ty::AssocKind::Type => { let my_name = self.ident.name.clean(cx); if let ty::TraitContainer(did) = self.container { @@ -2404,7 +2404,7 @@ impl<'tcx> Clean for ty::AssociatedItem { None }; - AssociatedTypeItem(bounds, ty.clean(cx)) + AssocTypeItem(bounds, ty.clean(cx)) } else { TypedefItem(Typedef { type_: cx.tcx.type_of(self.def_id).clean(cx), @@ -2415,7 +2415,7 @@ impl<'tcx> Clean for ty::AssociatedItem { }, true) } } - ty::AssociatedKind::Existential => unimplemented!(), + ty::AssocKind::Existential => unimplemented!(), }; let visibility = match self.container { @@ -4179,7 +4179,7 @@ fn resolve_type(cx: &DocContext<'_>, } Res::SelfTy(..) | Res::Def(DefKind::TyParam, _) - | Res::Def(DefKind::AssociatedTy, _) => true, + | Res::Def(DefKind::AssocTy, _) => true, _ => false, }; let did = register_res(&*cx, path.res); diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index 2784d5b3e10a0..58e55d570a4f3 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -722,7 +722,7 @@ fn fmt_type(t: &clean::Type, f: &mut fmt::Formatter<'_>, use_absolute: bool) -> "{name}", url = url, - shortty = ItemType::AssociatedType, + shortty = ItemType::AssocType, name = name, path = path.join("::"))?; } diff --git a/src/librustdoc/html/item_type.rs b/src/librustdoc/html/item_type.rs index 366e60b3ad920..3f3f4c85e81fc 100644 --- a/src/librustdoc/html/item_type.rs +++ b/src/librustdoc/html/item_type.rs @@ -33,9 +33,9 @@ pub enum ItemType { Variant = 13, Macro = 14, Primitive = 15, - AssociatedType = 16, + AssocType = 16, Constant = 17, - AssociatedConst = 18, + AssocConst = 18, Union = 19, ForeignType = 20, Keyword = 21, @@ -83,8 +83,8 @@ impl<'a> From<&'a clean::Item> for ItemType { clean::ForeignStaticItem(..) => ItemType::Static, // no ForeignStatic clean::MacroItem(..) => ItemType::Macro, clean::PrimitiveItem(..) => ItemType::Primitive, - clean::AssociatedConstItem(..) => ItemType::AssociatedConst, - clean::AssociatedTypeItem(..) => ItemType::AssociatedType, + clean::AssocConstItem(..) => ItemType::AssocConst, + clean::AssocTypeItem(..) => ItemType::AssocType, clean::ForeignTypeItem => ItemType::ForeignType, clean::KeywordItem(..) => ItemType::Keyword, clean::TraitAliasItem(..) => ItemType::TraitAlias, @@ -141,9 +141,9 @@ impl ItemType { ItemType::Variant => "variant", ItemType::Macro => "macro", ItemType::Primitive => "primitive", - ItemType::AssociatedType => "associatedtype", + ItemType::AssocType => "associatedtype", ItemType::Constant => "constant", - ItemType::AssociatedConst => "associatedconstant", + ItemType::AssocConst => "associatedconstant", ItemType::ForeignType => "foreigntype", ItemType::Keyword => "keyword", ItemType::Existential => "existential", @@ -162,7 +162,7 @@ impl ItemType { ItemType::Typedef | ItemType::Trait | ItemType::Primitive | - ItemType::AssociatedType | + ItemType::AssocType | ItemType::Existential | ItemType::TraitAlias | ItemType::ForeignType => NameSpace::Type, @@ -177,7 +177,7 @@ impl ItemType { ItemType::StructField | ItemType::Variant | ItemType::Constant | - ItemType::AssociatedConst => NameSpace::Value, + ItemType::AssocConst => NameSpace::Value, ItemType::Macro | ItemType::ProcAttribute | diff --git a/src/librustdoc/html/render.rs b/src/librustdoc/html/render.rs index b628bd450d314..efb59c22012bc 100644 --- a/src/librustdoc/html/render.rs +++ b/src/librustdoc/html/render.rs @@ -1554,12 +1554,12 @@ impl DocFolder for Cache { if let Some(ref s) = item.name { let (parent, is_inherent_impl_item) = match item.inner { clean::StrippedItem(..) => ((None, None), false), - clean::AssociatedConstItem(..) | + clean::AssocConstItem(..) | clean::TypedefItem(_, true) if self.parent_is_trait_impl => { // skip associated items in trait impls ((None, None), false) } - clean::AssociatedTypeItem(..) | + clean::AssocTypeItem(..) | clean::TyMethodItem(..) | clean::StructFieldItem(..) | clean::VariantItem(..) => { @@ -1567,7 +1567,7 @@ impl DocFolder for Cache { Some(&self.stack[..self.stack.len() - 1])), false) } - clean::MethodItem(..) | clean::AssociatedConstItem(..) => { + clean::MethodItem(..) | clean::AssocConstItem(..) => { if self.parent_stack.is_empty() { ((None, None), false) } else { @@ -3366,7 +3366,7 @@ fn naive_assoc_href(it: &clean::Item, link: AssocItemLink<'_>) -> String { let name = it.name.as_ref().unwrap(); let ty = match it.type_() { - Typedef | AssociatedType => AssociatedType, + Typedef | AssocType => AssocType, s@_ => s, }; @@ -3511,11 +3511,11 @@ fn render_assoc_item(w: &mut fmt::Formatter<'_>, clean::MethodItem(ref m) => { method(w, item, m.header, &m.generics, &m.decl, link, parent) } - clean::AssociatedConstItem(ref ty, ref default) => { + clean::AssocConstItem(ref ty, ref default) => { assoc_const(w, item, ty, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }) } - clean::AssociatedTypeItem(ref bounds, ref default) => { + clean::AssocTypeItem(ref bounds, ref default) => { assoc_type(w, item, bounds, default.as_ref(), link, if parent == ItemType::Trait { " " } else { "" }) } @@ -4247,14 +4247,14 @@ fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocIt } } clean::TypedefItem(ref tydef, _) => { - let id = cx.derive_id(format!("{}.{}", ItemType::AssociatedType, name)); + let id = cx.derive_id(format!("{}.{}", ItemType::AssocType, name)); let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space())); write!(w, "

", id, item_type, extra_class)?; write!(w, "", ns_id)?; assoc_type(w, item, &Vec::new(), Some(&tydef.type_), link.anchor(&id), "")?; write!(w, "

")?; } - clean::AssociatedConstItem(ref ty, ref default) => { + clean::AssocConstItem(ref ty, ref default) => { let id = cx.derive_id(format!("{}.{}", item_type, name)); let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space())); write!(w, "

", id, item_type, extra_class)?; @@ -4268,7 +4268,7 @@ fn render_impl(w: &mut fmt::Formatter<'_>, cx: &Context, i: &Impl, link: AssocIt } write!(w, "

")?; } - clean::AssociatedTypeItem(ref bounds, ref default) => { + clean::AssocTypeItem(ref bounds, ref default) => { let id = cx.derive_id(format!("{}.{}", item_type, name)); let ns_id = cx.derive_id(format!("{}.{}", name, item_type.name_space())); write!(w, "

", id, item_type, extra_class)?; @@ -4946,8 +4946,8 @@ fn item_ty_to_strs(ty: &ItemType) -> (&'static str, &'static str) { ItemType::Variant => ("variants", "Variants"), ItemType::Macro => ("macros", "Macros"), ItemType::Primitive => ("primitives", "Primitive Types"), - ItemType::AssociatedType => ("associated-types", "Associated Types"), - ItemType::AssociatedConst => ("associated-consts", "Associated Constants"), + ItemType::AssocType => ("associated-types", "Associated Types"), + ItemType::AssocConst => ("associated-consts", "Associated Constants"), ItemType::ForeignType => ("foreign-types", "Foreign Types"), ItemType::Keyword => ("keywords", "Keywords"), ItemType::Existential => ("existentials", "Existentials"), @@ -4974,7 +4974,7 @@ fn sidebar_module(fmt: &mut fmt::Formatter<'_>, _it: &clean::Item, ItemType::Enum, ItemType::Constant, ItemType::Static, ItemType::Trait, ItemType::Function, ItemType::Typedef, ItemType::Union, ItemType::Impl, ItemType::TyMethod, ItemType::Method, ItemType::StructField, ItemType::Variant, - ItemType::AssociatedType, ItemType::AssociatedConst, ItemType::ForeignType] { + ItemType::AssocType, ItemType::AssocConst, ItemType::ForeignType] { if items.iter().any(|it| !it.is_stripped() && it.type_() == myty) { let (short, name) = item_ty_to_strs(&myty); sidebar.push_str(&format!("
  • {name}
  • ", diff --git a/src/librustdoc/passes/collect_intra_doc_links.rs b/src/librustdoc/passes/collect_intra_doc_links.rs index 2c382a1c17596..860ea18a58ad0 100644 --- a/src/librustdoc/passes/collect_intra_doc_links.rs +++ b/src/librustdoc/passes/collect_intra_doc_links.rs @@ -75,8 +75,8 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { // In case this is a trait item, skip the // early return and try looking for the trait. let value = match result.res { - Res::Def(DefKind::Method, _) | Res::Def(DefKind::AssociatedConst, _) => true, - Res::Def(DefKind::AssociatedTy, _) => false, + Res::Def(DefKind::Method, _) | Res::Def(DefKind::AssocConst, _) => true, + Res::Def(DefKind::AssocTy, _) => false, Res::Def(DefKind::Variant, _) => return handle_variant(cx, result.res), // Not a trait item; just return what we found. _ => return Ok((result.res, None)) @@ -120,7 +120,7 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { return cx.tcx.associated_items(did) .find(|item| item.ident.name == item_name) .and_then(|item| match item.kind { - ty::AssociatedKind::Method => Some("method"), + ty::AssocKind::Method => Some("method"), _ => None, }) .map(|out| (prim, Some(format!("{}#{}.{}", path, out, item_name)))) @@ -143,8 +143,8 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { .find(|item| item.ident.name == item_name); if let Some(item) = item { let out = match item.kind { - ty::AssociatedKind::Method if ns == ValueNS => "method", - ty::AssociatedKind::Const if ns == ValueNS => "associatedconstant", + ty::AssocKind::Method if ns == ValueNS => "method", + ty::AssocKind::Const if ns == ValueNS => "associatedconstant", _ => return Err(()) }; Ok((ty.res, Some(format!("{}.{}", out, item_name)))) @@ -181,9 +181,9 @@ impl<'a, 'tcx> LinkCollector<'a, 'tcx> { .find(|item| item.ident.name == item_name); if let Some(item) = item { let kind = match item.kind { - ty::AssociatedKind::Const if ns == ValueNS => "associatedconstant", - ty::AssociatedKind::Type if ns == TypeNS => "associatedtype", - ty::AssociatedKind::Method if ns == ValueNS => { + ty::AssocKind::Const if ns == ValueNS => "associatedconstant", + ty::AssocKind::Type if ns == TypeNS => "associatedtype", + ty::AssocKind::Method if ns == ValueNS => { if item.defaultness.has_value() { "method" } else { diff --git a/src/librustdoc/passes/mod.rs b/src/librustdoc/passes/mod.rs index d9af33ac5b622..018ab5dea6081 100644 --- a/src/librustdoc/passes/mod.rs +++ b/src/librustdoc/passes/mod.rs @@ -172,7 +172,7 @@ impl<'a> DocFolder for Stripper<'a> { | clean::ForeignStaticItem(..) | clean::ConstantItem(..) | clean::UnionItem(..) - | clean::AssociatedConstItem(..) + | clean::AssocConstItem(..) | clean::TraitAliasItem(..) | clean::ForeignTypeItem => { if i.def_id.is_local() { @@ -214,7 +214,7 @@ impl<'a> DocFolder for Stripper<'a> { clean::PrimitiveItem(..) => {} // Associated types are never stripped - clean::AssociatedTypeItem(..) => {} + clean::AssocTypeItem(..) => {} // Keywords are never stripped clean::KeywordItem(..) => {} From fd1998914dcd2822a11367d3761d8574cb4eb634 Mon Sep 17 00:00:00 2001 From: vishalsodani Date: Sat, 25 May 2019 02:48:01 +0000 Subject: [PATCH 03/12] Fix spelling in release notes --- RELEASES.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/RELEASES.md b/RELEASES.md index 4185961187b39..91e3c5f721952 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -157,7 +157,7 @@ Libraries produce a warning if their returning type is unused. - [The methods `checked_pow`, `saturating_pow`, `wrapping_pow`, and `overflowing_pow` are now available for all numeric types.][57873] These are - equivalvent to methods such as `wrapping_add` for the `pow` operation. + equivalent to methods such as `wrapping_add` for the `pow` operation. Stabilized APIs From 72145ea2fe18cc2eb2e61c89f5adfe9c1c6c7cb7 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 25 May 2019 09:11:20 +0200 Subject: [PATCH 04/12] MaybeUninit doctest: remove unnecessary type ascription --- src/libcore/mem.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libcore/mem.rs b/src/libcore/mem.rs index 56869f38a4f6b..ce4aee7ebc54f 100644 --- a/src/libcore/mem.rs +++ b/src/libcore/mem.rs @@ -982,7 +982,7 @@ impl DerefMut for ManuallyDrop { /// out.write(vec![1, 2, 3]); /// } /// -/// let mut v: MaybeUninit> = MaybeUninit::uninit(); +/// let mut v = MaybeUninit::uninit(); /// unsafe { make_vec(v.as_mut_ptr()); } /// // Now we know `v` is initialized! This also makes sure the vector gets /// // properly dropped. @@ -1071,7 +1071,7 @@ impl DerefMut for ManuallyDrop { /// optimizations, potentially resulting in a larger size: /// /// ```rust -/// # use std::mem::{MaybeUninit, size_of, align_of}; +/// # use std::mem::{MaybeUninit, size_of}; /// assert_eq!(size_of::>(), 1); /// assert_eq!(size_of::>>(), 2); /// ``` From 9d82826e555e658680cf6ef246ae6d088f300d1d Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 25 May 2019 10:11:00 +0200 Subject: [PATCH 05/12] add test checking that Vec push/pop does not invalidate pointers --- src/liballoc/tests/vec.rs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/liballoc/tests/vec.rs b/src/liballoc/tests/vec.rs index 3307bdf94f985..5ddac673c9ff1 100644 --- a/src/liballoc/tests/vec.rs +++ b/src/liballoc/tests/vec.rs @@ -1152,3 +1152,24 @@ fn test_try_reserve_exact() { } } + +#[test] +fn test_stable_push_pop() { + // Test that, if we reserved enough space, adding and removing elements does not + // invalidate references into the vector (such as `v0`). This test also + // runs in Miri, which would detect such problems. + let mut v = Vec::with_capacity(10); + v.push(13); + + // laundering the lifetime -- we take care that `v` does not reallocate, so that's okay. + let v0 = unsafe { &*(&v[0] as *const _) }; + + // Now do a bunch of things and occasionally use `v0` again to assert it is still valid. + v.push(1); + v.push(2); + v.insert(1, 1); + assert_eq!(*v0, 13); + v.remove(1); + v.pop().unwrap(); + assert_eq!(*v0, 13); +} From 428ab7e1bd77b82db30dc574b3f9c4fe0a7c77f6 Mon Sep 17 00:00:00 2001 From: Ralf Jung Date: Sat, 25 May 2019 10:36:07 +0200 Subject: [PATCH 06/12] shadow as_ptr as as_mut_ptr in Vec to avoid going through Deref --- src/liballoc/vec.rs | 78 +++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 71 insertions(+), 7 deletions(-) diff --git a/src/liballoc/vec.rs b/src/liballoc/vec.rs index dc661a267e2a6..5cb91395b7bf7 100644 --- a/src/liballoc/vec.rs +++ b/src/liballoc/vec.rs @@ -735,6 +735,75 @@ impl Vec { self } + /// Returns a raw pointer to the vector's buffer. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up pointing to garbage. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// The caller must also ensure that the memory the pointer (non-transitively) points to + /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer + /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`]. + /// + /// # Examples + /// + /// ``` + /// let x = vec![1, 2, 4]; + /// let x_ptr = x.as_ptr(); + /// + /// unsafe { + /// for i in 0..x.len() { + /// assert_eq!(*x_ptr.add(i), 1 << i); + /// } + /// } + /// ``` + /// + /// [`as_mut_ptr`]: #method.as_mut_ptr + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[inline] + pub fn as_ptr(&self) -> *const T { + // We shadow the slice method of the same name to avoid going through + // `deref`, which creates an intermediate reference. + let ptr = self.buf.ptr(); + unsafe { assume(!ptr.is_null()); } + ptr + } + + /// Returns an unsafe mutable pointer to the vector's buffer. + /// + /// The caller must ensure that the vector outlives the pointer this + /// function returns, or else it will end up pointing to garbage. + /// Modifying the vector may cause its buffer to be reallocated, + /// which would also make any pointers to it invalid. + /// + /// # Examples + /// + /// ``` + /// // Allocate vector big enough for 4 elements. + /// let size = 4; + /// let mut x: Vec = Vec::with_capacity(size); + /// let x_ptr = x.as_mut_ptr(); + /// + /// // Initialize elements via raw pointer writes, then set length. + /// unsafe { + /// for i in 0..size { + /// *x_ptr.add(i) = i as i32; + /// } + /// x.set_len(size); + /// } + /// assert_eq!(&*x, &[0,1,2,3]); + /// ``` + #[stable(feature = "vec_as_ptr", since = "1.37.0")] + #[inline] + pub fn as_mut_ptr(&mut self) -> *mut T { + // We shadow the slice method of the same name to avoid going through + // `deref_mut`, which creates an intermediate reference. + let ptr = self.buf.ptr(); + unsafe { assume(!ptr.is_null()); } + ptr + } + /// Forces the length of the vector to `new_len`. /// /// This is a low-level operation that maintains none of the normal @@ -1706,9 +1775,7 @@ impl ops::Deref for Vec { fn deref(&self) -> &[T] { unsafe { - let p = self.buf.ptr(); - assume(!p.is_null()); - slice::from_raw_parts(p, self.len) + slice::from_raw_parts(self.as_ptr(), self.len) } } } @@ -1717,9 +1784,7 @@ impl ops::Deref for Vec { impl ops::DerefMut for Vec { fn deref_mut(&mut self) -> &mut [T] { unsafe { - let ptr = self.buf.ptr(); - assume(!ptr.is_null()); - slice::from_raw_parts_mut(ptr, self.len) + slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) } } } @@ -1754,7 +1819,6 @@ impl IntoIterator for Vec { fn into_iter(mut self) -> IntoIter { unsafe { let begin = self.as_mut_ptr(); - assume(!begin.is_null()); let end = if mem::size_of::() == 0 { arith_offset(begin as *const i8, self.len() as isize) as *const T } else { From a5e9d8240ece4a1a14178b7de15d2a874aef6d10 Mon Sep 17 00:00:00 2001 From: Fabian Drinck Date: Sat, 25 May 2019 11:40:06 +0200 Subject: [PATCH 07/12] Auto-derive Encode and Decode implementations --- src/librustc/hir/map/definitions.rs | 26 +------------------------- 1 file changed, 1 insertion(+), 25 deletions(-) diff --git a/src/librustc/hir/map/definitions.rs b/src/librustc/hir/map/definitions.rs index 1cc9a2c0e8a1b..2324c3f04284f 100644 --- a/src/librustc/hir/map/definitions.rs +++ b/src/librustc/hir/map/definitions.rs @@ -10,7 +10,6 @@ use crate::ich::Fingerprint; use rustc_data_structures::fx::FxHashMap; use rustc_data_structures::indexed_vec::{IndexVec}; use rustc_data_structures::stable_hasher::StableHasher; -use serialize::{Encodable, Decodable, Encoder, Decoder}; use crate::session::CrateDisambiguator; use std::borrow::Borrow; use std::fmt::Write; @@ -25,14 +24,13 @@ use crate::util::nodemap::NodeMap; /// Internally the DefPathTable holds a tree of DefKeys, where each DefKey /// stores the DefIndex of its parent. /// There is one DefPathTable for each crate. -#[derive(Clone, Default)] +#[derive(Clone, Default, RustcDecodable, RustcEncodable)] pub struct DefPathTable { index_to_key: Vec, def_path_hashes: Vec, } impl DefPathTable { - fn allocate(&mut self, key: DefKey, def_path_hash: DefPathHash) @@ -86,28 +84,6 @@ impl DefPathTable { } } - -impl Encodable for DefPathTable { - fn encode(&self, s: &mut S) -> Result<(), S::Error> { - // Index to key - self.index_to_key.encode(s)?; - - // DefPath hashes - self.def_path_hashes.encode(s)?; - - Ok(()) - } -} - -impl Decodable for DefPathTable { - fn decode(d: &mut D) -> Result { - Ok(DefPathTable { - index_to_key: Decodable::decode(d)?, - def_path_hashes : Decodable::decode(d)?, - }) - } -} - /// The definition table containing node definitions. /// It holds the `DefPathTable` for local `DefId`s/`DefPath`s and it also stores a /// mapping from `NodeId`s to local `DefId`s. From 9bfbbd2a786b7d69908f25e5d1f4170316f38726 Mon Sep 17 00:00:00 2001 From: Wesley Wiser Date: Sat, 25 May 2019 10:59:05 -0400 Subject: [PATCH 08/12] Add additional trace statements to the const propagator This makes it easier to figure out when const propagation fails. --- src/librustc_mir/transform/const_prop.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/src/librustc_mir/transform/const_prop.rs b/src/librustc_mir/transform/const_prop.rs index 8f3dd72c4f245..718cb5ce527ec 100644 --- a/src/librustc_mir/transform/const_prop.rs +++ b/src/librustc_mir/transform/const_prop.rs @@ -295,6 +295,7 @@ impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> { } fn eval_place(&mut self, place: &Place<'tcx>, source_info: SourceInfo) -> Option> { + trace!("eval_place(place={:?})", place); match *place { Place::Base(PlaceBase::Local(loc)) => self.places[loc].clone(), Place::Projection(ref proj) => match proj.elem { @@ -515,6 +516,7 @@ impl<'a, 'mir, 'tcx> ConstPropagator<'a, 'mir, 'tcx> { } fn replace_with_const(&self, rval: &mut Rvalue<'tcx>, value: Const<'tcx>, span: Span) { + trace!("attepting to replace {:?} with {:?}", rval, value); self.ecx.validate_operand( value, vec![], @@ -578,6 +580,10 @@ impl CanConstProp { // FIXME(oli-obk): lint variables until they are used in a condition // FIXME(oli-obk): lint if return value is constant *val = mir.local_kind(local) == LocalKind::Temp; + + if !*val { + trace!("local {:?} can't be propagated because it's not a temporary", local); + } } cpv.visit_mir(mir); cpv.can_const_prop @@ -597,6 +603,7 @@ impl<'tcx> Visitor<'tcx> for CanConstProp { // FIXME(oli-obk): we could be more powerful here, if the multiple writes // only occur in independent execution paths MutatingUse(MutatingUseContext::Store) => if self.found_assignment[local] { + trace!("local {:?} can't be propagated because of multiple assignments", local); self.can_const_prop[local] = false; } else { self.found_assignment[local] = true @@ -608,7 +615,10 @@ impl<'tcx> Visitor<'tcx> for CanConstProp { NonMutatingUse(NonMutatingUseContext::Projection) | MutatingUse(MutatingUseContext::Projection) | NonUse(_) => {}, - _ => self.can_const_prop[local] = false, + _ => { + trace!("local {:?} can't be propagaged because it's used: {:?}", local, context); + self.can_const_prop[local] = false; + }, } } } From 976541884f674127c33e08aaaf15c99b735701f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 23 May 2019 12:54:27 -0700 Subject: [PATCH 09/12] Tweak `self` arg not as first argument of a method diagnostic Mention that `self` is only valid on "associated functions" ``` error: unexpected `self` argument in function --> $DIR/self-in-function-arg.rs:1:15 | LL | fn foo(x:i32, self: i32) -> i32 { self } | ^^^^ not valid as function argument | = note: `self` is only valid as the first argument of an associated function ``` When it is a method, mention it must be first ``` error: unexpected `self` argument in function --> $DIR/trait-fn.rs:4:20 | LL | fn c(foo: u32, self) {} | ^^^^ must be the first associated function argument ``` --- src/libsyntax/parse/diagnostics.rs | 45 ++++++++++++++++++ src/libsyntax/parse/parser.rs | 47 ++++--------------- .../ui/invalid-self-argument/bare-fn-start.rs | 1 + .../bare-fn-start.stderr | 6 ++- src/test/ui/invalid-self-argument/bare-fn.rs | 1 + .../ui/invalid-self-argument/bare-fn.stderr | 6 ++- src/test/ui/invalid-self-argument/trait-fn.rs | 2 +- .../ui/invalid-self-argument/trait-fn.stderr | 2 +- src/test/ui/parser/self-in-function-arg.rs | 3 ++ .../ui/parser/self-in-function-arg.stderr | 10 ++++ 10 files changed, 80 insertions(+), 43 deletions(-) create mode 100644 src/test/ui/parser/self-in-function-arg.rs create mode 100644 src/test/ui/parser/self-in-function-arg.stderr diff --git a/src/libsyntax/parse/diagnostics.rs b/src/libsyntax/parse/diagnostics.rs index 810acc9cc923e..11f8eba033e9e 100644 --- a/src/libsyntax/parse/diagnostics.rs +++ b/src/libsyntax/parse/diagnostics.rs @@ -594,6 +594,51 @@ impl<'a> Parser<'a> { } } + crate fn recover_arg_parse(&mut self) -> PResult<'a, (P, P)> { + let pat = self.parse_pat(Some("argument name"))?; + self.expect(&token::Colon)?; + let ty = self.parse_ty()?; + + let mut err = self.diagnostic().struct_span_err_with_code( + pat.span, + "patterns aren't allowed in methods without bodies", + DiagnosticId::Error("E0642".into()), + ); + err.span_suggestion_short( + pat.span, + "give this argument a name or use an underscore to ignore it", + "_".to_owned(), + Applicability::MachineApplicable, + ); + err.emit(); + + // Pretend the pattern is `_`, to avoid duplicate errors from AST validation. + let pat = P(Pat { + node: PatKind::Wild, + span: pat.span, + id: ast::DUMMY_NODE_ID + }); + Ok((pat, ty)) + } + + crate fn recover_bad_self_arg( + &mut self, + mut arg: ast::Arg, + is_trait_item: bool, + ) -> PResult<'a, ast::Arg> { + let sp = arg.pat.span; + arg.ty.node = TyKind::Err; + let mut err = self.struct_span_err(sp, "unexpected `self` argument in function"); + if is_trait_item { + err.span_label(sp, "must be the first associated function argument"); + } else { + err.span_label(sp, "not valid as function argument"); + err.note("`self` is only valid as the first argument of an associated function"); + } + err.emit(); + Ok(arg) + } + crate fn consume_block(&mut self, delim: token::DelimToken) { let mut brace_depth = 0; loop { diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 56951ae08012a..b4b45fd9eff2b 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -1805,50 +1805,23 @@ impl<'a> Parser<'a> { } /// This version of parse arg doesn't necessarily require identifier names. - fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool, - allow_c_variadic: bool) -> PResult<'a, Arg> { - if let Ok(Some(_)) = self.parse_self_arg() { - let mut err = self.struct_span_err(self.prev_span, - "unexpected `self` argument in function"); - err.span_label(self.prev_span, - "`self` is only valid as the first argument of an associated function"); - return Err(err); + fn parse_arg_general( + &mut self, + require_name: bool, + is_trait_item: bool, + allow_c_variadic: bool, + ) -> PResult<'a, Arg> { + if let Ok(Some(arg)) = self.parse_self_arg() { + return self.recover_bad_self_arg(arg, is_trait_item); } let (pat, ty) = if require_name || self.is_named_argument() { - debug!("parse_arg_general parse_pat (require_name:{})", - require_name); + debug!("parse_arg_general parse_pat (require_name:{})", require_name); self.eat_incorrect_doc_comment("method arguments"); let pat = self.parse_pat(Some("argument name"))?; if let Err(mut err) = self.expect(&token::Colon) { - // If we find a pattern followed by an identifier, it could be an (incorrect) - // C-style parameter declaration. - if self.check_ident() && self.look_ahead(1, |t| { - *t == token::Comma || *t == token::CloseDelim(token::Paren) - }) { - let ident = self.parse_ident().unwrap(); - let span = pat.span.with_hi(ident.span.hi()); - - err.span_suggestion( - span, - "declare the type after the parameter binding", - String::from(": "), - Applicability::HasPlaceholders, - ); - } else if require_name && is_trait_item { - if let PatKind::Ident(_, ident, _) = pat.node { - err.span_suggestion( - pat.span, - "explicitly ignore parameter", - format!("_: {}", ident), - Applicability::MachineApplicable, - ); - } - - err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)"); - } - + self.argument_without_type(&mut err, pat, require_name, is_trait_item); return Err(err); } diff --git a/src/test/ui/invalid-self-argument/bare-fn-start.rs b/src/test/ui/invalid-self-argument/bare-fn-start.rs index 741ba5f41ce16..95a2b69c05cc6 100644 --- a/src/test/ui/invalid-self-argument/bare-fn-start.rs +++ b/src/test/ui/invalid-self-argument/bare-fn-start.rs @@ -1,5 +1,6 @@ fn a(&self) { } //~^ ERROR unexpected `self` argument in function +//~| NOTE not valid as function argument //~| NOTE `self` is only valid as the first argument of an associated function fn main() { } diff --git a/src/test/ui/invalid-self-argument/bare-fn-start.stderr b/src/test/ui/invalid-self-argument/bare-fn-start.stderr index 6a878b619d813..ba1092ca3770c 100644 --- a/src/test/ui/invalid-self-argument/bare-fn-start.stderr +++ b/src/test/ui/invalid-self-argument/bare-fn-start.stderr @@ -1,8 +1,10 @@ error: unexpected `self` argument in function - --> $DIR/bare-fn-start.rs:1:7 + --> $DIR/bare-fn-start.rs:1:6 | LL | fn a(&self) { } - | ^^^^ `self` is only valid as the first argument of an associated function + | ^^^^^ not valid as function argument + | + = note: `self` is only valid as the first argument of an associated function error: aborting due to previous error diff --git a/src/test/ui/invalid-self-argument/bare-fn.rs b/src/test/ui/invalid-self-argument/bare-fn.rs index 704fa996ca631..43c87fb79d88d 100644 --- a/src/test/ui/invalid-self-argument/bare-fn.rs +++ b/src/test/ui/invalid-self-argument/bare-fn.rs @@ -1,5 +1,6 @@ fn b(foo: u32, &mut self) { } //~^ ERROR unexpected `self` argument in function +//~| NOTE not valid as function argument //~| NOTE `self` is only valid as the first argument of an associated function fn main() { } diff --git a/src/test/ui/invalid-self-argument/bare-fn.stderr b/src/test/ui/invalid-self-argument/bare-fn.stderr index b13f746a4ec58..16a2d4b4b3737 100644 --- a/src/test/ui/invalid-self-argument/bare-fn.stderr +++ b/src/test/ui/invalid-self-argument/bare-fn.stderr @@ -1,8 +1,10 @@ error: unexpected `self` argument in function - --> $DIR/bare-fn.rs:1:21 + --> $DIR/bare-fn.rs:1:16 | LL | fn b(foo: u32, &mut self) { } - | ^^^^ `self` is only valid as the first argument of an associated function + | ^^^^^^^^^ not valid as function argument + | + = note: `self` is only valid as the first argument of an associated function error: aborting due to previous error diff --git a/src/test/ui/invalid-self-argument/trait-fn.rs b/src/test/ui/invalid-self-argument/trait-fn.rs index 31e867bc7641f..620a06db557b3 100644 --- a/src/test/ui/invalid-self-argument/trait-fn.rs +++ b/src/test/ui/invalid-self-argument/trait-fn.rs @@ -3,7 +3,7 @@ struct Foo {} impl Foo { fn c(foo: u32, self) {} //~^ ERROR unexpected `self` argument in function - //~| NOTE `self` is only valid as the first argument of an associated function + //~| NOTE must be the first associated function argument fn good(&mut self, foo: u32) {} } diff --git a/src/test/ui/invalid-self-argument/trait-fn.stderr b/src/test/ui/invalid-self-argument/trait-fn.stderr index b3c2cc5b5ebe0..00fedea3fead5 100644 --- a/src/test/ui/invalid-self-argument/trait-fn.stderr +++ b/src/test/ui/invalid-self-argument/trait-fn.stderr @@ -2,7 +2,7 @@ error: unexpected `self` argument in function --> $DIR/trait-fn.rs:4:20 | LL | fn c(foo: u32, self) {} - | ^^^^ `self` is only valid as the first argument of an associated function + | ^^^^ must be the first associated function argument error: aborting due to previous error diff --git a/src/test/ui/parser/self-in-function-arg.rs b/src/test/ui/parser/self-in-function-arg.rs new file mode 100644 index 0000000000000..502c2c0b74a59 --- /dev/null +++ b/src/test/ui/parser/self-in-function-arg.rs @@ -0,0 +1,3 @@ +fn foo(x:i32, self: i32) -> i32 { self } //~ ERROR unexpected `self` argument in function + +fn main() {} diff --git a/src/test/ui/parser/self-in-function-arg.stderr b/src/test/ui/parser/self-in-function-arg.stderr new file mode 100644 index 0000000000000..e1fc10306cc08 --- /dev/null +++ b/src/test/ui/parser/self-in-function-arg.stderr @@ -0,0 +1,10 @@ +error: unexpected `self` argument in function + --> $DIR/self-in-function-arg.rs:1:15 + | +LL | fn foo(x:i32, self: i32) -> i32 { self } + | ^^^^ not valid as function argument + | + = note: `self` is only valid as the first argument of an associated function + +error: aborting due to previous error + From d1364d5284e715944860d13ea6a55839c7eb052d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 23 May 2019 12:55:26 -0700 Subject: [PATCH 10/12] Move some methods to `diagnostics.rs` away from `parser.rs` Move a bunch of error recovery methods to `diagnostics.rs` away from `parser.rs`. --- src/libsyntax/parse/diagnostics.rs | 436 +++++++++++++++++++++++++++- src/libsyntax/parse/parser.rs | 439 +++-------------------------- 2 files changed, 462 insertions(+), 413 deletions(-) diff --git a/src/libsyntax/parse/diagnostics.rs b/src/libsyntax/parse/diagnostics.rs index 11f8eba033e9e..7df9b80c3c521 100644 --- a/src/libsyntax/parse/diagnostics.rs +++ b/src/libsyntax/parse/diagnostics.rs @@ -1,19 +1,104 @@ use crate::ast; use crate::ast::{ - BlockCheckMode, Expr, ExprKind, Item, ItemKind, Pat, PatKind, QSelf, Ty, TyKind, VariantData, + BlockCheckMode, BinOpKind, Expr, ExprKind, Item, ItemKind, Pat, PatKind, PathSegment, QSelf, + Ty, TyKind, VariantData, }; -use crate::parse::parser::{BlockMode, PathStyle, SemiColonMode, TokenType}; +use crate::parse::{SeqSep, token, PResult, Parser}; +use crate::parse::parser::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType}; use crate::parse::token; -use crate::parse::PResult; -use crate::parse::Parser; use crate::print::pprust; use crate::ptr::P; use crate::source_map::Spanned; use crate::symbol::kw; use crate::ThinVec; -use errors::{Applicability, DiagnosticBuilder}; -use log::debug; -use syntax_pos::{Span, DUMMY_SP}; +use crate::tokenstream::TokenTree; +use crate::util::parser::AssocOp; +use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; +use syntax_pos::{Span, DUMMY_SP, MultiSpan}; +use log::{debug, trace}; +use std::slice; + +pub enum Error { + FileNotFoundForModule { + mod_name: String, + default_path: String, + secondary_path: String, + dir_path: String, + }, + DuplicatePaths { + mod_name: String, + default_path: String, + secondary_path: String, + }, + UselessDocComment, + InclusiveRangeWithNoEnd, +} + +impl Error { + fn span_err>( + self, + sp: S, + handler: &errors::Handler, + ) -> DiagnosticBuilder<'_> { + match self { + Error::FileNotFoundForModule { + ref mod_name, + ref default_path, + ref secondary_path, + ref dir_path, + } => { + let mut err = struct_span_err!( + handler, + sp, + E0583, + "file not found for module `{}`", + mod_name, + ); + err.help(&format!( + "name the file either {} or {} inside the directory \"{}\"", + default_path, + secondary_path, + dir_path, + )); + err + } + Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => { + let mut err = struct_span_err!( + handler, + sp, + E0584, + "file for module `{}` found at both {} and {}", + mod_name, + default_path, + secondary_path, + ); + err.help("delete or rename one of them to remove the ambiguity"); + err + } + Error::UselessDocComment => { + let mut err = struct_span_err!( + handler, + sp, + E0585, + "found a documentation comment that doesn't document anything", + ); + err.help("doc comments must come before what they document, maybe a comment was \ + intended with `//`?"); + err + } + Error::InclusiveRangeWithNoEnd => { + let mut err = struct_span_err!( + handler, + sp, + E0586, + "inclusive range with no end", + ); + err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)"); + err + } + } + } +} pub trait RecoverQPath: Sized + 'static { const PATH_STYLE: PathStyle = PathStyle::Expr; @@ -63,6 +148,253 @@ impl RecoverQPath for Expr { } impl<'a> Parser<'a> { + pub fn look_ahead(&self, dist: usize, f: F) -> R where + F: FnOnce(&token::Token) -> R, + { + if dist == 0 { + return f(&self.token) + } + + f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(tree) => match tree { + TokenTree::Token(_, tok) => tok, + TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim), + }, + None => token::CloseDelim(self.token_cursor.frame.delim), + }) + } + + crate fn look_ahead_span(&self, dist: usize) -> Span { + if dist == 0 { + return self.span + } + + match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(TokenTree::Token(span, _)) => span, + Some(TokenTree::Delimited(span, ..)) => span.entire(), + None => self.look_ahead_span(dist - 1), + } + } + + pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(self.span, m) + } + + pub fn span_fatal>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_fatal(sp, m) + } + + pub fn span_fatal_err>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> { + err.span_err(sp, self.diagnostic()) + } + + pub fn bug(&self, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(self.span, m) + } + + pub fn span_err>(&self, sp: S, m: &str) { + self.sess.span_diagnostic.span_err(sp, m) + } + + crate fn struct_span_err>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { + self.sess.span_diagnostic.struct_span_err(sp, m) + } + + crate fn span_bug>(&self, sp: S, m: &str) -> ! { + self.sess.span_diagnostic.span_bug(sp, m) + } + + crate fn cancel(&self, err: &mut DiagnosticBuilder<'_>) { + self.sess.span_diagnostic.cancel(err) + } + + crate fn diagnostic(&self) -> &'a errors::Handler { + &self.sess.span_diagnostic + } + + crate fn expected_ident_found(&self) -> DiagnosticBuilder<'a> { + let mut err = self.struct_span_err( + self.span, + &format!("expected identifier, found {}", self.this_token_descr()), + ); + if let token::Ident(ident, false) = &self.token { + if ident.is_raw_guess() { + err.span_suggestion( + self.span, + "you can escape reserved keywords to use them as identifiers", + format!("r#{}", ident), + Applicability::MaybeIncorrect, + ); + } + } + if let Some(token_descr) = self.token_descr() { + err.span_label(self.span, format!("expected identifier, found {}", token_descr)); + } else { + err.span_label(self.span, "expected identifier"); + if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) { + err.span_suggestion( + self.span, + "remove this comma", + String::new(), + Applicability::MachineApplicable, + ); + } + } + err + } + + /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, + /// passes through any errors encountered. Used for error recovery. + crate fn eat_to_tokens(&mut self, kets: &[&token::Token]) { + let handler = self.diagnostic(); + + if let Err(ref mut err) = self.parse_seq_to_before_tokens( + kets, + SeqSep::none(), + TokenExpectType::Expect, + |p| Ok(p.parse_token_tree()), + ) { + handler.cancel(err); + } + } + + /// This function checks if there are trailing angle brackets and produces + /// a diagnostic to suggest removing them. + /// + /// ```ignore (diagnostic) + /// let _ = vec![1, 2, 3].into_iter().collect::>>>(); + /// ^^ help: remove extra angle brackets + /// ``` + crate fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) { + // This function is intended to be invoked after parsing a path segment where there are two + // cases: + // + // 1. A specific token is expected after the path segment. + // eg. `x.foo(`, `x.foo::(` (parenthesis - method call), + // `Foo::`, or `Foo::::` (mod sep - continued path). + // 2. No specific token is expected after the path segment. + // eg. `x.foo` (field access) + // + // This function is called after parsing `.foo` and before parsing the token `end` (if + // present). This includes any angle bracket arguments, such as `.foo::` or + // `Foo::`. + + // We only care about trailing angle brackets if we previously parsed angle bracket + // arguments. This helps stop us incorrectly suggesting that extra angle brackets be + // removed in this case: + // + // `x.foo >> (3)` (where `x.foo` is a `u32` for example) + // + // This case is particularly tricky as we won't notice it just looking at the tokens - + // it will appear the same (in terms of upcoming tokens) as below (since the `::` will + // have already been parsed): + // + // `x.foo::>>(3)` + let parsed_angle_bracket_args = segment.args + .as_ref() + .map(|args| args.is_angle_bracketed()) + .unwrap_or(false); + + debug!( + "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", + parsed_angle_bracket_args, + ); + if !parsed_angle_bracket_args { + return; + } + + // Keep the span at the start so we can highlight the sequence of `>` characters to be + // removed. + let lo = self.span; + + // We need to look-ahead to see if we have `>` characters without moving the cursor forward + // (since we might have the field access case and the characters we're eating are + // actual operators and not trailing characters - ie `x.foo >> 3`). + let mut position = 0; + + // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how + // many of each (so we can correctly pluralize our error messages) and continue to + // advance. + let mut number_of_shr = 0; + let mut number_of_gt = 0; + while self.look_ahead(position, |t| { + trace!("check_trailing_angle_brackets: t={:?}", t); + if *t == token::BinOp(token::BinOpToken::Shr) { + number_of_shr += 1; + true + } else if *t == token::Gt { + number_of_gt += 1; + true + } else { + false + } + }) { + position += 1; + } + + // If we didn't find any trailing `>` characters, then we have nothing to error about. + debug!( + "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}", + number_of_gt, number_of_shr, + ); + if number_of_gt < 1 && number_of_shr < 1 { + return; + } + + // Finally, double check that we have our end token as otherwise this is the + // second case. + if self.look_ahead(position, |t| { + trace!("check_trailing_angle_brackets: t={:?}", t); + *t == end + }) { + // Eat from where we started until the end token so that parsing can continue + // as if we didn't have those extra angle brackets. + self.eat_to_tokens(&[&end]); + let span = lo.until(self.span); + + let plural = number_of_gt > 1 || number_of_shr >= 1; + self.diagnostic() + .struct_span_err( + span, + &format!("unmatched angle bracket{}", if plural { "s" } else { "" }), + ) + .span_suggestion( + span, + &format!("remove extra angle bracket{}", if plural { "s" } else { "" }), + String::new(), + Applicability::MachineApplicable, + ) + .emit(); + } + } + + /// Produce an error if comparison operators are chained (RFC #558). + /// We only need to check lhs, not rhs, because all comparison ops + /// have same precedence and are left-associative + crate fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) { + debug_assert!(outer_op.is_comparison(), + "check_no_chained_comparison: {:?} is not comparison", + outer_op); + match lhs.node { + ExprKind::Binary(op, _, _) if op.node.is_comparison() => { + // respan to include both operators + let op_span = op.span.to(self.span); + let mut err = self.diagnostic().struct_span_err(op_span, + "chained comparison operators require parentheses"); + if op.node == BinOpKind::Lt && + *outer_op == AssocOp::Less || // Include `<` to provide this recommendation + *outer_op == AssocOp::Greater // even in a case like the following: + { // Foo>> + err.help( + "use `::<...>` instead of `<...>` if you meant to specify type arguments"); + err.help("or use `(...)` if you meant to specify fn arguments"); + } + err.emit(); + } + _ => {} + } + } + crate fn maybe_report_ambiguous_plus( &mut self, allow_plus: bool, @@ -594,6 +926,96 @@ impl<'a> Parser<'a> { } } + crate fn check_for_for_in_in_typo(&mut self, in_span: Span) { + if self.eat_keyword(kw::In) { + // a common typo: `for _ in in bar {}` + let mut err = self.sess.span_diagnostic.struct_span_err( + self.prev_span, + "expected iterable, found keyword `in`", + ); + err.span_suggestion_short( + in_span.until(self.prev_span), + "remove the duplicated `in`", + String::new(), + Applicability::MachineApplicable, + ); + err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)"); + err.note("for more information on the status of emplacement syntax, see <\ + https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"); + err.emit(); + } + } + + crate fn expected_semi_or_open_brace(&mut self) -> PResult<'a, ast::TraitItem> { + let token_str = self.this_token_descr(); + let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", token_str)); + err.span_label(self.span, "expected `;` or `{`"); + Err(err) + } + + crate fn eat_incorrect_doc_comment(&mut self, applied_to: &str) { + if let token::DocComment(_) = self.token { + let mut err = self.diagnostic().struct_span_err( + self.span, + &format!("documentation comments cannot be applied to {}", applied_to), + ); + err.span_label(self.span, "doc comments are not allowed here"); + err.emit(); + self.bump(); + } else if self.token == token::Pound && self.look_ahead(1, |t| { + *t == token::OpenDelim(token::Bracket) + }) { + let lo = self.span; + // Skip every token until next possible arg. + while self.token != token::CloseDelim(token::Bracket) { + self.bump(); + } + let sp = lo.to(self.span); + self.bump(); + let mut err = self.diagnostic().struct_span_err( + sp, + &format!("attributes cannot be applied to {}", applied_to), + ); + err.span_label(sp, "attributes are not allowed here"); + err.emit(); + } + } + + crate fn argument_without_type( + &mut self, + err: &mut DiagnosticBuilder<'_>, + pat: P, + require_name: bool, + is_trait_item: bool, + ) { + // If we find a pattern followed by an identifier, it could be an (incorrect) + // C-style parameter declaration. + if self.check_ident() && self.look_ahead(1, |t| { + *t == token::Comma || *t == token::CloseDelim(token::Paren) + }) { + let ident = self.parse_ident().unwrap(); + let span = pat.span.with_hi(ident.span.hi()); + + err.span_suggestion( + span, + "declare the type after the parameter binding", + String::from(": "), + Applicability::HasPlaceholders, + ); + } else if require_name && is_trait_item { + if let PatKind::Ident(_, ident, _) = pat.node { + err.span_suggestion( + pat.span, + "explicitly ignore parameter", + format!("_: {}", ident), + Applicability::MachineApplicable, + ); + } + + err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)"); + } + } + crate fn recover_arg_parse(&mut self) -> PResult<'a, (P, P)> { let pat = self.parse_pat(Some("argument name"))?; self.expect(&token::Colon)?; diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index b4b45fd9eff2b..6d866d7f3d43f 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -47,20 +47,17 @@ use crate::parse::PResult; use crate::ThinVec; use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; use crate::symbol::{kw, sym, Symbol}; +use crate::parse::diagnostics::Error; -use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; +use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; use rustc_target::spec::abi::{self, Abi}; -use syntax_pos::{ - BytePos, DUMMY_SP, FileName, MultiSpan, Span, - hygiene::CompilerDesugaringKind, -}; -use log::{debug, trace}; +use syntax_pos::{Span, BytePos, DUMMY_SP, FileName, hygiene::CompilerDesugaringKind}; +use log::debug; use std::borrow::Cow; use std::cmp; use std::mem; use std::path::{self, Path, PathBuf}; -use std::slice; #[derive(Debug)] /// Whether the type alias or associated type is a concrete type or an existential type @@ -217,7 +214,7 @@ pub struct Parser<'a> { /// into modules, and sub-parsers have new values for this name. pub root_module_name: Option, crate expected_tokens: Vec, - token_cursor: TokenCursor, + crate token_cursor: TokenCursor, desugar_doc_comments: bool, /// Whether we should configure out of line modules as we parse. pub cfg_mods: bool, @@ -232,7 +229,7 @@ pub struct Parser<'a> { /// it gets removed from here. Every entry left at the end gets emitted as an independent /// error. crate unclosed_delims: Vec, - last_unexpected_token_span: Option, + crate last_unexpected_token_span: Option, /// If present, this `Parser` is not parsing Rust code but rather a macro call. crate subparser_name: Option<&'static str>, } @@ -245,19 +242,19 @@ impl<'a> Drop for Parser<'a> { } #[derive(Clone)] -struct TokenCursor { - frame: TokenCursorFrame, - stack: Vec, +crate struct TokenCursor { + crate frame: TokenCursorFrame, + crate stack: Vec, } #[derive(Clone)] -struct TokenCursorFrame { - delim: token::DelimToken, - span: DelimSpan, - open_delim: bool, - tree_cursor: tokenstream::Cursor, - close_delim: bool, - last_token: LastToken, +crate struct TokenCursorFrame { + crate delim: token::DelimToken, + crate span: DelimSpan, + crate open_delim: bool, + crate tree_cursor: tokenstream::Cursor, + crate close_delim: bool, + crate last_token: LastToken, } /// This is used in `TokenCursorFrame` above to track tokens that are consumed @@ -278,7 +275,7 @@ struct TokenCursorFrame { /// You can find some more example usage of this in the `collect_tokens` method /// on the parser. #[derive(Clone)] -enum LastToken { +crate enum LastToken { Collecting(Vec), Was(Option), } @@ -430,65 +427,6 @@ pub struct ModulePathSuccess { warn: bool, } -pub enum Error { - FileNotFoundForModule { - mod_name: String, - default_path: String, - secondary_path: String, - dir_path: String, - }, - DuplicatePaths { - mod_name: String, - default_path: String, - secondary_path: String, - }, - UselessDocComment, - InclusiveRangeWithNoEnd, -} - -impl Error { - fn span_err>(self, - sp: S, - handler: &errors::Handler) -> DiagnosticBuilder<'_> { - match self { - Error::FileNotFoundForModule { ref mod_name, - ref default_path, - ref secondary_path, - ref dir_path } => { - let mut err = struct_span_err!(handler, sp, E0583, - "file not found for module `{}`", mod_name); - err.help(&format!("name the file either {} or {} inside the directory \"{}\"", - default_path, - secondary_path, - dir_path)); - err - } - Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => { - let mut err = struct_span_err!(handler, sp, E0584, - "file for module `{}` found at both {} and {}", - mod_name, - default_path, - secondary_path); - err.help("delete or rename one of them to remove the ambiguity"); - err - } - Error::UselessDocComment => { - let mut err = struct_span_err!(handler, sp, E0585, - "found a documentation comment that doesn't document anything"); - err.help("doc comments must come before what they document, maybe a comment was \ - intended with `//`?"); - err - } - Error::InclusiveRangeWithNoEnd => { - let mut err = struct_span_err!(handler, sp, E0586, - "inclusive range with no end"); - err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)"); - err - } - } - } -} - #[derive(Debug)] enum LhsExpr { NotYetParsed, @@ -529,7 +467,7 @@ fn dummy_arg(span: Span) -> Arg { } #[derive(Copy, Clone, Debug)] -enum TokenExpectType { +crate enum TokenExpectType { Expect, NoExpect, } @@ -610,7 +548,7 @@ impl<'a> Parser<'a> { pprust::token_to_string(&self.token) } - fn token_descr(&self) -> Option<&'static str> { + crate fn token_descr(&self) -> Option<&'static str> { Some(match &self.token { t if t.is_special_ident() => "reserved identifier", t if t.is_used_keyword() => "keyword", @@ -801,9 +739,10 @@ impl<'a> Parser<'a> { } /// Returns the span of expr, if it was not interpolated or the span of the interpolated token. - fn interpolated_or_expr_span(&self, - expr: PResult<'a, P>) - -> PResult<'a, (Span, P)> { + fn interpolated_or_expr_span( + &self, + expr: PResult<'a, P>, + ) -> PResult<'a, (Span, P)> { expr.map(|e| { if self.prev_token_kind == PrevTokenKind::Interpolated { (self.prev_span, e) @@ -813,36 +752,6 @@ impl<'a> Parser<'a> { }) } - fn expected_ident_found(&self) -> DiagnosticBuilder<'a> { - let mut err = self.struct_span_err(self.span, - &format!("expected identifier, found {}", - self.this_token_descr())); - if let token::Ident(ident, false) = &self.token { - if ident.is_raw_guess() { - err.span_suggestion( - self.span, - "you can escape reserved keywords to use them as identifiers", - format!("r#{}", ident), - Applicability::MaybeIncorrect, - ); - } - } - if let Some(token_descr) = self.token_descr() { - err.span_label(self.span, format!("expected identifier, found {}", token_descr)); - } else { - err.span_label(self.span, "expected identifier"); - if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) { - err.span_suggestion( - self.span, - "remove this comma", - String::new(), - Applicability::MachineApplicable, - ); - } - } - err - } - pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> { self.parse_ident_common(true) } @@ -925,7 +834,7 @@ impl<'a> Parser<'a> { } } - fn check_ident(&mut self) -> bool { + crate fn check_ident(&mut self) -> bool { if self.token.is_ident() { true } else { @@ -1115,19 +1024,6 @@ impl<'a> Parser<'a> { } } - /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, - /// passes through any errors encountered. Used for error recovery. - fn eat_to_tokens(&mut self, kets: &[&token::Token]) { - let handler = self.diagnostic(); - - if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets, - SeqSep::none(), - TokenExpectType::Expect, - |p| Ok(p.parse_token_tree())) { - handler.cancel(err); - } - } - /// Parses a sequence, including the closing delimiter. The function /// `f` must consume tokens until reaching the next separator or /// closing bracket. @@ -1159,7 +1055,7 @@ impl<'a> Parser<'a> { self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f) } - fn parse_seq_to_before_tokens( + crate fn parse_seq_to_before_tokens( &mut self, kets: &[&token::Token], sep: SeqSep, @@ -1292,63 +1188,6 @@ impl<'a> Parser<'a> { self.expected_tokens.clear(); } - pub fn look_ahead(&self, dist: usize, f: F) -> R where - F: FnOnce(&token::Token) -> R, - { - if dist == 0 { - return f(&self.token) - } - - f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { - Some(tree) => match tree { - TokenTree::Token(_, tok) => tok, - TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim), - }, - None => token::CloseDelim(self.token_cursor.frame.delim), - }) - } - - crate fn look_ahead_span(&self, dist: usize) -> Span { - if dist == 0 { - return self.span - } - - match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { - Some(TokenTree::Token(span, _)) => span, - Some(TokenTree::Delimited(span, ..)) => span.entire(), - None => self.look_ahead_span(dist - 1), - } - } - pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_fatal(self.span, m) - } - pub fn span_fatal>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_fatal(sp, m) - } - fn span_fatal_err>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> { - err.span_err(sp, self.diagnostic()) - } - fn bug(&self, m: &str) -> ! { - self.sess.span_diagnostic.span_bug(self.span, m) - } - fn span_err>(&self, sp: S, m: &str) { - self.sess.span_diagnostic.span_err(sp, m) - } - crate fn struct_span_err>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_err(sp, m) - } - crate fn span_bug>(&self, sp: S, m: &str) -> ! { - self.sess.span_diagnostic.span_bug(sp, m) - } - - fn cancel(&self, err: &mut DiagnosticBuilder<'_>) { - self.sess.span_diagnostic.cancel(err) - } - - crate fn diagnostic(&self) -> &'a errors::Handler { - &self.sess.span_diagnostic - } - /// Is the current token one of the keywords that signals a bare function type? fn token_is_bare_fn_keyword(&mut self) -> bool { self.check_keyword(kw::Fn) || @@ -1507,20 +1346,12 @@ impl<'a> Parser<'a> { Some(body) } _ => { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", - token_str)); - err.span_label(self.span, "expected `;` or `{`"); - return Err(err); + return self.expected_semi_or_open_brace(); } } } _ => { - let token_str = self.this_token_descr(); - let mut err = self.fatal(&format!("expected `;` or `{{`, found {}", - token_str)); - err.span_label(self.span, "expected `;` or `{`"); - return Err(err); + return self.expected_semi_or_open_brace(); } }; (ident, ast::TraitItemKind::Method(sig, body), generics) @@ -1776,34 +1607,6 @@ impl<'a> Parser<'a> { /// Skips unexpected attributes and doc comments in this position and emits an appropriate /// error. - fn eat_incorrect_doc_comment(&mut self, applied_to: &str) { - if let token::DocComment(_) = self.token { - let mut err = self.diagnostic().struct_span_err( - self.span, - &format!("documentation comments cannot be applied to {}", applied_to), - ); - err.span_label(self.span, "doc comments are not allowed here"); - err.emit(); - self.bump(); - } else if self.token == token::Pound && self.look_ahead(1, |t| { - *t == token::OpenDelim(token::Bracket) - }) { - let lo = self.span; - // Skip every token until next possible arg. - while self.token != token::CloseDelim(token::Bracket) { - self.bump(); - } - let sp = lo.to(self.span); - self.bump(); - let mut err = self.diagnostic().struct_span_err( - sp, - &format!("attributes cannot be applied to {}", applied_to), - ); - err.span_label(sp, "attributes are not allowed here"); - err.emit(); - } - } - /// This version of parse arg doesn't necessarily require identifier names. fn parse_arg_general( &mut self, @@ -1858,30 +1661,7 @@ impl<'a> Parser<'a> { // Recover from attempting to parse the argument as a type without pattern. err.cancel(); mem::replace(self, parser_snapshot_before_ty); - let pat = self.parse_pat(Some("argument name"))?; - self.expect(&token::Colon)?; - let ty = self.parse_ty()?; - - let mut err = self.diagnostic().struct_span_err_with_code( - pat.span, - "patterns aren't allowed in methods without bodies", - DiagnosticId::Error("E0642".into()), - ); - err.span_suggestion_short( - pat.span, - "give this argument a name or use an underscore to ignore it", - "_".to_owned(), - Applicability::MachineApplicable, - ); - err.emit(); - - // Pretend the pattern is `_`, to avoid duplicate errors from AST validation. - let pat = P(Pat { - node: PatKind::Wild, - span: pat.span, - id: ast::DUMMY_NODE_ID - }); - (pat, ty) + self.recover_arg_parse()? } } }; @@ -1889,11 +1669,6 @@ impl<'a> Parser<'a> { Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }) } - /// Parses a single function argument. - crate fn parse_arg(&mut self) -> PResult<'a, Arg> { - self.parse_arg_general(true, false, false) - } - /// Parses an argument in a lambda header (e.g., `|arg, arg|`). fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> { let pat = self.parse_pat(Some("argument name"))?; @@ -2858,116 +2633,6 @@ impl<'a> Parser<'a> { }) } - /// This function checks if there are trailing angle brackets and produces - /// a diagnostic to suggest removing them. - /// - /// ```ignore (diagnostic) - /// let _ = vec![1, 2, 3].into_iter().collect::>>>(); - /// ^^ help: remove extra angle brackets - /// ``` - fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) { - // This function is intended to be invoked after parsing a path segment where there are two - // cases: - // - // 1. A specific token is expected after the path segment. - // eg. `x.foo(`, `x.foo::(` (parenthesis - method call), - // `Foo::`, or `Foo::::` (mod sep - continued path). - // 2. No specific token is expected after the path segment. - // eg. `x.foo` (field access) - // - // This function is called after parsing `.foo` and before parsing the token `end` (if - // present). This includes any angle bracket arguments, such as `.foo::` or - // `Foo::`. - - // We only care about trailing angle brackets if we previously parsed angle bracket - // arguments. This helps stop us incorrectly suggesting that extra angle brackets be - // removed in this case: - // - // `x.foo >> (3)` (where `x.foo` is a `u32` for example) - // - // This case is particularly tricky as we won't notice it just looking at the tokens - - // it will appear the same (in terms of upcoming tokens) as below (since the `::` will - // have already been parsed): - // - // `x.foo::>>(3)` - let parsed_angle_bracket_args = segment.args - .as_ref() - .map(|args| args.is_angle_bracketed()) - .unwrap_or(false); - - debug!( - "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}", - parsed_angle_bracket_args, - ); - if !parsed_angle_bracket_args { - return; - } - - // Keep the span at the start so we can highlight the sequence of `>` characters to be - // removed. - let lo = self.span; - - // We need to look-ahead to see if we have `>` characters without moving the cursor forward - // (since we might have the field access case and the characters we're eating are - // actual operators and not trailing characters - ie `x.foo >> 3`). - let mut position = 0; - - // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how - // many of each (so we can correctly pluralize our error messages) and continue to - // advance. - let mut number_of_shr = 0; - let mut number_of_gt = 0; - while self.look_ahead(position, |t| { - trace!("check_trailing_angle_brackets: t={:?}", t); - if *t == token::BinOp(token::BinOpToken::Shr) { - number_of_shr += 1; - true - } else if *t == token::Gt { - number_of_gt += 1; - true - } else { - false - } - }) { - position += 1; - } - - // If we didn't find any trailing `>` characters, then we have nothing to error about. - debug!( - "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}", - number_of_gt, number_of_shr, - ); - if number_of_gt < 1 && number_of_shr < 1 { - return; - } - - // Finally, double check that we have our end token as otherwise this is the - // second case. - if self.look_ahead(position, |t| { - trace!("check_trailing_angle_brackets: t={:?}", t); - *t == end - }) { - // Eat from where we started until the end token so that parsing can continue - // as if we didn't have those extra angle brackets. - self.eat_to_tokens(&[&end]); - let span = lo.until(self.span); - - let plural = number_of_gt > 1 || number_of_shr >= 1; - self.diagnostic() - .struct_span_err( - span, - &format!("unmatched angle bracket{}", if plural { "s" } else { "" }), - ) - .span_suggestion( - span, - &format!("remove extra angle bracket{}", if plural { "s" } else { "" }), - String::new(), - Applicability::MachineApplicable, - ) - .emit(); - } - } - fn parse_dot_or_call_expr_with_(&mut self, e0: P, lo: Span) -> PResult<'a, P> { let mut e = e0; let mut hi; @@ -3529,33 +3194,6 @@ impl<'a> Parser<'a> { } } - /// Produce an error if comparison operators are chained (RFC #558). - /// We only need to check lhs, not rhs, because all comparison ops - /// have same precedence and are left-associative - fn check_no_chained_comparison(&self, lhs: &Expr, outer_op: &AssocOp) { - debug_assert!(outer_op.is_comparison(), - "check_no_chained_comparison: {:?} is not comparison", - outer_op); - match lhs.node { - ExprKind::Binary(op, _, _) if op.node.is_comparison() => { - // respan to include both operators - let op_span = op.span.to(self.span); - let mut err = self.diagnostic().struct_span_err(op_span, - "chained comparison operators require parentheses"); - if op.node == BinOpKind::Lt && - *outer_op == AssocOp::Less || // Include `<` to provide this recommendation - *outer_op == AssocOp::Greater // even in a case like the following: - { // Foo>> - err.help( - "use `::<...>` instead of `<...>` if you meant to specify type arguments"); - err.help("or use `(...)` if you meant to specify fn arguments"); - } - err.emit(); - } - _ => {} - } - } - /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr` fn parse_prefix_range_expr(&mut self, already_parsed_attrs: Option>) @@ -3582,7 +3220,7 @@ impl<'a> Parser<'a> { hi = x.span; x })?) - } else { + } else { None }; let limits = if tok == token::DotDot { @@ -3732,20 +3370,7 @@ impl<'a> Parser<'a> { err.emit(); } let in_span = self.prev_span; - if self.eat_keyword(kw::In) { - // a common typo: `for _ in in bar {}` - let mut err = self.sess.span_diagnostic.struct_span_err( - self.prev_span, - "expected iterable, found keyword `in`", - ); - err.span_suggestion_short( - in_span.until(self.prev_span), - "remove the duplicated `in`", - String::new(), - Applicability::MachineApplicable, - ); - err.emit(); - } + self.check_for_for_in_in_typo(in_span); let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?; let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?; attrs.extend(iattrs); @@ -6327,7 +5952,9 @@ impl<'a> Parser<'a> { let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?; let ident = self.parse_ident()?; let mut generics = self.parse_generics()?; - let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?; + let mut decl = self.parse_fn_decl_with_self(|p| { + p.parse_arg_general(true, true, false) + })?; generics.where_clause = self.parse_where_clause()?; self.construct_async_arguments(&mut asyncness, &mut decl); *at_end = true; From 4e68ddca90a8f3ee580445b1fc83a6a6d0c7f94f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Esteban=20K=C3=BCber?= Date: Thu, 23 May 2019 13:10:24 -0700 Subject: [PATCH 11/12] review comments: move back some methods and clean up wording --- src/libsyntax/parse/diagnostics.rs | 185 ++++++++++++++---- src/libsyntax/parse/parser.rs | 163 +++------------ .../ui/invalid-self-argument/bare-fn-start.rs | 6 +- .../bare-fn-start.stderr | 6 +- src/test/ui/invalid-self-argument/bare-fn.rs | 6 +- .../ui/invalid-self-argument/bare-fn.stderr | 6 +- src/test/ui/invalid-self-argument/trait-fn.rs | 4 +- .../ui/invalid-self-argument/trait-fn.stderr | 4 +- src/test/ui/parser/self-in-function-arg.rs | 2 +- .../ui/parser/self-in-function-arg.stderr | 6 +- 10 files changed, 196 insertions(+), 192 deletions(-) diff --git a/src/libsyntax/parse/diagnostics.rs b/src/libsyntax/parse/diagnostics.rs index 7df9b80c3c521..9431b559da55f 100644 --- a/src/libsyntax/parse/diagnostics.rs +++ b/src/libsyntax/parse/diagnostics.rs @@ -5,18 +5,15 @@ use crate::ast::{ }; use crate::parse::{SeqSep, token, PResult, Parser}; use crate::parse::parser::{BlockMode, PathStyle, SemiColonMode, TokenType, TokenExpectType}; -use crate::parse::token; use crate::print::pprust; use crate::ptr::P; use crate::source_map::Spanned; use crate::symbol::kw; use crate::ThinVec; -use crate::tokenstream::TokenTree; use crate::util::parser::AssocOp; -use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; +use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; use syntax_pos::{Span, DUMMY_SP, MultiSpan}; use log::{debug, trace}; -use std::slice; pub enum Error { FileNotFoundForModule { @@ -148,36 +145,8 @@ impl RecoverQPath for Expr { } impl<'a> Parser<'a> { - pub fn look_ahead(&self, dist: usize, f: F) -> R where - F: FnOnce(&token::Token) -> R, - { - if dist == 0 { - return f(&self.token) - } - - f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { - Some(tree) => match tree { - TokenTree::Token(_, tok) => tok, - TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim), - }, - None => token::CloseDelim(self.token_cursor.frame.delim), - }) - } - - crate fn look_ahead_span(&self, dist: usize) -> Span { - if dist == 0 { - return self.span - } - - match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { - Some(TokenTree::Token(span, _)) => span, - Some(TokenTree::Delimited(span, ..)) => span.entire(), - None => self.look_ahead_span(dist - 1), - } - } - pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> { - self.sess.span_diagnostic.struct_span_fatal(self.span, m) + self.span_fatal(self.span, m) } pub fn span_fatal>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> { @@ -243,6 +212,145 @@ impl<'a> Parser<'a> { err } + pub fn expected_one_of_not_found( + &mut self, + edible: &[token::Token], + inedible: &[token::Token], + ) -> PResult<'a, bool /* recovered */> { + fn tokens_to_string(tokens: &[TokenType]) -> String { + let mut i = tokens.iter(); + // This might be a sign we need a connect method on Iterator. + let b = i.next() + .map_or(String::new(), |t| t.to_string()); + i.enumerate().fold(b, |mut b, (i, a)| { + if tokens.len() > 2 && i == tokens.len() - 2 { + b.push_str(", or "); + } else if tokens.len() == 2 && i == tokens.len() - 2 { + b.push_str(" or "); + } else { + b.push_str(", "); + } + b.push_str(&a.to_string()); + b + }) + } + + let mut expected = edible.iter() + .map(|x| TokenType::Token(x.clone())) + .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) + .chain(self.expected_tokens.iter().cloned()) + .collect::>(); + expected.sort_by_cached_key(|x| x.to_string()); + expected.dedup(); + let expect = tokens_to_string(&expected[..]); + let actual = self.this_token_to_string(); + let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 { + let short_expect = if expected.len() > 6 { + format!("{} possible tokens", expected.len()) + } else { + expect.clone() + }; + (format!("expected one of {}, found `{}`", expect, actual), + (self.sess.source_map().next_point(self.prev_span), + format!("expected one of {} here", short_expect))) + } else if expected.is_empty() { + (format!("unexpected token: `{}`", actual), + (self.prev_span, "unexpected token after this".to_string())) + } else { + (format!("expected {}, found `{}`", expect, actual), + (self.sess.source_map().next_point(self.prev_span), + format!("expected {} here", expect))) + }; + self.last_unexpected_token_span = Some(self.span); + let mut err = self.fatal(&msg_exp); + if self.token.is_ident_named("and") { + err.span_suggestion_short( + self.span, + "use `&&` instead of `and` for the boolean operator", + "&&".to_string(), + Applicability::MaybeIncorrect, + ); + } + if self.token.is_ident_named("or") { + err.span_suggestion_short( + self.span, + "use `||` instead of `or` for the boolean operator", + "||".to_string(), + Applicability::MaybeIncorrect, + ); + } + let sp = if self.token == token::Token::Eof { + // This is EOF, don't want to point at the following char, but rather the last token + self.prev_span + } else { + label_sp + }; + match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { + TokenType::Token(t) => Some(t.clone()), + _ => None, + }).collect::>(), err) { + Err(e) => err = e, + Ok(recovered) => { + return Ok(recovered); + } + } + + let is_semi_suggestable = expected.iter().any(|t| match t { + TokenType::Token(token::Semi) => true, // we expect a `;` here + _ => false, + }) && ( // a `;` would be expected before the current keyword + self.token.is_keyword(kw::Break) || + self.token.is_keyword(kw::Continue) || + self.token.is_keyword(kw::For) || + self.token.is_keyword(kw::If) || + self.token.is_keyword(kw::Let) || + self.token.is_keyword(kw::Loop) || + self.token.is_keyword(kw::Match) || + self.token.is_keyword(kw::Return) || + self.token.is_keyword(kw::While) + ); + let cm = self.sess.source_map(); + match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { + (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => { + // The spans are in different lines, expected `;` and found `let` or `return`. + // High likelihood that it is only a missing `;`. + err.span_suggestion_short( + label_sp, + "a semicolon may be missing here", + ";".to_string(), + Applicability::MaybeIncorrect, + ); + err.emit(); + return Ok(true); + } + (Ok(ref a), Ok(ref b)) if a.line == b.line => { + // When the spans are in the same line, it means that the only content between + // them is whitespace, point at the found token in that case: + // + // X | () => { syntax error }; + // | ^^^^^ expected one of 8 possible tokens here + // + // instead of having: + // + // X | () => { syntax error }; + // | -^^^^^ unexpected token + // | | + // | expected one of 8 possible tokens here + err.span_label(self.span, label_exp); + } + _ if self.prev_span == syntax_pos::DUMMY_SP => { + // Account for macro context where the previous span might not be + // available to avoid incorrect output (#54841). + err.span_label(self.span, "unexpected token"); + } + _ => { + err.span_label(sp, label_exp); + err.span_label(self.span, "unexpected token"); + } + } + Err(err) + } + /// Eats and discards tokens until one of `kets` is encountered. Respects token trees, /// passes through any errors encountered. Used for error recovery. crate fn eat_to_tokens(&mut self, kets: &[&token::Token]) { @@ -939,9 +1047,6 @@ impl<'a> Parser<'a> { String::new(), Applicability::MachineApplicable, ); - err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)"); - err.note("for more information on the status of emplacement syntax, see <\ - https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>"); err.emit(); } } @@ -1050,12 +1155,12 @@ impl<'a> Parser<'a> { ) -> PResult<'a, ast::Arg> { let sp = arg.pat.span; arg.ty.node = TyKind::Err; - let mut err = self.struct_span_err(sp, "unexpected `self` argument in function"); + let mut err = self.struct_span_err(sp, "unexpected `self` parameter in function"); if is_trait_item { - err.span_label(sp, "must be the first associated function argument"); + err.span_label(sp, "must be the first associated function parameter"); } else { - err.span_label(sp, "not valid as function argument"); - err.note("`self` is only valid as the first argument of an associated function"); + err.span_label(sp, "not valid as function parameter"); + err.note("`self` is only valid as the first parameter of an associated function"); } err.emit(); Ok(arg) diff --git a/src/libsyntax/parse/parser.rs b/src/libsyntax/parse/parser.rs index 6d866d7f3d43f..6c29437362c89 100644 --- a/src/libsyntax/parse/parser.rs +++ b/src/libsyntax/parse/parser.rs @@ -49,7 +49,7 @@ use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint}; use crate::symbol::{kw, sym, Symbol}; use crate::parse::diagnostics::Error; -use errors::{Applicability, DiagnosticBuilder, DiagnosticId}; +use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError}; use rustc_target::spec::abi::{self, Abi}; use syntax_pos::{Span, BytePos, DUMMY_SP, FileName, hygiene::CompilerDesugaringKind}; use log::debug; @@ -58,6 +58,7 @@ use std::borrow::Cow; use std::cmp; use std::mem; use std::path::{self, Path, PathBuf}; +use std::slice; #[derive(Debug)] /// Whether the type alias or associated type is a concrete type or an existential type @@ -595,23 +596,6 @@ impl<'a> Parser<'a> { edible: &[token::Token], inedible: &[token::Token], ) -> PResult<'a, bool /* recovered */> { - fn tokens_to_string(tokens: &[TokenType]) -> String { - let mut i = tokens.iter(); - // This might be a sign we need a connect method on Iterator. - let b = i.next() - .map_or(String::new(), |t| t.to_string()); - i.enumerate().fold(b, |mut b, (i, a)| { - if tokens.len() > 2 && i == tokens.len() - 2 { - b.push_str(", or "); - } else if tokens.len() == 2 && i == tokens.len() - 2 { - b.push_str(" or "); - } else { - b.push_str(", "); - } - b.push_str(&a.to_string()); - b - }) - } if edible.contains(&self.token) { self.bump(); Ok(false) @@ -621,120 +605,7 @@ impl<'a> Parser<'a> { } else if self.last_unexpected_token_span == Some(self.span) { FatalError.raise(); } else { - let mut expected = edible.iter() - .map(|x| TokenType::Token(x.clone())) - .chain(inedible.iter().map(|x| TokenType::Token(x.clone()))) - .chain(self.expected_tokens.iter().cloned()) - .collect::>(); - expected.sort_by_cached_key(|x| x.to_string()); - expected.dedup(); - let expect = tokens_to_string(&expected[..]); - let actual = self.this_token_to_string(); - let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 { - let short_expect = if expected.len() > 6 { - format!("{} possible tokens", expected.len()) - } else { - expect.clone() - }; - (format!("expected one of {}, found `{}`", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected one of {} here", short_expect))) - } else if expected.is_empty() { - (format!("unexpected token: `{}`", actual), - (self.prev_span, "unexpected token after this".to_string())) - } else { - (format!("expected {}, found `{}`", expect, actual), - (self.sess.source_map().next_point(self.prev_span), - format!("expected {} here", expect))) - }; - self.last_unexpected_token_span = Some(self.span); - let mut err = self.fatal(&msg_exp); - if self.token.is_ident_named("and") { - err.span_suggestion_short( - self.span, - "use `&&` instead of `and` for the boolean operator", - "&&".to_string(), - Applicability::MaybeIncorrect, - ); - } - if self.token.is_ident_named("or") { - err.span_suggestion_short( - self.span, - "use `||` instead of `or` for the boolean operator", - "||".to_string(), - Applicability::MaybeIncorrect, - ); - } - let sp = if self.token == token::Token::Eof { - // This is EOF, don't want to point at the following char, but rather the last token - self.prev_span - } else { - label_sp - }; - match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt { - TokenType::Token(t) => Some(t.clone()), - _ => None, - }).collect::>(), err) { - Err(e) => err = e, - Ok(recovered) => { - return Ok(recovered); - } - } - - let is_semi_suggestable = expected.iter().any(|t| match t { - TokenType::Token(token::Semi) => true, // we expect a `;` here - _ => false, - }) && ( // a `;` would be expected before the current keyword - self.token.is_keyword(kw::Break) || - self.token.is_keyword(kw::Continue) || - self.token.is_keyword(kw::For) || - self.token.is_keyword(kw::If) || - self.token.is_keyword(kw::Let) || - self.token.is_keyword(kw::Loop) || - self.token.is_keyword(kw::Match) || - self.token.is_keyword(kw::Return) || - self.token.is_keyword(kw::While) - ); - let cm = self.sess.source_map(); - match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) { - (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => { - // The spans are in different lines, expected `;` and found `let` or `return`. - // High likelihood that it is only a missing `;`. - err.span_suggestion_short( - label_sp, - "a semicolon may be missing here", - ";".to_string(), - Applicability::MaybeIncorrect, - ); - err.emit(); - return Ok(true); - } - (Ok(ref a), Ok(ref b)) if a.line == b.line => { - // When the spans are in the same line, it means that the only content between - // them is whitespace, point at the found token in that case: - // - // X | () => { syntax error }; - // | ^^^^^ expected one of 8 possible tokens here - // - // instead of having: - // - // X | () => { syntax error }; - // | -^^^^^ unexpected token - // | | - // | expected one of 8 possible tokens here - err.span_label(self.span, label_exp); - } - _ if self.prev_span == DUMMY_SP => { - // Account for macro context where the previous span might not be - // available to avoid incorrect output (#54841). - err.span_label(self.span, "unexpected token"); - } - _ => { - err.span_label(sp, label_exp); - err.span_label(self.span, "unexpected token"); - } - } - Err(err) + self.expected_one_of_not_found(edible, inedible) } } @@ -1188,6 +1059,34 @@ impl<'a> Parser<'a> { self.expected_tokens.clear(); } + pub fn look_ahead(&self, dist: usize, f: F) -> R where + F: FnOnce(&token::Token) -> R, + { + if dist == 0 { + return f(&self.token) + } + + f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(tree) => match tree { + TokenTree::Token(_, tok) => tok, + TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim), + }, + None => token::CloseDelim(self.token_cursor.frame.delim), + }) + } + + crate fn look_ahead_span(&self, dist: usize) -> Span { + if dist == 0 { + return self.span + } + + match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) { + Some(TokenTree::Token(span, _)) => span, + Some(TokenTree::Delimited(span, ..)) => span.entire(), + None => self.look_ahead_span(dist - 1), + } + } + /// Is the current token one of the keywords that signals a bare function type? fn token_is_bare_fn_keyword(&mut self) -> bool { self.check_keyword(kw::Fn) || diff --git a/src/test/ui/invalid-self-argument/bare-fn-start.rs b/src/test/ui/invalid-self-argument/bare-fn-start.rs index 95a2b69c05cc6..a003a01941bde 100644 --- a/src/test/ui/invalid-self-argument/bare-fn-start.rs +++ b/src/test/ui/invalid-self-argument/bare-fn-start.rs @@ -1,6 +1,6 @@ fn a(&self) { } -//~^ ERROR unexpected `self` argument in function -//~| NOTE not valid as function argument -//~| NOTE `self` is only valid as the first argument of an associated function +//~^ ERROR unexpected `self` parameter in function +//~| NOTE not valid as function parameter +//~| NOTE `self` is only valid as the first parameter of an associated function fn main() { } diff --git a/src/test/ui/invalid-self-argument/bare-fn-start.stderr b/src/test/ui/invalid-self-argument/bare-fn-start.stderr index ba1092ca3770c..23de6502094f0 100644 --- a/src/test/ui/invalid-self-argument/bare-fn-start.stderr +++ b/src/test/ui/invalid-self-argument/bare-fn-start.stderr @@ -1,10 +1,10 @@ -error: unexpected `self` argument in function +error: unexpected `self` parameter in function --> $DIR/bare-fn-start.rs:1:6 | LL | fn a(&self) { } - | ^^^^^ not valid as function argument + | ^^^^^ not valid as function parameter | - = note: `self` is only valid as the first argument of an associated function + = note: `self` is only valid as the first parameter of an associated function error: aborting due to previous error diff --git a/src/test/ui/invalid-self-argument/bare-fn.rs b/src/test/ui/invalid-self-argument/bare-fn.rs index 43c87fb79d88d..73d68e8b7a5ab 100644 --- a/src/test/ui/invalid-self-argument/bare-fn.rs +++ b/src/test/ui/invalid-self-argument/bare-fn.rs @@ -1,6 +1,6 @@ fn b(foo: u32, &mut self) { } -//~^ ERROR unexpected `self` argument in function -//~| NOTE not valid as function argument -//~| NOTE `self` is only valid as the first argument of an associated function +//~^ ERROR unexpected `self` parameter in function +//~| NOTE not valid as function parameter +//~| NOTE `self` is only valid as the first parameter of an associated function fn main() { } diff --git a/src/test/ui/invalid-self-argument/bare-fn.stderr b/src/test/ui/invalid-self-argument/bare-fn.stderr index 16a2d4b4b3737..601a51bb4a96a 100644 --- a/src/test/ui/invalid-self-argument/bare-fn.stderr +++ b/src/test/ui/invalid-self-argument/bare-fn.stderr @@ -1,10 +1,10 @@ -error: unexpected `self` argument in function +error: unexpected `self` parameter in function --> $DIR/bare-fn.rs:1:16 | LL | fn b(foo: u32, &mut self) { } - | ^^^^^^^^^ not valid as function argument + | ^^^^^^^^^ not valid as function parameter | - = note: `self` is only valid as the first argument of an associated function + = note: `self` is only valid as the first parameter of an associated function error: aborting due to previous error diff --git a/src/test/ui/invalid-self-argument/trait-fn.rs b/src/test/ui/invalid-self-argument/trait-fn.rs index 620a06db557b3..1e8220d7b4a78 100644 --- a/src/test/ui/invalid-self-argument/trait-fn.rs +++ b/src/test/ui/invalid-self-argument/trait-fn.rs @@ -2,8 +2,8 @@ struct Foo {} impl Foo { fn c(foo: u32, self) {} - //~^ ERROR unexpected `self` argument in function - //~| NOTE must be the first associated function argument + //~^ ERROR unexpected `self` parameter in function + //~| NOTE must be the first associated function parameter fn good(&mut self, foo: u32) {} } diff --git a/src/test/ui/invalid-self-argument/trait-fn.stderr b/src/test/ui/invalid-self-argument/trait-fn.stderr index 00fedea3fead5..96a2251c036b1 100644 --- a/src/test/ui/invalid-self-argument/trait-fn.stderr +++ b/src/test/ui/invalid-self-argument/trait-fn.stderr @@ -1,8 +1,8 @@ -error: unexpected `self` argument in function +error: unexpected `self` parameter in function --> $DIR/trait-fn.rs:4:20 | LL | fn c(foo: u32, self) {} - | ^^^^ must be the first associated function argument + | ^^^^ must be the first associated function parameter error: aborting due to previous error diff --git a/src/test/ui/parser/self-in-function-arg.rs b/src/test/ui/parser/self-in-function-arg.rs index 502c2c0b74a59..6172ffe1b0347 100644 --- a/src/test/ui/parser/self-in-function-arg.rs +++ b/src/test/ui/parser/self-in-function-arg.rs @@ -1,3 +1,3 @@ -fn foo(x:i32, self: i32) -> i32 { self } //~ ERROR unexpected `self` argument in function +fn foo(x:i32, self: i32) -> i32 { self } //~ ERROR unexpected `self` parameter in function fn main() {} diff --git a/src/test/ui/parser/self-in-function-arg.stderr b/src/test/ui/parser/self-in-function-arg.stderr index e1fc10306cc08..f58df9b9e79b3 100644 --- a/src/test/ui/parser/self-in-function-arg.stderr +++ b/src/test/ui/parser/self-in-function-arg.stderr @@ -1,10 +1,10 @@ -error: unexpected `self` argument in function +error: unexpected `self` parameter in function --> $DIR/self-in-function-arg.rs:1:15 | LL | fn foo(x:i32, self: i32) -> i32 { self } - | ^^^^ not valid as function argument + | ^^^^ not valid as function parameter | - = note: `self` is only valid as the first argument of an associated function + = note: `self` is only valid as the first parameter of an associated function error: aborting due to previous error From e6aa4b8033417732e2906bd9fdb8eec976f92c3d Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 25 May 2019 22:28:15 +0200 Subject: [PATCH 12/12] Add comment to explain why we change the layout for Projection --- src/librustc_mir/interpret/operand.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/librustc_mir/interpret/operand.rs b/src/librustc_mir/interpret/operand.rs index e26b147ea581d..de788a22886ab 100644 --- a/src/librustc_mir/interpret/operand.rs +++ b/src/librustc_mir/interpret/operand.rs @@ -475,6 +475,8 @@ impl<'a, 'mir, 'tcx, M: Machine<'a, 'mir, 'tcx>> InterpretCx<'a, 'mir, 'tcx, M> PlaceBase::Local(mir::RETURN_PLACE) => return err!(ReadFromReturnPointer), PlaceBase::Local(local) => { // FIXME use place_projection.is_empty() when is available + // Do not use the layout passed in as argument if the base we are looking at + // here is not the entire place. let layout = if let Place::Base(_) = mir_place { layout } else {