rust/compiler/rustc_typeck/src/lib.rs

459 lines
16 KiB
Rust
Raw Normal View History

2014-11-26 12:11:29 +01:00
/*!
2012-11-29 01:20:41 +01:00
2019-02-08 14:53:55 +01:00
# typeck
2012-11-29 01:20:41 +01:00
The type checker is responsible for:
1. Determining the type of each expression.
2. Resolving methods and traits.
3. Guaranteeing that most type rules are met. ("Most?", you say, "why most?"
Well, dear reader, read on.)
2012-11-29 01:20:41 +01:00
The main entry point is [`check_crate()`]. Type checking operates in
several major phases:
2012-11-29 01:20:41 +01:00
1. The collect phase first passes over all items and determines their
type, without examining their "innards".
2. Variance inference then runs to compute the variance of each parameter.
3. Coherence checks for overlapping or orphaned impls.
4. Finally, the check phase then checks function bodies and so forth.
Within the check phase, we check each function body one at a time
(bodies of function expressions are checked as part of the
containing function). Inference is used to supply types wherever
they are unknown. The actual checking of a function itself has
several phases (check, regionck, writeback), as discussed in the
documentation for the [`check`] module.
2012-11-29 01:20:41 +01:00
The type checker is defined into various submodules which are documented
independently:
- astconv: converts the AST representation of types
into the `ty` representation.
2012-11-29 01:20:41 +01:00
- collect: computes the types of each top-level item and enters them into
the `tcx.types` table for later use.
2012-11-29 01:20:41 +01:00
- coherence: enforces coherence rules, builds some tables.
- variance: variance inference
- outlives: outlives inference
2012-11-29 01:20:41 +01:00
- check: walks over function bodies and type checks them, inferring types for
local variables, type parameters, etc as necessary.
- infer: finds the types to use for each type variable such that
all subtyping and assignment constraints are met. In essence, the check
module specifies the constraints, and the infer module solves them.
## Note
2014-11-26 12:11:29 +01:00
This API is completely unstable and subject to change.
2012-11-29 01:20:41 +01:00
*/
2020-09-23 21:51:56 +02:00
#![doc(html_root_url = "https://doc.rust-lang.org/nightly/nightly-rustc/")]
2021-02-09 09:57:42 +01:00
#![feature(bindings_after_at)]
2019-10-08 02:14:42 +02:00
#![feature(bool_to_option)]
#![feature(box_syntax)]
#![feature(crate_visibility_modifier)]
#![feature(format_args_capture)]
#![feature(in_band_lifetimes)]
#![feature(is_sorted)]
#![feature(nll)]
#![feature(or_patterns)]
2019-12-30 11:39:13 +01:00
#![feature(try_blocks)]
#![feature(never_type)]
#![feature(slice_partition_dedup)]
#![feature(control_flow_enum)]
2019-12-22 23:42:04 +01:00
#![recursion_limit = "256"]
2019-12-22 23:42:04 +01:00
#[macro_use]
2020-08-14 08:05:01 +02:00
extern crate tracing;
2019-12-22 23:42:04 +01:00
#[macro_use]
2020-03-29 16:41:09 +02:00
extern crate rustc_middle;
2014-11-26 12:11:29 +01:00
2020-08-03 02:19:33 +02:00
// These are used by Clippy.
pub mod check;
pub mod expr_use_visitor;
mod astconv;
mod bounds;
mod check_unused;
mod coherence;
mod collect;
mod constrained_generic_params;
mod errors;
mod impl_wf_check;
mod mem_categorization;
mod outlives;
2019-12-22 23:42:04 +01:00
mod structured_errors;
mod variance;
2020-03-31 21:18:30 +02:00
use rustc_errors::{struct_span_err, ErrorReported};
use rustc_hir as hir;
use rustc_hir::def_id::{LocalDefId, LOCAL_CRATE};
use rustc_hir::Node;
2020-01-06 23:12:31 +01:00
use rustc_infer::infer::{InferOk, TyCtxtInferExt};
2020-02-11 21:19:40 +01:00
use rustc_infer::traits::TraitEngineExt as _;
2020-03-29 16:41:09 +02:00
use rustc_middle::middle;
use rustc_middle::ty::query::Providers;
use rustc_middle::ty::{self, Ty, TyCtxt};
use rustc_middle::util;
use rustc_session::config::EntryFnType;
2020-08-04 07:30:04 +02:00
use rustc_span::{symbol::sym, Span, DUMMY_SP};
2019-12-22 23:42:04 +01:00
use rustc_target::spec::abi::Abi;
2020-02-11 21:19:40 +01:00
use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
use rustc_trait_selection::traits::{
ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt as _,
};
use std::iter;
use astconv::AstConv;
use bounds::Bounds;
2014-05-06 15:52:04 +02:00
2019-12-01 16:08:58 +01:00
fn require_c_abi_if_c_variadic(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: Abi, span: Span) {
rustc_target: add "unwind" payloads to `Abi` ### Overview This commit begins the implementation work for RFC 2945. For more information, see the rendered RFC [1] and tracking issue [2]. A boolean `unwind` payload is added to the `C`, `System`, `Stdcall`, and `Thiscall` variants, marking whether unwinding across FFI boundaries is acceptable. The cases where each of these variants' `unwind` member is true correspond with the `C-unwind`, `system-unwind`, `stdcall-unwind`, and `thiscall-unwind` ABI strings introduced in RFC 2945 [3]. ### Feature Gate and Unstable Book This commit adds a `c_unwind` feature gate for the new ABI strings. Tests for this feature gate are included in `src/test/ui/c-unwind/`, which ensure that this feature gate works correctly for each of the new ABIs. A new language features entry in the unstable book is added as well. ### Further Work To Be Done This commit does not proceed to implement the new unwinding ABIs, and is intentionally scoped specifically to *defining* the ABIs and their feature flag. ### One Note on Test Churn This will lead to some test churn, in re-blessing hash tests, as the deleted comment in `src/librustc_target/spec/abi.rs` mentioned, because we can no longer guarantee the ordering of the `Abi` variants. While this is a downside, this decision was made bearing in mind that RFC 2945 states the following, in the "Other `unwind` Strings" section [3]: > More unwind variants of existing ABI strings may be introduced, > with the same semantics, without an additional RFC. Adding a new variant for each of these cases, rather than specifying a payload for a given ABI, would quickly become untenable, and make working with the `Abi` enum prone to mistakes. This approach encodes the unwinding information *into* a given ABI, to account for the future possibility of other `-unwind` ABI strings. ### Ignore Directives `ignore-*` directives are used in two of our `*-unwind` ABI test cases. Specifically, the `stdcall-unwind` and `thiscall-unwind` test cases ignore architectures that do not support `stdcall` and `thiscall`, respectively. These directives are cribbed from `src/test/ui/c-variadic/variadic-ffi-1.rs` for `stdcall`, and `src/test/ui/extern/extern-thiscall.rs` for `thiscall`. This would otherwise fail on some targets, see: https://github.com/rust-lang-ci/rust/commit/fcf697f90206e9c87b39d494f94ab35d976bfc60 ### Footnotes [1]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md [2]: https://github.com/rust-lang/rust/issues/74990 [3]: https://github.com/rust-lang/rfcs/blob/master/text/2945-c-unwind-abi.md#other-unwind-abi-strings
2020-08-27 17:49:18 +02:00
match (decl.c_variadic, abi) {
// The function has the correct calling convention, or isn't a "C-variadic" function.
(false, _) | (true, Abi::C { .. }) | (true, Abi::Cdecl) => {}
// The function is a "C-variadic" function with an incorrect calling convention.
(true, _) => {
let mut err = struct_span_err!(
tcx.sess,
span,
E0045,
"C-variadic function must have C or cdecl calling convention"
);
err.span_label(span, "C-variadics require C or cdecl calling convention").emit();
}
}
}
fn require_same_types<'tcx>(
2019-06-13 23:48:52 +02:00
tcx: TyCtxt<'tcx>,
cause: &ObligationCause<'tcx>,
expected: Ty<'tcx>,
actual: Ty<'tcx>,
) -> bool {
tcx.infer_ctxt().enter(|ref infcx| {
let param_env = ty::ParamEnv::empty();
let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
match infcx.at(&cause, param_env).eq(expected, actual) {
Ok(InferOk { obligations, .. }) => {
fulfill_cx.register_predicate_obligations(infcx, obligations);
}
Err(err) => {
infcx.report_mismatched_types(cause, expected, actual, err).emit();
return false;
}
}
match fulfill_cx.select_all_or_error(infcx) {
Ok(()) => true,
Err(errors) => {
infcx.report_fulfillment_errors(&errors, None, false);
false
}
2012-11-29 01:20:41 +01:00
}
})
2012-11-29 01:20:41 +01:00
}
fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: LocalDefId) {
let main_id = tcx.hir().local_def_id_to_hir_id(main_def_id);
2019-01-13 13:06:26 +01:00
let main_span = tcx.def_span(main_def_id);
let main_t = tcx.type_of(main_def_id);
2020-08-03 00:49:11 +02:00
match main_t.kind() {
ty::FnDef(..) => {
2019-06-24 09:58:49 +02:00
if let Some(Node::Item(it)) = tcx.hir().find(main_id) {
if let hir::ItemKind::Fn(ref sig, ref generics, _) = it.kind {
let mut error = false;
if !generics.params.is_empty() {
let msg = "`main` function is not allowed to have generic \
2019-12-22 23:42:04 +01:00
parameters"
.to_owned();
let label = "`main` cannot have generic parameters".to_string();
struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg)
.span_label(generics.span, label)
.emit();
error = true;
}
if let Some(sp) = generics.where_clause.span() {
2019-12-22 23:42:04 +01:00
struct_span_err!(
tcx.sess,
sp,
E0646,
"`main` function is not allowed to have a `where` clause"
)
.span_label(sp, "`main` cannot have a `where` clause")
.emit();
error = true;
}
if let hir::IsAsync::Async = sig.header.asyncness {
let span = tcx.sess.source_map().guess_head_span(it.span);
struct_span_err!(
tcx.sess,
span,
E0752,
"`main` function is not allowed to be `async`"
)
.span_label(span, "`main` function is not allowed to be `async`")
.emit();
error = true;
}
2020-08-04 07:30:04 +02:00
2021-01-24 13:17:54 +01:00
let attrs = tcx.hir().attrs(main_id);
for attr in attrs {
if tcx.sess.check_name(attr, sym::track_caller) {
2020-08-04 07:30:04 +02:00
tcx.sess
.struct_span_err(
attr.span,
"`main` function is not allowed to be `#[track_caller]`",
)
.span_label(
main_span,
"`main` function is not allowed to be `#[track_caller]`",
)
.emit();
error = true;
}
}
if error {
return;
2012-11-29 01:20:41 +01:00
}
}
}
2017-12-21 13:07:50 +01:00
let actual = tcx.fn_sig(main_def_id);
let expected_return_type = if tcx.lang_items().termination().is_some() {
// we take the return type of the given main function, the real check is done
// in `check_fn`
2020-12-17 04:36:14 +01:00
actual.output()
} else {
// standard () main return type
2020-12-17 04:36:14 +01:00
ty::Binder::dummy(tcx.mk_unit())
};
2017-12-21 13:07:50 +01:00
2020-12-17 04:36:14 +01:00
let se_ty = tcx.mk_fn_ptr(expected_return_type.map_bound(|expected_return_type| {
tcx.mk_fn_sig(
iter::empty(),
expected_return_type,
false,
hir::Unsafety::Normal,
Abi::Rust,
)
}));
2017-12-21 13:07:50 +01:00
require_same_types(
tcx,
&ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
se_ty,
2019-12-22 23:42:04 +01:00
tcx.mk_fn_ptr(actual),
);
2012-11-29 01:20:41 +01:00
}
_ => {
2019-12-22 23:42:04 +01:00
span_bug!(main_span, "main has a non-function type: found `{}`", main_t);
2012-11-29 01:20:41 +01:00
}
}
}
fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: LocalDefId) {
let start_id = tcx.hir().local_def_id_to_hir_id(start_def_id);
2019-01-13 13:06:26 +01:00
let start_span = tcx.def_span(start_def_id);
let start_t = tcx.type_of(start_def_id);
2020-08-03 00:49:11 +02:00
match start_t.kind() {
ty::FnDef(..) => {
2019-06-24 09:58:49 +02:00
if let Some(Node::Item(it)) = tcx.hir().find(start_id) {
if let hir::ItemKind::Fn(ref sig, ref generics, _) = it.kind {
let mut error = false;
if !generics.params.is_empty() {
2019-12-22 23:42:04 +01:00
struct_span_err!(
tcx.sess,
generics.span,
E0132,
"start function is not allowed to have type parameters"
)
.span_label(generics.span, "start function cannot have type parameters")
.emit();
error = true;
}
if let Some(sp) = generics.where_clause.span() {
2019-12-22 23:42:04 +01:00
struct_span_err!(
tcx.sess,
sp,
E0647,
"start function is not allowed to have a `where` clause"
)
.span_label(sp, "start function cannot have a `where` clause")
.emit();
error = true;
}
if let hir::IsAsync::Async = sig.header.asyncness {
let span = tcx.sess.source_map().guess_head_span(it.span);
struct_span_err!(
tcx.sess,
span,
E0752,
2020-08-04 21:36:21 +02:00
"`start` is not allowed to be `async`"
)
2020-08-04 21:36:21 +02:00
.span_label(span, "`start` is not allowed to be `async`")
.emit();
error = true;
}
2020-08-04 07:30:04 +02:00
2021-01-24 13:17:54 +01:00
let attrs = tcx.hir().attrs(start_id);
for attr in attrs {
if tcx.sess.check_name(attr, sym::track_caller) {
2020-08-04 07:30:04 +02:00
tcx.sess
.struct_span_err(
attr.span,
2020-08-04 21:36:21 +02:00
"`start` is not allowed to be `#[track_caller]`",
2020-08-04 07:30:04 +02:00
)
.span_label(
start_span,
2020-08-04 21:36:21 +02:00
"`start` is not allowed to be `#[track_caller]`",
2020-08-04 07:30:04 +02:00
)
.emit();
error = true;
}
}
if error {
return;
}
}
}
let se_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
2019-12-22 23:42:04 +01:00
[tcx.types.isize, tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))].iter().cloned(),
tcx.types.isize,
false,
hir::Unsafety::Normal,
Abi::Rust,
)));
2016-07-16 18:38:17 +02:00
require_same_types(
tcx,
&ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
se_ty,
2019-12-22 23:42:04 +01:00
tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)),
);
}
_ => {
2019-12-22 23:42:04 +01:00
span_bug!(start_span, "start has a non-function type: found `{}`", start_t);
}
}
}
2019-06-21 23:49:03 +02:00
fn check_for_entry_fn(tcx: TyCtxt<'_>) {
2019-01-13 13:06:26 +01:00
match tcx.entry_fn(LOCAL_CRATE) {
Some((def_id, EntryFnType::Main)) => check_main_fn_ty(tcx, def_id),
Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id),
2019-01-13 13:06:26 +01:00
_ => {}
2012-11-29 01:20:41 +01:00
}
}
pub fn provide(providers: &mut Providers) {
collect::provide(providers);
coherence::provide(providers);
check::provide(providers);
variance::provide(providers);
outlives::provide(providers);
2019-01-26 12:18:32 +01:00
impl_wf_check::provide(providers);
}
2019-06-21 23:49:03 +02:00
pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorReported> {
let _prof_timer = tcx.sess.timer("type_check_crate");
2018-05-19 19:50:58 +02:00
// this ensures that later parts of type checking can assume that items
// have valid types and not error
// FIXME(matthewjasper) We shouldn't need to use `track_errors`.
tcx.sess.track_errors(|| {
tcx.sess.time("type_collecting", || {
2019-02-23 19:18:14 +01:00
for &module in tcx.hir().krate().modules.keys() {
2021-01-31 17:58:57 +01:00
tcx.ensure().collect_mod_item_types(module);
2019-02-23 19:18:14 +01:00
}
});
})?;
2019-01-26 15:26:49 +01:00
if tcx.features().rustc_attrs {
tcx.sess.track_errors(|| {
tcx.sess.time("outlives_testing", || outlives::test::test_inferred_outlives(tcx));
2019-01-26 15:26:49 +01:00
})?;
}
tcx.sess.track_errors(|| {
tcx.sess.time("impl_wf_inference", || impl_wf_check::impl_wf_check(tcx));
})?;
tcx.sess.track_errors(|| {
tcx.sess.time("coherence_checking", || coherence::check_coherence(tcx));
})?;
2013-03-21 11:28:58 +01:00
2019-01-26 15:26:49 +01:00
if tcx.features().rustc_attrs {
tcx.sess.track_errors(|| {
tcx.sess.time("variance_testing", || variance::test::test_variance(tcx));
2019-01-26 15:26:49 +01:00
})?;
}
2019-06-22 13:46:48 +02:00
tcx.sess.track_errors(|| {
tcx.sess.time("wf_checking", || check::check_wf_new(tcx));
2019-06-22 13:46:48 +02:00
})?;
// NOTE: This is copy/pasted in librustdoc/core.rs and should be kept in sync.
tcx.sess.time("item_types_checking", || {
for &module in tcx.hir().krate().modules.keys() {
2021-01-31 17:58:57 +01:00
tcx.ensure().check_mod_item_types(module);
}
});
2013-03-21 11:28:58 +01:00
tcx.sess.time("item_bodies_checking", || tcx.typeck_item_bodies(LOCAL_CRATE));
2016-04-19 15:43:10 +02:00
check_unused::check_crate(tcx);
check_for_entry_fn(tcx);
2019-12-22 23:42:04 +01:00
if tcx.sess.err_count() == 0 { Ok(()) } else { Err(ErrorReported) }
2012-11-29 01:20:41 +01:00
}
/// A quasi-deprecated helper used in rustdoc and clippy to get
/// the type from a HIR node.
2019-12-01 16:08:58 +01:00
pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
// In case there are any projections, etc., find the "environment"
// def-ID that will be used to determine the traits/predicates in
// scope. This is derived from the enclosing item-like thing.
let env_node_id = tcx.hir().get_parent_item(hir_ty.hir_id);
let env_def_id = tcx.hir().local_def_id(env_node_id);
let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.to_def_id());
2021-02-10 02:05:18 +01:00
item_cx.to_ty(hir_ty)
2017-11-18 16:49:37 +01:00
}
2019-12-01 16:08:58 +01:00
pub fn hir_trait_to_predicates<'tcx>(
tcx: TyCtxt<'tcx>,
hir_trait: &hir::TraitRef<'_>,
2020-04-07 02:03:54 +02:00
self_ty: Ty<'tcx>,
2019-12-01 16:08:58 +01:00
) -> Bounds<'tcx> {
// In case there are any projections, etc., find the "environment"
// def-ID that will be used to determine the traits/predicates in
2017-11-18 16:49:37 +01:00
// scope. This is derived from the enclosing item-like thing.
2019-02-26 15:47:14 +01:00
let env_hir_id = tcx.hir().get_parent_item(hir_trait.hir_ref_id);
let env_def_id = tcx.hir().local_def_id(env_hir_id);
let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.to_def_id());
let mut bounds = Bounds::default();
let _ = <dyn AstConv<'_>>::instantiate_poly_trait_ref_inner(
2019-12-22 23:42:04 +01:00
&item_cx,
hir_trait,
DUMMY_SP,
hir::Constness::NotConst,
2020-04-07 02:03:54 +02:00
self_ty,
2019-12-22 23:42:04 +01:00
&mut bounds,
true,
2017-11-18 16:49:37 +01:00
);
bounds
}