Skip to content

Querify object_safety_violations. #69242

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/librustc/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -653,7 +653,7 @@ rustc_queries! {
desc { |tcx| "building specialization graph of trait `{}`", tcx.def_path_str(key) }
cache_on_disk_if { true }
}
query is_object_safe(key: DefId) -> bool {
query object_safety_violations(key: DefId) -> Vec<traits::ObjectSafetyViolation> {
desc { |tcx| "determine object safety of trait `{}`", tcx.def_path_str(key) }
}

Expand Down
132 changes: 132 additions & 0 deletions src/librustc/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,10 @@ use crate::ty::{self, AdtKind, List, Ty, TyCtxt};
use rustc_hir as hir;
use rustc_hir::def_id::DefId;
use rustc_span::{Span, DUMMY_SP};
use smallvec::SmallVec;
use syntax::ast;

use std::borrow::Cow;
use std::fmt::Debug;
use std::rc::Rc;

Expand Down Expand Up @@ -737,3 +739,133 @@ where
tcx: TyCtxt<'tcx>,
) -> Option<Self::LiftedLiteral>;
}

#[derive(Clone, Debug, PartialEq, Eq, Hash, HashStable)]
pub enum ObjectSafetyViolation {
/// `Self: Sized` declared on the trait.
SizedSelf(SmallVec<[Span; 1]>),

/// Supertrait reference references `Self` an in illegal location
/// (e.g., `trait Foo : Bar<Self>`).
SupertraitSelf(SmallVec<[Span; 1]>),

/// Method has something illegal.
Method(ast::Name, MethodViolationCode, Span),

/// Associated const.
AssocConst(ast::Name, Span),
}

impl ObjectSafetyViolation {
pub fn error_msg(&self) -> Cow<'static, str> {
match *self {
ObjectSafetyViolation::SizedSelf(_) => "it requires `Self: Sized`".into(),
ObjectSafetyViolation::SupertraitSelf(ref spans) => {
if spans.iter().any(|sp| *sp != DUMMY_SP) {
"it uses `Self` as a type parameter in this".into()
} else {
"it cannot use `Self` as a type parameter in a supertrait or `where`-clause"
.into()
}
}
ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(_), _) => {
format!("associated function `{}` has no `self` parameter", name).into()
}
ObjectSafetyViolation::Method(
name,
MethodViolationCode::ReferencesSelfInput(_),
DUMMY_SP,
) => format!("method `{}` references the `Self` type in its parameters", name).into(),
ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfInput(_), _) => {
format!("method `{}` references the `Self` type in this parameter", name).into()
}
ObjectSafetyViolation::Method(name, MethodViolationCode::ReferencesSelfOutput, _) => {
format!("method `{}` references the `Self` type in its return type", name).into()
}
ObjectSafetyViolation::Method(
name,
MethodViolationCode::WhereClauseReferencesSelf,
_,
) => {
format!("method `{}` references the `Self` type in its `where` clause", name).into()
}
ObjectSafetyViolation::Method(name, MethodViolationCode::Generic, _) => {
format!("method `{}` has generic type parameters", name).into()
}
ObjectSafetyViolation::Method(name, MethodViolationCode::UndispatchableReceiver, _) => {
format!("method `{}`'s `self` parameter cannot be dispatched on", name).into()
}
ObjectSafetyViolation::AssocConst(name, DUMMY_SP) => {
format!("it contains associated `const` `{}`", name).into()
}
ObjectSafetyViolation::AssocConst(..) => "it contains this associated `const`".into(),
}
}

pub fn solution(&self) -> Option<(String, Option<(String, Span)>)> {
Some(match *self {
ObjectSafetyViolation::SizedSelf(_) | ObjectSafetyViolation::SupertraitSelf(_) => {
return None;
}
ObjectSafetyViolation::Method(name, MethodViolationCode::StaticMethod(sugg), _) => (
format!(
"consider turning `{}` into a method by giving it a `&self` argument or \
constraining it so it does not apply to trait objects",
name
),
sugg.map(|(sugg, sp)| (sugg.to_string(), sp)),
),
ObjectSafetyViolation::Method(
name,
MethodViolationCode::UndispatchableReceiver,
span,
) => (
format!("consider changing method `{}`'s `self` parameter to be `&self`", name)
.into(),
Some(("&Self".to_string(), span)),
),
ObjectSafetyViolation::AssocConst(name, _)
| ObjectSafetyViolation::Method(name, ..) => {
(format!("consider moving `{}` to another trait", name), None)
}
})
}

pub fn spans(&self) -> SmallVec<[Span; 1]> {
// When `span` comes from a separate crate, it'll be `DUMMY_SP`. Treat it as `None` so
// diagnostics use a `note` instead of a `span_label`.
match self {
ObjectSafetyViolation::SupertraitSelf(spans)
| ObjectSafetyViolation::SizedSelf(spans) => spans.clone(),
ObjectSafetyViolation::AssocConst(_, span)
| ObjectSafetyViolation::Method(_, _, span)
if *span != DUMMY_SP =>
{
smallvec![*span]
}
_ => smallvec![],
}
}
}

/// Reasons a method might not be object-safe.
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash, HashStable)]
pub enum MethodViolationCode {
/// e.g., `fn foo()`
StaticMethod(Option<(&'static str, Span)>),

/// e.g., `fn foo(&self, x: Self)`
ReferencesSelfInput(usize),

/// e.g., `fn foo(&self) -> Self`
ReferencesSelfOutput,

/// e.g., `fn foo(&self) where Self: Clone`
WhereClauseReferencesSelf,

/// e.g., `fn foo<A>()`
Generic,

/// the method's receiver (`self` argument) can't be dispatched on
UndispatchableReceiver,
}
4 changes: 4 additions & 0 deletions src/librustc/ty/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2998,6 +2998,10 @@ impl<'tcx> TyCtxt<'tcx> {
};
(ident, scope)
}

pub fn is_object_safe(self, key: DefId) -> bool {
self.object_safety_violations(key).is_empty()
}
}

#[derive(Clone, HashStable)]
Expand Down
2 changes: 1 addition & 1 deletion src/librustc_incremental/persist/dirty_clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const BASE_STRUCT: &[&str] =
const BASE_TRAIT_DEF: &[&str] = &[
label_strs::associated_item_def_ids,
label_strs::generics_of,
label_strs::is_object_safe,
label_strs::object_safety_violations,
label_strs::predicates_of,
label_strs::specialization_graph_of,
label_strs::trait_def,
Expand Down
3 changes: 1 addition & 2 deletions src/librustc_infer/infer/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ use super::{InferCtxt, RegionVariableOrigin, SubregionOrigin, TypeTrace, ValuePa
use crate::infer::opaque_types;
use crate::infer::{self, SuppressRegionErrors};
use crate::traits::error_reporting::report_object_safety_error;
use crate::traits::object_safety_violations;
use crate::traits::{
IfExpressionCause, MatchExpressionArmCause, ObligationCause, ObligationCauseCode,
};
Expand Down Expand Up @@ -1618,7 +1617,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
let failure_code = trace.cause.as_failure_code(terr);
let mut diag = match failure_code {
FailureCode::Error0038(did) => {
let violations = object_safety_violations(self.tcx, did);
let violations = self.tcx.object_safety_violations(did);
report_object_safety_error(self.tcx, span, did, violations)
}
FailureCode::Error0317(failure_str) => {
Expand Down
5 changes: 2 additions & 3 deletions src/librustc_infer/traits/error_reporting/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use super::{
use crate::infer::error_reporting::{TyCategory, TypeAnnotationNeeded as ErrorCode};
use crate::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind};
use crate::infer::{self, InferCtxt, TyCtxtInferExt};
use crate::traits::object_safety_violations;
use rustc::mir::interpret::ErrorHandled;
use rustc::session::DiagnosticMessageId;
use rustc::ty::error::ExpectedFound;
Expand Down Expand Up @@ -748,7 +747,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}

ty::Predicate::ObjectSafe(trait_def_id) => {
let violations = object_safety_violations(self.tcx, trait_def_id);
let violations = self.tcx.object_safety_violations(trait_def_id);
report_object_safety_error(self.tcx, span, trait_def_id, violations)
}

Expand Down Expand Up @@ -912,7 +911,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
}

TraitNotObjectSafe(did) => {
let violations = object_safety_violations(self.tcx, did);
let violations = self.tcx.object_safety_violations(did);
report_object_safety_error(self.tcx, span, did, violations)
}

Expand Down
3 changes: 1 addition & 2 deletions src/librustc_infer/traits/error_reporting/suggestions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use super::{

use crate::infer::InferCtxt;
use crate::traits::error_reporting::suggest_constraining_type_param;
use crate::traits::object_safety::object_safety_violations;

use rustc::ty::TypeckTables;
use rustc::ty::{self, AdtKind, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
Expand Down Expand Up @@ -587,7 +586,7 @@ impl<'a, 'tcx> InferCtxt<'a, 'tcx> {
// If the `dyn Trait` is not object safe, do not suggest `Box<dyn Trait>`.
predicates
.principal_def_id()
.map_or(true, |def_id| object_safety_violations(self.tcx, def_id).is_empty())
.map_or(true, |def_id| self.tcx.object_safety_violations(def_id).is_empty())
}
// We only want to suggest `impl Trait` to `dyn Trait`s.
// For example, `fn foo() -> str` needs to be filtered out.
Expand Down
3 changes: 1 addition & 2 deletions src/librustc_infer/traits/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ pub use self::engine::{TraitEngine, TraitEngineExt};
pub use self::fulfill::{FulfillmentContext, PendingPredicateObligation};
pub use self::object_safety::astconv_object_safety_violations;
pub use self::object_safety::is_vtable_safe_method;
pub use self::object_safety::object_safety_violations;
pub use self::object_safety::MethodViolationCode;
pub use self::object_safety::ObjectSafetyViolation;
pub use self::on_unimplemented::{OnUnimplementedDirective, OnUnimplementedNote};
Expand Down Expand Up @@ -636,8 +635,8 @@ impl<'tcx> TraitObligation<'tcx> {
}

pub fn provide(providers: &mut ty::query::Providers<'_>) {
object_safety::provide(providers);
*providers = ty::query::Providers {
is_object_safe: object_safety::is_object_safe_provider,
specialization_graph_of: specialize::specialization_graph_provider,
specializes: specialize::specializes,
codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
Expand Down
Loading