Skip to content
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

Handle associated types in const context #70056

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
15 changes: 15 additions & 0 deletions src/librustc/query/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,19 @@ rustc_queries! {
desc { |tcx| "type-checking `{}`", tcx.def_path_str(key) }
cache_on_disk_if { key.is_local() }
}

query const_typeck_tables_of(key: DefId) -> &'tcx ty::TypeckTables<'tcx> {
desc { |tcx| "type-checking `{}`", tcx.def_path_str(key) }
cache_on_disk_if { key.is_local() }
load_cached(tcx, id) {
let typeck_tables: Option<ty::TypeckTables<'tcx>> = tcx
.queries.on_disk_cache
.try_load_query_result(tcx, id);

typeck_tables.map(|tables| &*tcx.arena.alloc(tables))
}
}

query diagnostic_only_typeck_tables_of(key: DefId) -> &'tcx ty::TypeckTables<'tcx> {
cache_on_disk_if { key.is_local() }
load_cached(tcx, id) {
Expand All @@ -458,6 +471,8 @@ rustc_queries! {
TypeChecking {
query has_typeck_tables(_: DefId) -> bool {}

query const_has_typeck_tables(_: DefId) -> bool {}

query coherent_trait(def_id: DefId) -> () {
desc { |tcx| "coherence checking all impls of trait `{}`", tcx.def_path_str(def_id) }
}
Expand Down
5 changes: 5 additions & 0 deletions src/librustc_infer/infer/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,10 @@ pub struct InferCtxt<'a, 'tcx> {
/// This flag is true while there is an active snapshot.
in_snapshot: Cell<bool>,

/// This flag is `true` if the current scope is in a `const` context,
/// like in an array length. Used exclusively to improve diagnostics.
pub in_const_context: Cell<bool>,

/// What is the innermost universe we have created? Starts out as
/// `UniverseIndex::root()` but grows from there as we enter
/// universal quantifiers.
Expand Down Expand Up @@ -584,6 +588,7 @@ impl<'tcx> InferCtxtBuilder<'tcx> {
tainted_by_errors_flag: Cell::new(false),
err_count_on_creation: tcx.sess.err_count(),
in_snapshot: Cell::new(false),
in_const_context: Cell::new(false),
skip_leak_check: Cell::new(false),
universe: Cell::new(ty::UniverseIndex::ROOT),
})
Expand Down
4 changes: 2 additions & 2 deletions src/librustc_mir/const_eval/eval_queries.rs
Original file line number Diff line number Diff line change
Expand Up @@ -290,8 +290,8 @@ pub fn const_eval_raw_provider<'tcx>(
let def_id = cid.instance.def.def_id();

if def_id.is_local()
&& tcx.has_typeck_tables(def_id)
&& tcx.typeck_tables_of(def_id).tainted_by_errors
&& tcx.const_has_typeck_tables(def_id)
&& tcx.const_typeck_tables_of(def_id).tainted_by_errors
{
return Err(ErrorHandled::Reported);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,12 @@ impl<'a, 'tcx> InferCtxtExt<'tcx> for InferCtxt<'a, 'tcx> {
ty::Projection(projection) => (false, Some(projection)),
_ => return,
};
if self.in_const_context.get() {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is weirdly specific given that anything involving type parameters doesn't work.

Copy link
Contributor Author

@estebank estebank Mar 16, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a very common thing people encounter when trying to be too clever by half. I'm looking for other cases that are likely to be hit so that I can also handle them. One case I'm looking at now is the following, which ICEs

fn test<T: ?Sized>() {
    [0u8; std::mem::size_of::<&T>()];
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should fix generics_of if the parent of AnonConst is an Expr (and probably any Ty nested in a body, but that's harder to check), I think I've suggested that before. It should just work, the query cycles only come from types outside bodies.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

And by "fix" I mean a trivial whitelist, much smaller than this PR.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

CC #70452

err.note(
"associated types can't be referenced in `const` contexts, like array in length",
estebank marked this conversation as resolved.
Show resolved Hide resolved
);
return;
}

let suggest_restriction =
|generics: &hir::Generics<'_>, msg, err: &mut DiagnosticBuilder<'_>| {
Expand Down
52 changes: 46 additions & 6 deletions src/librustc_typeck/check/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -753,7 +753,12 @@ fn check_mod_item_types(tcx: TyCtxt<'_>, module_def_id: DefId) {
fn typeck_item_bodies(tcx: TyCtxt<'_>, crate_num: CrateNum) {
debug_assert!(crate_num == LOCAL_CRATE);
tcx.par_body_owners(|body_owner_def_id| {
tcx.ensure().typeck_tables_of(body_owner_def_id);
if let Some(hir::Node::AnonConst(_)) = tcx.hir().get_if_local(body_owner_def_id) {
// We don't want to incorrectly suggest constraining type parameters for array lengths.
tcx.ensure().const_typeck_tables_of(body_owner_def_id);
} else {
tcx.ensure().typeck_tables_of(body_owner_def_id);
}
estebank marked this conversation as resolved.
Show resolved Hide resolved
});
}

Expand All @@ -774,8 +779,10 @@ pub fn provide(providers: &mut Providers<'_>) {
*providers = Providers {
typeck_item_bodies,
typeck_tables_of,
const_typeck_tables_of,
diagnostic_only_typeck_tables_of,
has_typeck_tables,
const_has_typeck_tables,
adt_destructor,
used_trait_imports,
check_item_well_formed,
Expand Down Expand Up @@ -834,11 +841,23 @@ fn primary_body_of(
}

fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
has_typeck_tables_inner(tcx, def_id, false)
}

fn const_has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
has_typeck_tables_inner(tcx, def_id, true)
}

fn has_typeck_tables_inner(tcx: TyCtxt<'_>, def_id: DefId, in_const_context: bool) -> bool {
// Closures' tables come from their outermost function,
// as they are part of the same "inference environment".
let outer_def_id = tcx.closure_base_def_id(def_id);
if outer_def_id != def_id {
return tcx.has_typeck_tables(outer_def_id);
if in_const_context {
return tcx.const_has_typeck_tables(outer_def_id);
} else {
return tcx.has_typeck_tables(outer_def_id);
}
}

if let Some(id) = tcx.hir().as_local_hir_id(def_id) {
Expand All @@ -849,7 +868,13 @@ fn has_typeck_tables(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
}

fn used_trait_imports(tcx: TyCtxt<'_>, def_id: DefId) -> &DefIdSet {
&*tcx.typeck_tables_of(def_id).used_trait_imports
&*if let Some(hir::Node::AnonConst(_)) = tcx.hir().get_if_local(def_id) {
// We don't want to incorrectly suggest constraining type parameters for array lengths.
tcx.const_typeck_tables_of(def_id)
} else {
tcx.typeck_tables_of(def_id)
}
.used_trait_imports
}

/// Inspects the substs of opaque types, replacing any inference variables
Expand Down Expand Up @@ -965,7 +990,14 @@ where

fn typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &ty::TypeckTables<'tcx> {
let fallback = move || tcx.type_of(def_id);
typeck_tables_of_with_fallback(tcx, def_id, fallback)
typeck_tables_of_with_fallback(tcx, def_id, fallback, false)
}

/// Used only to improve diagnostics when trying to access associated item in a const context.
/// The most common case is trying to use an associated item to set the length of an array.
fn const_typeck_tables_of<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId) -> &ty::TypeckTables<'tcx> {
let fallback = move || tcx.type_of(def_id);
typeck_tables_of_with_fallback(tcx, def_id, fallback, true)
}

/// Used only to get `TypeckTables` for type inference during error recovery.
Expand All @@ -980,19 +1012,24 @@ fn diagnostic_only_typeck_tables_of<'tcx>(
tcx.sess.delay_span_bug(span, "diagnostic only typeck table used");
tcx.types.err
};
typeck_tables_of_with_fallback(tcx, def_id, fallback)
typeck_tables_of_with_fallback(tcx, def_id, fallback, false)
}

fn typeck_tables_of_with_fallback<'tcx>(
tcx: TyCtxt<'tcx>,
def_id: DefId,
fallback: impl Fn() -> Ty<'tcx> + 'tcx,
in_const_context: bool,
) -> &'tcx ty::TypeckTables<'tcx> {
// Closures' tables come from their outermost function,
// as they are part of the same "inference environment".
let outer_def_id = tcx.closure_base_def_id(def_id);
if outer_def_id != def_id {
return tcx.typeck_tables_of(outer_def_id);
if in_const_context {
return tcx.const_typeck_tables_of(outer_def_id);
} else {
return tcx.typeck_tables_of(outer_def_id);
}
}

let id = tcx.hir().as_local_hir_id(def_id).unwrap();
Expand All @@ -1005,6 +1042,8 @@ fn typeck_tables_of_with_fallback<'tcx>(
let body = tcx.hir().body(body_id);

let tables = Inherited::build(tcx, def_id).enter(|inh| {
let in_const = inh.in_const_context.get();
inh.in_const_context.set(in_const_context);
estebank marked this conversation as resolved.
Show resolved Hide resolved
let param_env = tcx.param_env(def_id);
let fcx = if let (Some(header), Some(decl)) = (fn_header, fn_decl) {
let fn_sig = if crate::collect::get_infer_ret_ty(&decl.output).is_some() {
Expand Down Expand Up @@ -1124,6 +1163,7 @@ fn typeck_tables_of_with_fallback<'tcx>(
fcx.regionck_expr(body);
}

inh.in_const_context.set(in_const);
fcx.resolve_type_vars_in_body(body)
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ LL | const Y: usize;
LL | let _array = [4; <A as Foo>::Y];
| ^^^^^^^^^^^^^ the trait `Foo` is not implemented for `A`
|
help: consider further restricting this bound with `+ Foo`
--> $DIR/associated-const-type-parameter-arrays-2.rs:15:16
|
LL | pub fn test<A: Foo, B: Foo>() {
| ^^^
= note: associated types can't be referenced in `const` contexts, like array in length

error: aborting due to previous error

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,7 @@ LL | const Y: usize;
LL | let _array: [u32; <A as Foo>::Y];
| ^^^^^^^^^^^^^ the trait `Foo` is not implemented for `A`
|
help: consider further restricting this bound with `+ Foo`
--> $DIR/associated-const-type-parameter-arrays.rs:15:16
|
LL | pub fn test<A: Foo, B: Foo>() {
| ^^^
= note: associated types can't be referenced in `const` contexts, like array in length

error: aborting due to previous error

Expand Down
1 change: 1 addition & 0 deletions src/test/ui/closures/issue-52437.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,5 @@ fn main() {
//~^ ERROR: invalid label name `'static`
//~| ERROR: `loop` is not allowed in a `const`
//~| ERROR: type annotations needed
//~| ERROR: type annotations needed
}
8 changes: 7 additions & 1 deletion src/test/ui/closures/issue-52437.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,13 @@ error[E0282]: type annotations needed
LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]
| ^ consider giving this closure parameter a type

error: aborting due to 3 previous errors
error[E0282]: type annotations needed
--> $DIR/issue-52437.rs:2:30
|
LL | [(); &(&'static: loop { |x| {}; }) as *const _ as usize]
| ^ consider giving this closure parameter a type

error: aborting due to 4 previous errors

Some errors have detailed explanations: E0282, E0658.
For more information about an error, try `rustc --explain E0282`.
27 changes: 18 additions & 9 deletions src/test/ui/consts/const-integer-bool-ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ const X: usize = 42 && 39;
//~| expected `bool`, found integer
//~| ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
//~| ERROR mismatched types
//~| ERROR mismatched types
const ARR: [i32; X] = [99; 34];
//~^ ERROR evaluation of constant value failed

Expand All @@ -15,6 +18,9 @@ const X1: usize = 42 || 39;
//~| expected `bool`, found integer
//~| ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
//~| ERROR mismatched types
//~| ERROR mismatched types
const ARR1: [i32; X1] = [99; 47];
//~^ ERROR evaluation of constant value failed

Expand All @@ -25,52 +31,55 @@ const X2: usize = -42 || -39;
//~| expected `bool`, found integer
//~| ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
//~| ERROR mismatched types
//~| ERROR mismatched types
const ARR2: [i32; X2] = [99; 18446744073709551607];
//~^ ERROR evaluation of constant value failed

const X3: usize = -42 && -39;
//~^ ERROR mismatched types
//~| expected `bool`, found integer
//~| ERROR mismatched types
//~| expected `bool`, found integer
//~| ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
//~| ERROR mismatched types
//~| ERROR mismatched types
const ARR3: [i32; X3] = [99; 6];
//~^ ERROR evaluation of constant value failed

const Y: usize = 42.0 == 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR: [i32; Y] = [99; 1];
//~^ ERROR evaluation of constant value failed

const Y1: usize = 42.0 >= 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR1: [i32; Y1] = [99; 1];
//~^ ERROR evaluation of constant value failed

const Y2: usize = 42.0 <= 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR2: [i32; Y2] = [99; 1];
//~^ ERROR evaluation of constant value failed

const Y3: usize = 42.0 > 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR3: [i32; Y3] = [99; 0];
//~^ ERROR evaluation of constant value failed

const Y4: usize = 42.0 < 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR4: [i32; Y4] = [99; 0];
//~^ ERROR evaluation of constant value failed

const Y5: usize = 42.0 != 42.0;
//~^ ERROR mismatched types
//~| expected `usize`, found `bool`
//~| ERROR mismatched types
const ARRR5: [i32; Y5] = [99; 0];
//~^ ERROR evaluation of constant value failed

Expand Down
Loading