Skip to content

Commit 10d7da4

Browse files
committed
implement type_implments_trait query
1 parent a1104b4 commit 10d7da4

File tree

10 files changed

+120
-42
lines changed

10 files changed

+120
-42
lines changed

src/librustc_middle/hir/map/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ impl<'hir> Map<'hir> {
390390
/// Given a `HirId`, returns the `BodyId` associated with it,
391391
/// if the node is a body owner, otherwise returns `None`.
392392
pub fn maybe_body_owned_by(&self, hir_id: HirId) -> Option<BodyId> {
393-
if let Some(node) = self.find(hir_id) { associated_body(node) } else { None }
393+
self.find(hir_id).map(associated_body).flatten()
394394
}
395395

396396
/// Given a body owner's id, returns the `BodyId` associated with it.

src/librustc_middle/query/mod.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1164,6 +1164,12 @@ rustc_queries! {
11641164
desc { "evaluating trait selection obligation `{}`", goal.value }
11651165
}
11661166

1167+
query type_implements_trait(
1168+
key: (DefId, Ty<'tcx>, SubstsRef<'tcx>, ty::ParamEnv<'tcx>, )
1169+
) -> bool {
1170+
desc { "evaluating `type_implements_trait` `{:?}`", key }
1171+
}
1172+
11671173
/// Do not call this query directly: part of the `Eq` type-op
11681174
query type_op_ascribe_user_type(
11691175
goal: CanonicalTypeOpAscribeUserTypeGoal<'tcx>

src/librustc_middle/ty/query/keys.rs

+12
Original file line numberDiff line numberDiff line change
@@ -295,3 +295,15 @@ impl Key for (Symbol, u32, u32) {
295295
DUMMY_SP
296296
}
297297
}
298+
299+
impl<'tcx> Key for (DefId, Ty<'tcx>, SubstsRef<'tcx>, ty::ParamEnv<'tcx>) {
300+
type CacheSelector = DefaultCacheSelector;
301+
302+
fn query_crate(&self) -> CrateNum {
303+
LOCAL_CRATE
304+
}
305+
306+
fn default_span(&self, _tcx: TyCtxt<'_>) -> Span {
307+
DUMMY_SP
308+
}
309+
}

src/librustc_trait_selection/traits/error_reporting/suggestions.rs

+19-18
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ use rustc_hir as hir;
1111
use rustc_hir::def::DefKind;
1212
use rustc_hir::def_id::DefId;
1313
use rustc_hir::intravisit::Visitor;
14+
use rustc_hir::lang_items;
1415
use rustc_hir::{AsyncGeneratorKind, GeneratorKind, Node};
1516
use rustc_middle::ty::TypeckTables;
1617
use rustc_middle::ty::{
@@ -1785,37 +1786,37 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
17851786
span: Span,
17861787
) {
17871788
debug!(
1788-
"suggest_await_befor_try: obligation={:?}, span={:?}, trait_ref={:?}",
1789-
obligation, span, trait_ref
1789+
"suggest_await_befor_try: obligation={:?}, span={:?}, trait_ref={:?}, trait_ref_self_ty={:?}",
1790+
obligation,
1791+
span,
1792+
trait_ref,
1793+
trait_ref.self_ty()
17901794
);
17911795
let body_hir_id = obligation.cause.body_id;
17921796
let item_id = self.tcx.hir().get_parent_node(body_hir_id);
17931797

1794-
let mut is_future = false;
1795-
if let ty::Opaque(def_id, substs) = trait_ref.self_ty().kind {
1796-
let preds = self.tcx.predicates_of(def_id).instantiate(self.tcx, substs);
1797-
for p in preds.predicates {
1798-
if let Some(trait_ref) = p.to_opt_poly_trait_ref() {
1799-
if Some(trait_ref.def_id()) == self.tcx.lang_items().future_trait() {
1800-
is_future = true;
1801-
break;
1802-
}
1803-
}
1804-
}
1805-
}
1806-
18071798
if let Some(body_id) = self.tcx.hir().maybe_body_owned_by(item_id) {
18081799
let body = self.tcx.hir().body(body_id);
18091800
if let Some(hir::GeneratorKind::Async(_)) = body.generator_kind {
1810-
let future_trait = self.tcx.lang_items().future_trait().unwrap();
1801+
let future_trait =
1802+
self.tcx.require_lang_item(lang_items::FutureTraitLangItem, None);
1803+
1804+
let self_ty = self.resolve_vars_if_possible(&trait_ref.self_ty());
1805+
1806+
let impls_future = self.tcx.type_implements_trait((
1807+
future_trait,
1808+
self_ty,
1809+
ty::List::empty(),
1810+
obligation.param_env,
1811+
));
1812+
18111813
let item_def_id = self
18121814
.tcx
18131815
.associated_items(future_trait)
18141816
.in_definition_order()
18151817
.next()
18161818
.unwrap()
18171819
.def_id;
1818-
debug!("trait_ref_self_ty: {:?}", trait_ref.self_ty());
18191820
// `<T as Future>::Output`
18201821
let projection_ty = ty::ProjectionTy {
18211822
// `T`
@@ -1850,7 +1851,7 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
18501851
obligation.param_env,
18511852
);
18521853
debug!("suggest_await_befor_try: try_trait_obligation {:?}", try_obligation);
1853-
if self.predicate_may_hold(&try_obligation) && is_future {
1854+
if self.predicate_may_hold(&try_obligation) && impls_future {
18541855
if let Ok(snippet) = self.tcx.sess.source_map().span_to_snippet(span) {
18551856
if snippet.ends_with('?') {
18561857
err.span_suggestion(

src/librustc_trait_selection/traits/mod.rs

+41-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ use rustc_hir::def_id::DefId;
3131
use rustc_middle::middle::region;
3232
use rustc_middle::ty::fold::TypeFoldable;
3333
use rustc_middle::ty::subst::{InternalSubsts, SubstsRef};
34-
use rustc_middle::ty::{self, GenericParamDefKind, ToPredicate, Ty, TyCtxt, WithConstness};
34+
use rustc_middle::ty::{
35+
self, GenericParamDefKind, ParamEnv, ToPredicate, Ty, TyCtxt, WithConstness,
36+
};
3537
use rustc_span::Span;
3638

3739
use std::fmt::Debug;
@@ -523,6 +525,43 @@ fn vtable_methods<'tcx>(
523525
}))
524526
}
525527

528+
/// Check whether a `ty` implements given trait(trait_def_id).
529+
///
530+
/// NOTE: Always return `false` for a type which needs inference.
531+
fn type_implements_trait<'tcx>(
532+
tcx: TyCtxt<'tcx>,
533+
key: (
534+
DefId, // trait_def_id,
535+
Ty<'tcx>, // type
536+
SubstsRef<'tcx>,
537+
ParamEnv<'tcx>,
538+
),
539+
) -> bool {
540+
let (trait_def_id, ty, params, param_env) = key;
541+
542+
debug!(
543+
"type_implements_trait: trait_def_id={:?}, type={:?}, params={:?}, param_env={:?}",
544+
trait_def_id, ty, params, param_env
545+
);
546+
547+
// Do not check on infer_types to avoid panic in evaluate_obligation.
548+
if ty.has_infer_types() {
549+
return false;
550+
}
551+
552+
let ty = tcx.erase_regions(&ty);
553+
554+
let trait_ref = ty::TraitRef { def_id: trait_def_id, substs: tcx.mk_substs_trait(ty, params) };
555+
556+
let obligation = Obligation {
557+
cause: ObligationCause::dummy(),
558+
param_env,
559+
recursion_depth: 0,
560+
predicate: trait_ref.without_const().to_predicate(),
561+
};
562+
tcx.infer_ctxt().enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
563+
}
564+
526565
pub fn provide(providers: &mut ty::query::Providers<'_>) {
527566
object_safety::provide(providers);
528567
*providers = ty::query::Providers {
@@ -531,6 +570,7 @@ pub fn provide(providers: &mut ty::query::Providers<'_>) {
531570
codegen_fulfill_obligation: codegen::codegen_fulfill_obligation,
532571
vtable_methods,
533572
substitute_normalize_and_test_predicates,
573+
type_implements_trait,
534574
..*providers
535575
};
536576
}

src/test/ui/async-await/issue-61076.rs

+20
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,19 @@
11
// edition:2018
22

3+
use core::future::Future;
4+
use core::pin::Pin;
5+
use core::task::{Context, Poll};
6+
7+
struct T;
8+
9+
impl Future for T {
10+
type Output = Result<(), ()>;
11+
12+
fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
13+
Poll::Pending
14+
}
15+
}
16+
317
async fn foo() -> Result<(), ()> {
418
Ok(())
519
}
@@ -9,4 +23,10 @@ async fn bar() -> Result<(), ()> {
923
Ok(())
1024
}
1125

26+
async fn baz() -> Result<(), ()> {
27+
let t = T;
28+
t?; //~ ERROR the `?` operator can only be applied to values that implement `std::ops::Try`
29+
Ok(())
30+
}
31+
1232
fn main() {}

src/test/ui/async-await/issue-61076.stderr

+14-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
2-
--> $DIR/issue-61076.rs:8:5
2+
--> $DIR/issue-61076.rs:22:5
33
|
44
LL | foo()?;
55
| ^^^^^^
@@ -10,6 +10,18 @@ LL | foo()?;
1010
= help: the trait `std::ops::Try` is not implemented for `impl std::future::Future`
1111
= note: required by `std::ops::Try::into_result`
1212

13-
error: aborting due to previous error
13+
error[E0277]: the `?` operator can only be applied to values that implement `std::ops::Try`
14+
--> $DIR/issue-61076.rs:28:5
15+
|
16+
LL | t?;
17+
| ^^
18+
| |
19+
| the `?` operator cannot be applied to type `T`
20+
| help: consider using `.await` here: `t.await?`
21+
|
22+
= help: the trait `std::ops::Try` is not implemented for `T`
23+
= note: required by `std::ops::Try::into_result`
24+
25+
error: aborting due to 2 previous errors
1426

1527
For more information about this error, try `rustc --explain E0277`.

src/test/ui/async-await/try-on-option-in-async.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ async fn an_async_block() -> u32 {
77
let x: Option<u32> = None;
88
x?; //~ ERROR the `?` operator
99
22
10-
}.await
10+
}
11+
.await
1112
}
1213

1314
async fn async_closure_containing_fn() -> u32 {

src/test/ui/async-await/try-on-option-in-async.stderr

+3-3
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,14 @@ LL | | let x: Option<u32> = None;
77
LL | | x?;
88
| | ^^ cannot use the `?` operator in an async block that returns `{integer}`
99
LL | | 22
10-
LL | | }.await
10+
LL | | }
1111
| |_____- this function should return `Result` or `Option` to accept `?`
1212
|
1313
= help: the trait `std::ops::Try` is not implemented for `{integer}`
1414
= note: required by `std::ops::Try::from_error`
1515

1616
error[E0277]: the `?` operator can only be used in an async closure that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
17-
--> $DIR/try-on-option-in-async.rs:16:9
17+
--> $DIR/try-on-option-in-async.rs:17:9
1818
|
1919
LL | let async_closure = async || {
2020
| __________________________________-
@@ -29,7 +29,7 @@ LL | | };
2929
= note: required by `std::ops::Try::from_error`
3030

3131
error[E0277]: the `?` operator can only be used in an async function that returns `Result` or `Option` (or another type that implements `std::ops::Try`)
32-
--> $DIR/try-on-option-in-async.rs:25:5
32+
--> $DIR/try-on-option-in-async.rs:26:5
3333
|
3434
LL | async fn an_async_function() -> u32 {
3535
| _____________________________________-

src/tools/clippy/clippy_lints/src/utils/mod.rs

+2-16
Original file line numberDiff line numberDiff line change
@@ -40,15 +40,12 @@ use rustc_hir::{
4040
use rustc_infer::infer::TyCtxtInferExt;
4141
use rustc_lint::{LateContext, Level, Lint, LintContext};
4242
use rustc_middle::hir::map::Map;
43-
use rustc_middle::traits;
4443
use rustc_middle::ty::{self, layout::IntegerExt, subst::GenericArg, Binder, Ty, TyCtxt, TypeFoldable};
4544
use rustc_span::hygiene::{ExpnKind, MacroKind};
4645
use rustc_span::source_map::original_sp;
4746
use rustc_span::symbol::{self, kw, Symbol};
4847
use rustc_span::{BytePos, Pos, Span, DUMMY_SP};
4948
use rustc_target::abi::Integer;
50-
use rustc_trait_selection::traits::predicate_for_trait_def;
51-
use rustc_trait_selection::traits::query::evaluate_obligation::InferCtxtExt;
5249
use rustc_trait_selection::traits::query::normalize::AtExt;
5350
use smallvec::SmallVec;
5451

@@ -326,19 +323,8 @@ pub fn implements_trait<'a, 'tcx>(
326323
trait_id: DefId,
327324
ty_params: &[GenericArg<'tcx>],
328325
) -> bool {
329-
let ty = cx.tcx.erase_regions(&ty);
330-
let obligation = predicate_for_trait_def(
331-
cx.tcx,
332-
cx.param_env,
333-
traits::ObligationCause::dummy(),
334-
trait_id,
335-
0,
336-
ty,
337-
ty_params,
338-
);
339-
cx.tcx
340-
.infer_ctxt()
341-
.enter(|infcx| infcx.predicate_must_hold_modulo_regions(&obligation))
326+
let ty_params = cx.tcx.mk_substs(ty_params.iter());
327+
cx.tcx.type_implements_trait((trait_id, ty, ty_params, cx.param_env))
342328
}
343329

344330
/// Gets the `hir::TraitRef` of the trait the given method is implemented for.

0 commit comments

Comments
 (0)