Skip to content

Commit 846891a

Browse files
committed
Auto merge of rust-lang#41494 - withoutboats:associated-consts-are-not-object-safe, r=eddyb
Associated consts are not object safe. fixes rust-lang#26847 r? @eddyb
2 parents 15ce540 + 5dc43d2 commit 846891a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/librustc/traits/object_safety.rs

+9
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,9 @@ pub enum ObjectSafetyViolation {
3737

3838
/// Method has something illegal
3939
Method(ast::Name, MethodViolationCode),
40+
41+
/// Associated const
42+
AssociatedConst(ast::Name),
4043
}
4144

4245
impl ObjectSafetyViolation {
@@ -54,6 +57,8 @@ impl ObjectSafetyViolation {
5457
in its arguments or return type", name).into(),
5558
ObjectSafetyViolation::Method(name, MethodViolationCode::Generic) =>
5659
format!("method `{}` has generic type parameters", name).into(),
60+
ObjectSafetyViolation::AssociatedConst(name) =>
61+
format!("the trait cannot contain associated consts like `{}`", name).into(),
5762
}
5863
}
5964
}
@@ -141,6 +146,10 @@ impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
141146
violations.push(ObjectSafetyViolation::SupertraitSelf);
142147
}
143148

149+
violations.extend(self.associated_items(trait_def_id)
150+
.filter(|item| item.kind == ty::AssociatedKind::Const)
151+
.map(|item| ObjectSafetyViolation::AssociatedConst(item.name)));
152+
144153
debug!("object_safety_violations_for_trait(trait_def_id={:?}) = {:?}",
145154
trait_def_id,
146155
violations);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// Check that we correctly prevent users from making trait objects
12+
// from traits with associated consts.
13+
14+
#![feature(associated_consts)]
15+
16+
trait Bar {
17+
const X: usize;
18+
}
19+
20+
fn make_bar<T:Bar>(t: &T) -> &Bar {
21+
//~^ ERROR E0038
22+
//~| NOTE the trait cannot contain associated consts like `X`
23+
//~| NOTE the trait `Bar` cannot be made into an object
24+
t
25+
}
26+
27+
fn main() {
28+
}

0 commit comments

Comments
 (0)