Skip to content

Commit 289f46a

Browse files
committed
Detect mistyped associated consts in Instance::resolve.
1 parent 0b83a5a commit 289f46a

File tree

20 files changed

+142
-52
lines changed

20 files changed

+142
-52
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4310,6 +4310,7 @@ version = "0.0.0"
43104310
dependencies = [
43114311
"log",
43124312
"rustc_data_structures",
4313+
"rustc_errors",
43134314
"rustc_hir",
43144315
"rustc_infer",
43154316
"rustc_middle",

src/librustc_codegen_llvm/context.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -376,6 +376,7 @@ impl MiscMethods<'tcx> for CodegenCx<'ll, 'tcx> {
376376
def_id,
377377
tcx.intern_substs(&[]),
378378
)
379+
.unwrap()
379380
.unwrap(),
380381
),
381382
_ => {

src/librustc_codegen_ssa/base.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -468,6 +468,7 @@ pub fn maybe_create_entry_wrapper<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>>(
468468
start_def_id,
469469
cx.tcx().intern_substs(&[main_ret_ty.into()]),
470470
)
471+
.unwrap()
471472
.unwrap(),
472473
);
473474
(

src/librustc_codegen_ssa/mir/block.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -537,6 +537,7 @@ impl<'a, 'tcx, Bx: BuilderMethods<'a, 'tcx>> FunctionCx<'a, 'tcx, Bx> {
537537
ty::FnDef(def_id, substs) => (
538538
Some(
539539
ty::Instance::resolve(bx.tcx(), ty::ParamEnv::reveal_all(), def_id, substs)
540+
.unwrap()
540541
.unwrap(),
541542
),
542543
None,

src/librustc_middle/mir/interpret/queries.rs

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -39,12 +39,13 @@ impl<'tcx> TyCtxt<'tcx> {
3939
promoted: Option<mir::Promoted>,
4040
span: Option<Span>,
4141
) -> ConstEvalResult<'tcx> {
42-
let instance = ty::Instance::resolve(self, param_env, def_id, substs);
43-
if let Some(instance) = instance {
44-
let cid = GlobalId { instance, promoted };
45-
self.const_eval_global_id(param_env, cid, span)
46-
} else {
47-
Err(ErrorHandled::TooGeneric)
42+
match ty::Instance::resolve(self, param_env, def_id, substs) {
43+
Ok(Some(instance)) => {
44+
let cid = GlobalId { instance, promoted };
45+
self.const_eval_global_id(param_env, cid, span)
46+
}
47+
Ok(None) => Err(ErrorHandled::TooGeneric),
48+
Err(error_reported) => Err(ErrorHandled::Reported(error_reported)),
4849
}
4950
}
5051

src/librustc_middle/query/mod.rs

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -679,7 +679,7 @@ rustc_queries! {
679679
Codegen {
680680
query codegen_fulfill_obligation(
681681
key: (ty::ParamEnv<'tcx>, ty::PolyTraitRef<'tcx>)
682-
) -> Option<Vtable<'tcx, ()>> {
682+
) -> Result<Vtable<'tcx, ()>, ErrorReported> {
683683
cache_on_disk_if { true }
684684
desc { |tcx|
685685
"checking if `{}` fulfills its obligations",
@@ -1258,9 +1258,18 @@ rustc_queries! {
12581258
desc { "looking up enabled feature gates" }
12591259
}
12601260

1261+
/// Attempt to resolve the given `DefId` to an `Instance`, for the
1262+
/// given generics args (`SubstsRef`), returning one of:
1263+
/// * `Ok(Some(instance))` on success
1264+
/// * `Ok(None)` when the `SubstsRef` are still too generic,
1265+
/// and therefore don't allow finding the final `Instance`
1266+
/// * `Err(ErrorReported)` when the `Instance` resolution process
1267+
/// couldn't complete due to errors elsewhere - this is distinct
1268+
/// from `Ok(None)` to avoid misleading diagnostics when an error
1269+
/// has already been/will be emitted, for the original cause
12611270
query resolve_instance(
12621271
key: ty::ParamEnvAnd<'tcx, (DefId, SubstsRef<'tcx>)>
1263-
) -> Option<ty::Instance<'tcx>> {
1272+
) -> Result<Option<ty::Instance<'tcx>>, ErrorReported> {
12641273
desc { "resolving instance `{}`", ty::Instance::new(key.value.0, key.value.1) }
12651274
}
12661275
}

src/librustc_middle/ty/instance.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
use crate::middle::codegen_fn_attrs::CodegenFnAttrFlags;
22
use crate::ty::print::{FmtPrinter, Printer};
33
use crate::ty::{self, SubstsRef, Ty, TyCtxt, TypeFoldable};
4+
use rustc_errors::ErrorReported;
45
use rustc_hir::def::Namespace;
56
use rustc_hir::def_id::{CrateNum, DefId};
67
use rustc_hir::lang_items::DropInPlaceFnLangItem;
@@ -268,26 +269,31 @@ impl<'tcx> Instance<'tcx> {
268269
/// this is used to find the precise code that will run for a trait method invocation,
269270
/// if known.
270271
///
271-
/// Returns `None` if we cannot resolve `Instance` to a specific instance.
272+
/// Returns `Ok(None)` if we cannot resolve `Instance` to a specific instance.
272273
/// For example, in a context like this,
273274
///
274275
/// ```
275276
/// fn foo<T: Debug>(t: T) { ... }
276277
/// ```
277278
///
278-
/// trying to resolve `Debug::fmt` applied to `T` will yield `None`, because we do not
279+
/// trying to resolve `Debug::fmt` applied to `T` will yield `Ok(None)`, because we do not
279280
/// know what code ought to run. (Note that this setting is also affected by the
280281
/// `RevealMode` in the parameter environment.)
281282
///
282283
/// Presuming that coherence and type-check have succeeded, if this method is invoked
283284
/// in a monomorphic context (i.e., like during codegen), then it is guaranteed to return
284-
/// `Some`.
285+
/// `Ok(Some(instance))`.
286+
///
287+
/// Returns `Err(ErrorReported)` when the `Instance` resolution process
288+
/// couldn't complete due to errors elsewhere - this is distinct
289+
/// from `Ok(None)` to avoid misleading diagnostics when an error
290+
/// has already been/will be emitted, for the original cause
285291
pub fn resolve(
286292
tcx: TyCtxt<'tcx>,
287293
param_env: ty::ParamEnv<'tcx>,
288294
def_id: DefId,
289295
substs: SubstsRef<'tcx>,
290-
) -> Option<Instance<'tcx>> {
296+
) -> Result<Option<Instance<'tcx>>, ErrorReported> {
291297
// All regions in the result of this query are erased, so it's
292298
// fine to erase all of the input regions.
293299

@@ -307,7 +313,7 @@ impl<'tcx> Instance<'tcx> {
307313
substs: SubstsRef<'tcx>,
308314
) -> Option<Instance<'tcx>> {
309315
debug!("resolve(def_id={:?}, substs={:?})", def_id, substs);
310-
Instance::resolve(tcx, param_env, def_id, substs).map(|mut resolved| {
316+
Instance::resolve(tcx, param_env, def_id, substs).ok().flatten().map(|mut resolved| {
311317
match resolved.def {
312318
InstanceDef::Item(def_id) if resolved.def.requires_caller_location(tcx) => {
313319
debug!(" => fn pointer created for function with #[track_caller]");
@@ -339,7 +345,7 @@ impl<'tcx> Instance<'tcx> {
339345
debug!(" => associated item with unsizeable self: Self");
340346
Some(Instance { def: InstanceDef::VtableShim(def_id), substs })
341347
} else {
342-
Instance::resolve(tcx, param_env, def_id, substs)
348+
Instance::resolve(tcx, param_env, def_id, substs).ok().flatten()
343349
}
344350
}
345351

@@ -360,7 +366,7 @@ impl<'tcx> Instance<'tcx> {
360366
pub fn resolve_drop_in_place(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> ty::Instance<'tcx> {
361367
let def_id = tcx.require_lang_item(DropInPlaceFnLangItem, None);
362368
let substs = tcx.intern_substs(&[ty.into()]);
363-
Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap()
369+
Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap().unwrap()
364370
}
365371

366372
pub fn fn_once_adapter_instance(

src/librustc_mir/interpret/eval_context.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -453,8 +453,13 @@ impl<'mir, 'tcx, M: Machine<'mir, 'tcx>> InterpCx<'mir, 'tcx, M> {
453453
trace!("resolve: {:?}, {:#?}", def_id, substs);
454454
trace!("param_env: {:#?}", self.param_env);
455455
trace!("substs: {:#?}", substs);
456-
ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs)
457-
.ok_or_else(|| err_inval!(TooGeneric).into())
456+
match ty::Instance::resolve(*self.tcx, self.param_env, def_id, substs) {
457+
Ok(Some(instance)) => Ok(instance),
458+
Ok(None) => throw_inval!(TooGeneric),
459+
460+
// FIXME(eddyb) this could be a bit more specific than `TypeckError`.
461+
Err(error_reported) => throw_inval!(TypeckError(error_reported)),
462+
}
458463
}
459464

460465
pub fn layout_of_local(

src/librustc_mir/monomorphize/collector.rs

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -674,9 +674,12 @@ fn visit_fn_use<'tcx>(
674674
output: &mut Vec<MonoItem<'tcx>>,
675675
) {
676676
if let ty::FnDef(def_id, substs) = ty.kind {
677-
let resolver =
678-
if is_direct_call { ty::Instance::resolve } else { ty::Instance::resolve_for_fn_ptr };
679-
let instance = resolver(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap();
677+
let instance = if is_direct_call {
678+
ty::Instance::resolve(tcx, ty::ParamEnv::reveal_all(), def_id, substs).unwrap().unwrap()
679+
} else {
680+
ty::Instance::resolve_for_fn_ptr(tcx, ty::ParamEnv::reveal_all(), def_id, substs)
681+
.unwrap()
682+
};
680683
visit_instance_use(tcx, instance, is_direct_call, output);
681684
}
682685
}
@@ -1057,6 +1060,7 @@ impl RootCollector<'_, 'v> {
10571060
start_def_id,
10581061
self.tcx.intern_substs(&[main_ret_ty.into()]),
10591062
)
1063+
.unwrap()
10601064
.unwrap();
10611065

10621066
self.output.push(create_fn_mono_item(start_instance));
@@ -1112,8 +1116,9 @@ fn create_mono_items_for_default_impls<'tcx>(
11121116
trait_ref.substs[param.index as usize]
11131117
}
11141118
});
1115-
let instance =
1116-
ty::Instance::resolve(tcx, param_env, method.def_id, substs).unwrap();
1119+
let instance = ty::Instance::resolve(tcx, param_env, method.def_id, substs)
1120+
.unwrap()
1121+
.unwrap();
11171122

11181123
let mono_item = create_fn_mono_item(instance);
11191124
if mono_item.is_instantiable(tcx) && should_monomorphize_locally(tcx, &instance)

src/librustc_mir/monomorphize/mod.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ pub fn custom_coerce_unsize_info<'tcx>(
1818
});
1919

2020
match tcx.codegen_fulfill_obligation((ty::ParamEnv::reveal_all(), trait_ref)) {
21-
Some(traits::VtableImpl(traits::VtableImplData { impl_def_id, .. })) => {
21+
Ok(traits::VtableImpl(traits::VtableImplData { impl_def_id, .. })) => {
2222
tcx.coerce_unsized_info(impl_def_id).custom_kind.unwrap()
2323
}
2424
vtable => {

0 commit comments

Comments
 (0)