Skip to content

Commit 421bd77

Browse files
committed
Auto merge of #64564 - jonas-schievink:cowardly-default, r=nikomatsakis
Deny specializing items not in the parent impl Part of #29661 (rust-lang/rfcs#2532). At least sort of? This was discussed in #61812 (comment) and is needed for that PR to make progress (fixing an unsoundness). One annoyance with doing this is that it sometimes requires users to copy-paste a provided trait method into an impl just to mark it `default` (ie. there is no syntax to forward this impl method to the provided trait method). cc @Centril and @arielb1
2 parents 9203ee7 + 47f89e7 commit 421bd77

File tree

12 files changed

+268
-45
lines changed

12 files changed

+268
-45
lines changed

src/liballoc/boxed.rs

+24-2
Original file line numberDiff line numberDiff line change
@@ -871,11 +871,33 @@ impl<I: Iterator + ?Sized> Iterator for Box<I> {
871871
fn nth(&mut self, n: usize) -> Option<I::Item> {
872872
(**self).nth(n)
873873
}
874+
fn last(self) -> Option<I::Item> {
875+
BoxIter::last(self)
876+
}
877+
}
878+
879+
trait BoxIter {
880+
type Item;
881+
fn last(self) -> Option<Self::Item>;
882+
}
883+
884+
impl<I: Iterator + ?Sized> BoxIter for Box<I> {
885+
type Item = I::Item;
886+
default fn last(self) -> Option<I::Item> {
887+
#[inline]
888+
fn some<T>(_: Option<T>, x: T) -> Option<T> {
889+
Some(x)
890+
}
891+
892+
self.fold(None, some)
893+
}
874894
}
875895

896+
/// Specialization for sized `I`s that uses `I`s implementation of `last()`
897+
/// instead of the default.
876898
#[stable(feature = "rust1", since = "1.0.0")]
877-
impl<I: Iterator + Sized> Iterator for Box<I> {
878-
fn last(self) -> Option<I::Item> where I: Sized {
899+
impl<I: Iterator> BoxIter for Box<I> {
900+
fn last(self) -> Option<I::Item> {
879901
(*self).last()
880902
}
881903
}

src/librustc/traits/project.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -1505,8 +1505,8 @@ fn assoc_ty_def(
15051505

15061506
if let Some(assoc_item) = trait_def
15071507
.ancestors(tcx, impl_def_id)
1508-
.defs(tcx, assoc_ty_name, ty::AssocKind::Type, trait_def_id)
1509-
.next() {
1508+
.leaf_def(tcx, assoc_ty_name, ty::AssocKind::Type) {
1509+
15101510
assoc_item
15111511
} else {
15121512
// This is saying that neither the trait nor

src/librustc/traits/specialize/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ pub fn find_associated_item<'tcx>(
125125
let trait_def = tcx.trait_def(trait_def_id);
126126

127127
let ancestors = trait_def.ancestors(tcx, impl_data.impl_def_id);
128-
match ancestors.defs(tcx, item.ident, item.kind, trait_def_id).next() {
128+
match ancestors.leaf_def(tcx, item.ident, item.kind) {
129129
Some(node_item) => {
130130
let substs = tcx.infer_ctxt().enter(|infcx| {
131131
let param_env = param_env.with_reveal_all();

src/librustc/traits/specialize/specialization_graph.rs

+39-24
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ use crate::traits;
77
use crate::ty::{self, TyCtxt, TypeFoldable};
88
use crate::ty::fast_reject::{self, SimplifiedType};
99
use syntax::ast::Ident;
10-
use crate::util::captures::Captures;
1110
use crate::util::nodemap::{DefIdMap, FxHashMap};
1211

1312
/// A per-trait graph of impls in specialization order. At the moment, this
@@ -419,6 +418,35 @@ impl<'tcx> Node {
419418
tcx.associated_items(self.def_id())
420419
}
421420

421+
/// Finds an associated item defined in this node.
422+
///
423+
/// If this returns `None`, the item can potentially still be found in
424+
/// parents of this node.
425+
pub fn item(
426+
&self,
427+
tcx: TyCtxt<'tcx>,
428+
trait_item_name: Ident,
429+
trait_item_kind: ty::AssocKind,
430+
trait_def_id: DefId,
431+
) -> Option<ty::AssocItem> {
432+
use crate::ty::AssocKind::*;
433+
434+
tcx.associated_items(self.def_id())
435+
.find(move |impl_item| match (trait_item_kind, impl_item.kind) {
436+
| (Const, Const)
437+
| (Method, Method)
438+
| (Type, Type)
439+
| (Type, OpaqueTy) // assoc. types can be made opaque in impls
440+
=> tcx.hygienic_eq(impl_item.ident, trait_item_name, trait_def_id),
441+
442+
| (Const, _)
443+
| (Method, _)
444+
| (Type, _)
445+
| (OpaqueTy, _)
446+
=> false,
447+
})
448+
}
449+
422450
pub fn def_id(&self) -> DefId {
423451
match *self {
424452
Node::Impl(did) => did,
@@ -427,6 +455,7 @@ impl<'tcx> Node {
427455
}
428456
}
429457

458+
#[derive(Copy, Clone)]
430459
pub struct Ancestors<'tcx> {
431460
trait_def_id: DefId,
432461
specialization_graph: &'tcx Graph,
@@ -465,32 +494,18 @@ impl<T> NodeItem<T> {
465494
}
466495

467496
impl<'tcx> Ancestors<'tcx> {
468-
/// Search the items from the given ancestors, returning each definition
469-
/// with the given name and the given kind.
470-
// FIXME(#35870): avoid closures being unexported due to `impl Trait`.
471-
#[inline]
472-
pub fn defs(
473-
self,
497+
/// Finds the bottom-most (ie. most specialized) definition of an associated
498+
/// item.
499+
pub fn leaf_def(
500+
mut self,
474501
tcx: TyCtxt<'tcx>,
475502
trait_item_name: Ident,
476503
trait_item_kind: ty::AssocKind,
477-
trait_def_id: DefId,
478-
) -> impl Iterator<Item = NodeItem<ty::AssocItem>> + Captures<'tcx> + 'tcx {
479-
self.flat_map(move |node| {
480-
use crate::ty::AssocKind::*;
481-
node.items(tcx).filter(move |impl_item| match (trait_item_kind, impl_item.kind) {
482-
| (Const, Const)
483-
| (Method, Method)
484-
| (Type, Type)
485-
| (Type, OpaqueTy)
486-
=> tcx.hygienic_eq(impl_item.ident, trait_item_name, trait_def_id),
487-
488-
| (Const, _)
489-
| (Method, _)
490-
| (Type, _)
491-
| (OpaqueTy, _)
492-
=> false,
493-
}).map(move |item| NodeItem { node: node, item: item })
504+
) -> Option<NodeItem<ty::AssocItem>> {
505+
let trait_def_id = self.trait_def_id;
506+
self.find_map(|node| {
507+
node.item(tcx, trait_item_name, trait_item_kind, trait_def_id)
508+
.map(|item| NodeItem { node, item })
494509
})
495510
}
496511
}

src/librustc/traits/util.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ use syntax_pos::Span;
44

55
use crate::hir;
66
use crate::hir::def_id::DefId;
7-
use crate::traits::specialize::specialization_graph::NodeItem;
87
use crate::ty::{self, Ty, TyCtxt, ToPredicate, ToPolyTraitRef};
98
use crate::ty::outlives::Component;
109
use crate::ty::subst::{GenericArg, Subst, SubstsRef};
@@ -667,8 +666,8 @@ impl<'tcx> TyCtxt<'tcx> {
667666
}
668667
}
669668

670-
pub fn impl_item_is_final(self, node_item: &NodeItem<hir::Defaultness>) -> bool {
671-
node_item.item.is_final() && !self.impl_is_default(node_item.node.def_id())
669+
pub fn impl_item_is_final(self, assoc_item: &ty::AssocItem) -> bool {
670+
assoc_item.defaultness.is_final() && !self.impl_is_default(assoc_item.container.id())
672671
}
673672
}
674673

src/librustc/ty/query/config.rs

+11
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,17 @@ impl<'tcx, M: QueryAccessors<'tcx, Key = DefId>> QueryDescription<'tcx> for M {
7373
format!("processing {:?} with query `{}`", def_id, name).into()
7474
}
7575
}
76+
77+
default fn cache_on_disk(_: TyCtxt<'tcx>, _: Self::Key, _: Option<&Self::Value>) -> bool {
78+
false
79+
}
80+
81+
default fn try_load_from_disk(
82+
_: TyCtxt<'tcx>,
83+
_: SerializedDepNodeIndex,
84+
) -> Option<Self::Value> {
85+
bug!("QueryDescription::load_from_disk() called for an unsupported query.")
86+
}
7687
}
7788

7889
impl<'tcx> QueryDescription<'tcx> for queries::analysis<'tcx> {

src/librustc_typeck/check/mod.rs

+45-10
Original file line numberDiff line numberDiff line change
@@ -1713,24 +1713,60 @@ fn check_specialization_validity<'tcx>(
17131713
impl_id: DefId,
17141714
impl_item: &hir::ImplItem,
17151715
) {
1716-
let ancestors = trait_def.ancestors(tcx, impl_id);
1717-
17181716
let kind = match impl_item.kind {
17191717
hir::ImplItemKind::Const(..) => ty::AssocKind::Const,
17201718
hir::ImplItemKind::Method(..) => ty::AssocKind::Method,
17211719
hir::ImplItemKind::OpaqueTy(..) => ty::AssocKind::OpaqueTy,
17221720
hir::ImplItemKind::TyAlias(_) => ty::AssocKind::Type,
17231721
};
17241722

1725-
let parent = ancestors.defs(tcx, trait_item.ident, kind, trait_def.def_id).nth(1)
1726-
.map(|node_item| node_item.map(|parent| parent.defaultness));
1723+
let mut ancestor_impls = trait_def.ancestors(tcx, impl_id)
1724+
.skip(1)
1725+
.filter_map(|parent| {
1726+
if parent.is_from_trait() {
1727+
None
1728+
} else {
1729+
Some((parent, parent.item(tcx, trait_item.ident, kind, trait_def.def_id)))
1730+
}
1731+
})
1732+
.peekable();
17271733

1728-
if let Some(parent) = parent {
1729-
if tcx.impl_item_is_final(&parent) {
1730-
report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
1731-
}
1734+
if ancestor_impls.peek().is_none() {
1735+
// No parent, nothing to specialize.
1736+
return;
17321737
}
17331738

1739+
let opt_result = ancestor_impls.find_map(|(parent_impl, parent_item)| {
1740+
match parent_item {
1741+
// Parent impl exists, and contains the parent item we're trying to specialize, but
1742+
// doesn't mark it `default`.
1743+
Some(parent_item) if tcx.impl_item_is_final(&parent_item) => {
1744+
Some(Err(parent_impl.def_id()))
1745+
}
1746+
1747+
// Parent impl contains item and makes it specializable.
1748+
Some(_) => {
1749+
Some(Ok(()))
1750+
}
1751+
1752+
// Parent impl doesn't mention the item. This means it's inherited from the
1753+
// grandparent. In that case, if parent is a `default impl`, inherited items use the
1754+
// "defaultness" from the grandparent, else they are final.
1755+
None => if tcx.impl_is_default(parent_impl.def_id()) {
1756+
None
1757+
} else {
1758+
Some(Err(parent_impl.def_id()))
1759+
}
1760+
}
1761+
});
1762+
1763+
// If `opt_result` is `None`, we have only encoutered `default impl`s that don't contain the
1764+
// item. This is allowed, the item isn't actually getting specialized here.
1765+
let result = opt_result.unwrap_or(Ok(()));
1766+
1767+
if let Err(parent_impl) = result {
1768+
report_forbidden_specialization(tcx, impl_item, parent_impl);
1769+
}
17341770
}
17351771

17361772
fn check_impl_items_against_trait<'tcx>(
@@ -1846,8 +1882,7 @@ fn check_impl_items_against_trait<'tcx>(
18461882
let associated_type_overridden = overridden_associated_type.is_some();
18471883
for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
18481884
let is_implemented = trait_def.ancestors(tcx, impl_id)
1849-
.defs(tcx, trait_item.ident, trait_item.kind, impl_trait_ref.def_id)
1850-
.next()
1885+
.leaf_def(tcx, trait_item.ident, trait_item.kind)
18511886
.map(|node_item| !node_item.node.is_from_trait())
18521887
.unwrap_or(false);
18531888

src/test/ui/specialization/auxiliary/cross_crates_defaults.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,9 @@ pub trait Bar {
2222
fn bar(&self) -> i32 { 0 }
2323
}
2424

25-
impl<T> Bar for T {} // use the provided method
25+
impl<T> Bar for T {
26+
default fn bar(&self) -> i32 { 0 }
27+
}
2628

2729
impl Bar for i32 {
2830
fn bar(&self) -> i32 { 1 }

src/test/ui/specialization/issue-36804.rs

+4
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,10 @@ where
1313
fn next(&mut self) -> Option<T> {
1414
unimplemented!()
1515
}
16+
17+
default fn count(self) -> usize where Self: Sized {
18+
self.fold(0, |cnt, _| cnt + 1)
19+
}
1620
}
1721

1822
impl<'a, I, T: 'a> Iterator for Cloned<I>
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#![feature(specialization, associated_type_defaults)]
2+
3+
// Test that attempting to override a non-default method or one not in the
4+
// parent impl causes an error.
5+
6+
trait Foo {
7+
type Ty = ();
8+
const CONST: u8 = 123;
9+
fn foo(&self) -> bool { true }
10+
}
11+
12+
// Specialization tree for Foo:
13+
//
14+
// Box<T> Vec<T>
15+
// / \ / \
16+
// Box<i32> Box<i64> Vec<()> Vec<bool>
17+
18+
impl<T> Foo for Box<T> {
19+
type Ty = bool;
20+
const CONST: u8 = 0;
21+
fn foo(&self) -> bool { false }
22+
}
23+
24+
// Allowed
25+
impl Foo for Box<i32> {}
26+
27+
// Can't override a non-`default` fn
28+
impl Foo for Box<i64> {
29+
type Ty = Vec<()>;
30+
//~^ error: `Ty` specializes an item from a parent `impl`, but that item is not marked `default`
31+
const CONST: u8 = 42;
32+
//~^ error: `CONST` specializes an item from a parent `impl`, but that item is not marked `default`
33+
fn foo(&self) -> bool { true }
34+
//~^ error: `foo` specializes an item from a parent `impl`, but that item is not marked `default`
35+
}
36+
37+
38+
// Doesn't mention the item = provided body/value is used and the method is final.
39+
impl<T> Foo for Vec<T> {}
40+
41+
// Allowed
42+
impl Foo for Vec<()> {}
43+
44+
impl Foo for Vec<bool> {
45+
type Ty = Vec<()>;
46+
//~^ error: `Ty` specializes an item from a parent `impl`, but that item is not marked `default`
47+
const CONST: u8 = 42;
48+
//~^ error: `CONST` specializes an item from a parent `impl`, but that item is not marked `default`
49+
fn foo(&self) -> bool { true }
50+
//~^ error: `foo` specializes an item from a parent `impl`, but that item is not marked `default`
51+
}
52+
53+
fn main() {}

0 commit comments

Comments
 (0)