1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
13 typeck.rs, an introduction
15 The type checker is responsible for:
17 1. Determining the type of each expression
18 2. Resolving methods and traits
19 3. Guaranteeing that most type rules are met ("most?", you say, "why most?"
20 Well, dear reader, read on)
22 The main entry point is `check_crate()`. Type checking operates in
25 1. The collect phase first passes over all items and determines their
26 type, without examining their "innards".
28 2. Variance inference then runs to compute the variance of each parameter
30 3. Coherence checks for overlapping or orphaned impls
32 4. Finally, the check phase then checks function bodies and so forth.
33 Within the check phase, we check each function body one at a time
34 (bodies of function expressions are checked as part of the
35 containing function). Inference is used to supply types wherever
36 they are unknown. The actual checking of a function itself has
37 several phases (check, regionck, writeback), as discussed in the
38 documentation for the `check` module.
40 The type checker is defined into various submodules which are documented
43 - astconv: converts the AST representation of types
44 into the `ty` representation
46 - collect: computes the types of each top-level item and enters them into
47 the `tcx.types` table for later use
49 - coherence: enforces coherence rules, builds some tables
51 - variance: variance inference
53 - check: walks over function bodies and type checks them, inferring types for
54 local variables, type parameters, etc as necessary.
56 - infer: finds the types to use for each type variable such that
57 all subtyping and assignment constraints are met. In essence, the check
58 module specifies the constraints, and the infer module solves them.
62 This API is completely unstable and subject to change.
66 #![crate_name = "rustc_typeck"]
67 #![unstable(feature = "rustc_private", issue = "27812")]
68 #![crate_type = "dylib"]
69 #![crate_type = "rlib"]
70 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
71 html_favicon_url
= "https://doc.rust-lang.org/favicon.ico",
72 html_root_url
= "https://doc.rust-lang.org/nightly/")]
75 #![allow(non_camel_case_types)]
77 #![feature(box_patterns)]
78 #![feature(box_syntax)]
79 #![feature(conservative_impl_trait)]
80 #![cfg_attr(stage0,feature(field_init_shorthand))]
81 #![feature(loop_break_value)]
83 #![feature(rustc_diagnostic_macros)]
84 #![feature(rustc_private)]
85 #![feature(staged_api)]
87 #[macro_use] extern crate log;
88 #[macro_use] extern crate syntax;
89 extern crate syntax_pos
;
92 extern crate fmt_macros
;
93 #[macro_use] extern crate rustc;
94 extern crate rustc_platform_intrinsics
as intrinsics
;
95 extern crate rustc_back
;
96 extern crate rustc_const_math
;
97 extern crate rustc_const_eval
;
98 extern crate rustc_data_structures
;
99 extern crate rustc_errors
as errors
;
101 pub use rustc
::dep_graph
;
104 pub use rustc
::middle
;
105 pub use rustc
::session
;
108 use dep_graph
::DepNode
;
109 use hir
::map
as hir_map
;
110 use rustc
::infer
::InferOk
;
111 use rustc
::ty
::subst
::Substs
;
112 use rustc
::ty
::{self, Ty, TyCtxt}
;
113 use rustc
::ty
::maps
::Providers
;
114 use rustc
::traits
::{ObligationCause, ObligationCauseCode, Reveal}
;
116 use util
::common
::time
;
119 use syntax
::abi
::Abi
;
120 use syntax_pos
::Span
;
123 // NB: This module needs to be declared first so diagnostics are
124 // registered before they are used.
128 pub mod check_unused
;
131 mod constrained_type_params
;
136 pub struct TypeAndSubsts
<'tcx
> {
137 pub substs
: &'tcx Substs
<'tcx
>,
141 fn require_c_abi_if_variadic(tcx
: TyCtxt
,
145 if decl
.variadic
&& abi
!= Abi
::C
{
146 let mut err
= struct_span_err
!(tcx
.sess
, span
, E0045
,
147 "variadic function must have C calling convention");
148 err
.span_label(span
, &("variadics require C calling conventions").to_string())
153 fn require_same_types
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
154 cause
: &ObligationCause
<'tcx
>,
158 tcx
.infer_ctxt((), Reveal
::UserFacing
).enter(|infcx
| {
159 match infcx
.eq_types(false, &cause
, expected
, actual
) {
160 Ok(InferOk { obligations, .. }
) => {
161 // FIXME(#32730) propagate obligations
162 assert
!(obligations
.is_empty());
166 infcx
.report_mismatched_types(cause
, expected
, actual
, err
).emit();
173 fn check_main_fn_ty
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
174 main_id
: ast
::NodeId
,
176 let main_def_id
= tcx
.hir
.local_def_id(main_id
);
177 let main_t
= tcx
.item_type(main_def_id
);
180 match tcx
.hir
.find(main_id
) {
181 Some(hir_map
::NodeItem(it
)) => {
183 hir
::ItemFn(.., ref generics
, _
) => {
184 if generics
.is_parameterized() {
185 struct_span_err
!(tcx
.sess
, generics
.span
, E0131
,
186 "main function is not allowed to have type parameters")
187 .span_label(generics
.span
,
188 &format
!("main cannot have type parameters"))
198 let substs
= tcx
.intern_substs(&[]);
199 let se_ty
= tcx
.mk_fn_def(main_def_id
, substs
,
200 ty
::Binder(tcx
.mk_fn_sig(
204 hir
::Unsafety
::Normal
,
211 &ObligationCause
::new(main_span
, main_id
, ObligationCauseCode
::MainFunctionType
),
217 "main has a non-function type: found `{}`",
223 fn check_start_fn_ty
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>,
224 start_id
: ast
::NodeId
,
226 let start_def_id
= tcx
.hir
.local_def_id(start_id
);
227 let start_t
= tcx
.item_type(start_def_id
);
230 match tcx
.hir
.find(start_id
) {
231 Some(hir_map
::NodeItem(it
)) => {
233 hir
::ItemFn(..,ref ps
,_
)
234 if ps
.is_parameterized() => {
235 struct_span_err
!(tcx
.sess
, ps
.span
, E0132
,
236 "start function is not allowed to have type parameters")
238 &format
!("start function cannot have type parameters"))
248 let substs
= tcx
.intern_substs(&[]);
249 let se_ty
= tcx
.mk_fn_def(start_def_id
, substs
,
250 ty
::Binder(tcx
.mk_fn_sig(
253 tcx
.mk_imm_ptr(tcx
.mk_imm_ptr(tcx
.types
.u8))
257 hir
::Unsafety
::Normal
,
264 &ObligationCause
::new(start_span
, start_id
, ObligationCauseCode
::StartFunctionType
),
269 span_bug
!(start_span
,
270 "start has a non-function type: found `{}`",
276 fn check_for_entry_fn
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>) {
277 let _task
= tcx
.dep_graph
.in_task(DepNode
::CheckEntryFn
);
278 if let Some((id
, sp
)) = *tcx
.sess
.entry_fn
.borrow() {
279 match tcx
.sess
.entry_type
.get() {
280 Some(config
::EntryMain
) => check_main_fn_ty(tcx
, id
, sp
),
281 Some(config
::EntryStart
) => check_start_fn_ty(tcx
, id
, sp
),
282 Some(config
::EntryNone
) => {}
283 None
=> bug
!("entry function without a type")
288 pub fn provide(providers
: &mut Providers
) {
289 collect
::provide(providers
);
290 coherence
::provide(providers
);
291 check
::provide(providers
);
294 pub fn check_crate
<'a
, 'tcx
>(tcx
: TyCtxt
<'a
, 'tcx
, 'tcx
>)
295 -> Result
<(), usize> {
296 let time_passes
= tcx
.sess
.time_passes();
298 // this ensures that later parts of type checking can assume that items
299 // have valid types and not error
300 tcx
.sess
.track_errors(|| {
301 time(time_passes
, "type collecting", ||
302 collect
::collect_item_types(tcx
));
306 time(time_passes
, "variance inference", ||
307 variance
::infer_variance(tcx
));
309 tcx
.sess
.track_errors(|| {
310 time(time_passes
, "impl wf inference", ||
311 impl_wf_check
::impl_wf_check(tcx
));
314 tcx
.sess
.track_errors(|| {
315 time(time_passes
, "coherence checking", ||
316 coherence
::check_coherence(tcx
));
319 time(time_passes
, "wf checking", || check
::check_wf_new(tcx
))?
;
321 time(time_passes
, "item-types checking", || check
::check_item_types(tcx
))?
;
323 time(time_passes
, "item-bodies checking", || check
::check_item_bodies(tcx
))?
;
325 check_unused
::check_crate(tcx
);
326 check_for_entry_fn(tcx
);
328 let err_count
= tcx
.sess
.err_count();
336 __build_diagnostic_array
! { librustc_typeck, DIAGNOSTICS }