5 The type checker is responsible for:
7 1. Determining the type of each expression.
8 2. Resolving methods and traits.
9 3. Guaranteeing that most type rules are met. ("Most?", you say, "why most?"
10 Well, dear reader, read on)
12 The main entry point is `check_crate()`. Type checking operates in
15 1. The collect phase first passes over all items and determines their
16 type, without examining their "innards".
18 2. Variance inference then runs to compute the variance of each parameter.
20 3. Coherence checks for overlapping or orphaned impls.
22 4. Finally, the check phase then checks function bodies and so forth.
23 Within the check phase, we check each function body one at a time
24 (bodies of function expressions are checked as part of the
25 containing function). Inference is used to supply types wherever
26 they are unknown. The actual checking of a function itself has
27 several phases (check, regionck, writeback), as discussed in the
28 documentation for the `check` module.
30 The type checker is defined into various submodules which are documented
33 - astconv: converts the AST representation of types
34 into the `ty` representation.
36 - collect: computes the types of each top-level item and enters them into
37 the `tcx.types` table for later use.
39 - coherence: enforces coherence rules, builds some tables.
41 - variance: variance inference
43 - outlives: outlives inference
45 - check: walks over function bodies and type checks them, inferring types for
46 local variables, type parameters, etc as necessary.
48 - infer: finds the types to use for each type variable such that
49 all subtyping and assignment constraints are met. In essence, the check
50 module specifies the constraints, and the infer module solves them.
54 This API is completely unstable and subject to change.
58 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
60 #![allow(non_camel_case_types)]
62 #![feature(box_patterns)]
63 #![feature(box_syntax)]
64 #![feature(crate_visibility_modifier)]
65 #![feature(exhaustive_patterns)]
66 #![feature(in_band_lifetimes)]
68 #![feature(rustc_diagnostic_macros)]
69 #![feature(slice_patterns)]
70 #![feature(never_type)]
71 #![feature(inner_deref)]
74 #![recursion_limit="256"]
76 #[macro_use] extern crate log;
77 #[macro_use] extern crate syntax;
79 #[macro_use] extern crate rustc;
81 // N.B., this module needs to be declared first so diagnostics are
82 // registered before they are used.
90 mod constrained_generic_params;
91 mod structured_errors;
97 use rustc_target::spec::abi::Abi;
98 use rustc::hir::{self, Node};
99 use rustc::hir::def_id::{DefId, LOCAL_CRATE};
100 use rustc::infer::InferOk;
104 use rustc::util::common::ErrorReported;
105 use rustc::session::config::EntryFnType;
106 use rustc::traits::{ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt};
107 use rustc::ty::subst::SubstsRef;
108 use rustc::ty::{self, Ty, TyCtxt};
109 use rustc::ty::query::Providers;
111 use syntax_pos::Span;
112 use util::common::time;
116 use astconv::{AstConv, Bounds};
117 pub use collect::checked_type_of;
119 pub struct TypeAndSubsts<'tcx> {
120 substs: SubstsRef<'tcx>,
124 fn require_c_abi_if_c_variadic(tcx: TyCtxt<'_>, decl: &hir::FnDecl, abi: Abi, span: Span) {
125 if decl.c_variadic && !(abi == Abi::C || abi == Abi::Cdecl) {
126 let mut err = struct_span_err!(tcx.sess, span, E0045,
127 "C-variadic function must have C or cdecl calling convention");
128 err.span_label(span, "C-variadics require C or cdecl calling convention").emit();
132 fn require_same_types<'tcx>(
134 cause: &ObligationCause<'tcx>,
138 tcx.infer_ctxt().enter(|ref infcx| {
139 let param_env = ty::ParamEnv::empty();
140 let mut fulfill_cx = TraitEngine::new(infcx.tcx);
141 match infcx.at(&cause, param_env).eq(expected, actual) {
142 Ok(InferOk { obligations, .. }) => {
143 fulfill_cx.register_predicate_obligations(infcx, obligations);
146 infcx.report_mismatched_types(cause, expected, actual, err).emit();
151 match fulfill_cx.select_all_or_error(infcx) {
154 infcx.report_fulfillment_errors(&errors, None, false);
161 fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) {
162 let main_id = tcx.hir().as_local_hir_id(main_def_id).unwrap();
163 let main_span = tcx.def_span(main_def_id);
164 let main_t = tcx.type_of(main_def_id);
167 if let Some(Node::Item(it)) = tcx.hir().find(main_id) {
168 if let hir::ItemKind::Fn(.., ref generics, _) = it.node {
169 let mut error = false;
170 if !generics.params.is_empty() {
171 let msg = "`main` function is not allowed to have generic \
172 parameters".to_owned();
173 let label = "`main` cannot have generic parameters".to_string();
174 struct_span_err!(tcx.sess, generics.span, E0131, "{}", msg)
175 .span_label(generics.span, label)
179 if let Some(sp) = generics.where_clause.span() {
180 struct_span_err!(tcx.sess, sp, E0646,
181 "`main` function is not allowed to have a `where` clause")
182 .span_label(sp, "`main` cannot have a `where` clause")
192 let actual = tcx.fn_sig(main_def_id);
193 let expected_return_type = if tcx.lang_items().termination().is_some() {
194 // we take the return type of the given main function, the real check is done
196 actual.output().skip_binder()
198 // standard () main return type
202 let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
205 expected_return_type,
207 hir::Unsafety::Normal,
214 &ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
216 tcx.mk_fn_ptr(actual));
220 "main has a non-function type: found `{}`",
226 fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) {
227 let start_id = tcx.hir().as_local_hir_id(start_def_id).unwrap();
228 let start_span = tcx.def_span(start_def_id);
229 let start_t = tcx.type_of(start_def_id);
232 if let Some(Node::Item(it)) = tcx.hir().find(start_id) {
233 if let hir::ItemKind::Fn(.., ref generics, _) = it.node {
234 let mut error = false;
235 if !generics.params.is_empty() {
236 struct_span_err!(tcx.sess, generics.span, E0132,
237 "start function is not allowed to have type parameters")
238 .span_label(generics.span,
239 "start function cannot have type parameters")
243 if let Some(sp) = generics.where_clause.span() {
244 struct_span_err!(tcx.sess, sp, E0647,
245 "start function is not allowed to have a `where` clause")
246 .span_label(sp, "start function cannot have a `where` clause")
256 let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
260 tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))
264 hir::Unsafety::Normal,
271 &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
273 tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)));
276 span_bug!(start_span,
277 "start has a non-function type: found `{}`",
283 fn check_for_entry_fn(tcx: TyCtxt<'_>) {
284 match tcx.entry_fn(LOCAL_CRATE) {
285 Some((def_id, EntryFnType::Main)) => check_main_fn_ty(tcx, def_id),
286 Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id),
291 pub fn provide(providers: &mut Providers<'_>) {
292 collect::provide(providers);
293 coherence::provide(providers);
294 check::provide(providers);
295 variance::provide(providers);
296 outlives::provide(providers);
297 impl_wf_check::provide(providers);
300 pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorReported> {
301 tcx.sess.profiler(|p| p.start_activity("type-check crate"));
303 // this ensures that later parts of type checking can assume that items
304 // have valid types and not error
305 // FIXME(matthewjasper) We shouldn't need to do this.
306 tcx.sess.track_errors(|| {
307 time(tcx.sess, "type collecting", || {
308 for &module in tcx.hir().krate().modules.keys() {
309 tcx.ensure().collect_mod_item_types(tcx.hir().local_def_id_from_node_id(module));
314 if tcx.features().rustc_attrs {
315 tcx.sess.track_errors(|| {
316 time(tcx.sess, "outlives testing", ||
317 outlives::test::test_inferred_outlives(tcx));
321 tcx.sess.track_errors(|| {
322 time(tcx.sess, "impl wf inference", ||
323 impl_wf_check::impl_wf_check(tcx));
326 tcx.sess.track_errors(|| {
327 time(tcx.sess, "coherence checking", ||
328 coherence::check_coherence(tcx));
331 if tcx.features().rustc_attrs {
332 tcx.sess.track_errors(|| {
333 time(tcx.sess, "variance testing", ||
334 variance::test::test_variance(tcx));
338 tcx.sess.track_errors(|| {
339 time(tcx.sess, "wf checking", || check::check_wf_new(tcx));
342 time(tcx.sess, "item-types checking", || {
343 for &module in tcx.hir().krate().modules.keys() {
344 tcx.ensure().check_mod_item_types(tcx.hir().local_def_id_from_node_id(module));
348 time(tcx.sess, "item-bodies checking", || tcx.typeck_item_bodies(LOCAL_CRATE));
350 check_unused::check_crate(tcx);
351 check_for_entry_fn(tcx);
353 tcx.sess.profiler(|p| p.end_activity("type-check crate"));
355 if tcx.sess.err_count() == 0 {
362 /// A quasi-deprecated helper used in rustdoc and clippy to get
363 /// the type from a HIR node.
364 pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> {
365 // In case there are any projections, etc., find the "environment"
366 // def-ID that will be used to determine the traits/predicates in
367 // scope. This is derived from the enclosing item-like thing.
368 let env_node_id = tcx.hir().get_parent_item(hir_ty.hir_id);
369 let env_def_id = tcx.hir().local_def_id(env_node_id);
370 let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
372 astconv::AstConv::ast_ty_to_ty(&item_cx, hir_ty)
375 pub fn hir_trait_to_predicates<'tcx>(
377 hir_trait: &hir::TraitRef,
378 ) -> (ty::PolyTraitRef<'tcx>, Bounds<'tcx>) {
379 // In case there are any projections, etc., find the "environment"
380 // def-ID that will be used to determine the traits/predicates in
381 // scope. This is derived from the enclosing item-like thing.
382 let env_hir_id = tcx.hir().get_parent_item(hir_trait.hir_ref_id);
383 let env_def_id = tcx.hir().local_def_id(env_hir_id);
384 let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
385 let mut bounds = Bounds::default();
386 let (principal, _) = AstConv::instantiate_poly_trait_ref_inner(
387 &item_cx, hir_trait, tcx.types.err, &mut bounds, true
393 __build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }