]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/lib.rs
Rollup merge of #48877 - GuillaumeGomez:vec-missing-links, r=QuietMisdreavus
[rust.git] / src / librustc_typeck / lib.rs
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.
4 //
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.
10
11 /*!
12
13 typeck.rs, an introduction
14
15 The type checker is responsible for:
16
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)
21
22 The main entry point is `check_crate()`.  Type checking operates in
23 several major phases:
24
25 1. The collect phase first passes over all items and determines their
26    type, without examining their "innards".
27
28 2. Variance inference then runs to compute the variance of each parameter
29
30 3. Coherence checks for overlapping or orphaned impls
31
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.
39
40 The type checker is defined into various submodules which are documented
41 independently:
42
43 - astconv: converts the AST representation of types
44   into the `ty` representation
45
46 - collect: computes the types of each top-level item and enters them into
47   the `tcx.types` table for later use
48
49 - coherence: enforces coherence rules, builds some tables
50
51 - variance: variance inference
52
53 - outlives: outlives inference
54
55 - check: walks over function bodies and type checks them, inferring types for
56   local variables, type parameters, etc as necessary.
57
58 - infer: finds the types to use for each type variable such that
59   all subtyping and assignment constraints are met.  In essence, the check
60   module specifies the constraints, and the infer module solves them.
61
62 # Note
63
64 This API is completely unstable and subject to change.
65
66 */
67
68 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
69       html_favicon_url = "https://doc.rust-lang.org/favicon.ico",
70       html_root_url = "https://doc.rust-lang.org/nightly/")]
71 #![deny(warnings)]
72
73 #![allow(non_camel_case_types)]
74
75 #![feature(advanced_slice_patterns)]
76 #![feature(box_patterns)]
77 #![feature(box_syntax)]
78 #![feature(conservative_impl_trait)]
79 #![feature(copy_closures, clone_closures)]
80 #![feature(crate_visibility_modifier)]
81 #![feature(from_ref)]
82 #![feature(match_default_bindings)]
83 #![feature(never_type)]
84 #![feature(option_filter)]
85 #![feature(quote)]
86 #![feature(refcell_replace_swap)]
87 #![feature(rustc_diagnostic_macros)]
88 #![feature(slice_patterns)]
89 #![feature(i128_type)]
90
91 #[macro_use] extern crate log;
92 #[macro_use] extern crate syntax;
93 extern crate syntax_pos;
94
95 extern crate arena;
96 #[macro_use] extern crate rustc;
97 extern crate rustc_platform_intrinsics as intrinsics;
98 extern crate rustc_const_math;
99 extern crate rustc_data_structures;
100 extern crate rustc_errors as errors;
101
102 use rustc::hir;
103 use rustc::lint;
104 use rustc::middle;
105 use rustc::session;
106 use rustc::util;
107
108 use hir::map as hir_map;
109 use rustc::infer::InferOk;
110 use rustc::ty::subst::Substs;
111 use rustc::ty::{self, Ty, TyCtxt};
112 use rustc::ty::maps::Providers;
113 use rustc::traits::{FulfillmentContext, ObligationCause, ObligationCauseCode, Reveal};
114 use session::{CompileIncomplete, config};
115 use util::common::time;
116
117 use syntax::ast;
118 use syntax::abi::Abi;
119 use syntax_pos::Span;
120
121 use std::iter;
122
123 // NB: This module needs to be declared first so diagnostics are
124 // registered before they are used.
125 mod diagnostics;
126
127 mod astconv;
128 mod check;
129 mod check_unused;
130 mod coherence;
131 mod collect;
132 mod constrained_type_params;
133 mod structured_errors;
134 mod impl_wf_check;
135 mod namespace;
136 mod outlives;
137 mod variance;
138
139 pub struct TypeAndSubsts<'tcx> {
140     substs: &'tcx Substs<'tcx>,
141     ty: Ty<'tcx>,
142 }
143
144 fn require_c_abi_if_variadic(tcx: TyCtxt,
145                              decl: &hir::FnDecl,
146                              abi: Abi,
147                              span: Span) {
148     if decl.variadic && !(abi == Abi::C || abi == Abi::Cdecl) {
149         let mut err = struct_span_err!(tcx.sess, span, E0045,
150                   "variadic function must have C or cdecl calling convention");
151         err.span_label(span, "variadics require C or cdecl calling convention").emit();
152     }
153 }
154
155 fn require_same_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
156                                 cause: &ObligationCause<'tcx>,
157                                 expected: Ty<'tcx>,
158                                 actual: Ty<'tcx>)
159                                 -> bool {
160     tcx.infer_ctxt().enter(|ref infcx| {
161         let param_env = ty::ParamEnv::empty(Reveal::UserFacing);
162         let mut fulfill_cx = FulfillmentContext::new();
163         match infcx.at(&cause, param_env).eq(expected, actual) {
164             Ok(InferOk { obligations, .. }) => {
165                 fulfill_cx.register_predicate_obligations(infcx, obligations);
166             }
167             Err(err) => {
168                 infcx.report_mismatched_types(cause, expected, actual, err).emit();
169                 return false;
170             }
171         }
172
173         match fulfill_cx.select_all_or_error(infcx) {
174             Ok(()) => true,
175             Err(errors) => {
176                 infcx.report_fulfillment_errors(&errors, None);
177                 false
178             }
179         }
180     })
181 }
182
183 fn check_main_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
184                               main_id: ast::NodeId,
185                               main_span: Span) {
186     let main_def_id = tcx.hir.local_def_id(main_id);
187     let main_t = tcx.type_of(main_def_id);
188     match main_t.sty {
189         ty::TyFnDef(..) => {
190             match tcx.hir.find(main_id) {
191                 Some(hir_map::NodeItem(it)) => {
192                     match it.node {
193                         hir::ItemFn(.., ref generics, _) => {
194                             if !generics.params.is_empty() {
195                                 struct_span_err!(tcx.sess, generics.span, E0131,
196                                          "main function is not allowed to have type parameters")
197                                     .span_label(generics.span,
198                                                 "main cannot have type parameters")
199                                     .emit();
200                                 return;
201                             }
202                         }
203                         _ => ()
204                     }
205                 }
206                 _ => ()
207             }
208
209             let actual = tcx.fn_sig(main_def_id);
210             let expected_return_type = if tcx.lang_items().termination().is_some()
211                 && tcx.features().termination_trait {
212                 // we take the return type of the given main function, the real check is done
213                 // in `check_fn`
214                 actual.output().skip_binder()
215             } else {
216                 // standard () main return type
217                 tcx.mk_nil()
218             };
219
220             let se_ty = tcx.mk_fn_ptr(ty::Binder(
221                 tcx.mk_fn_sig(
222                     iter::empty(),
223                     expected_return_type,
224                     false,
225                     hir::Unsafety::Normal,
226                     Abi::Rust
227                 )
228             ));
229
230             require_same_types(
231                 tcx,
232                 &ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
233                 se_ty,
234                 tcx.mk_fn_ptr(actual));
235         }
236         _ => {
237             span_bug!(main_span,
238                       "main has a non-function type: found `{}`",
239                       main_t);
240         }
241     }
242 }
243
244 fn check_start_fn_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
245                                start_id: ast::NodeId,
246                                start_span: Span) {
247     let start_def_id = tcx.hir.local_def_id(start_id);
248     let start_t = tcx.type_of(start_def_id);
249     match start_t.sty {
250         ty::TyFnDef(..) => {
251             match tcx.hir.find(start_id) {
252                 Some(hir_map::NodeItem(it)) => {
253                     match it.node {
254                         hir::ItemFn(..,ref ps,_)
255                         if !ps.params.is_empty() => {
256                             struct_span_err!(tcx.sess, ps.span, E0132,
257                                 "start function is not allowed to have type parameters")
258                                 .span_label(ps.span,
259                                             "start function cannot have type parameters")
260                                 .emit();
261                             return;
262                         }
263                         _ => ()
264                     }
265                 }
266                 _ => ()
267             }
268
269             let se_ty = tcx.mk_fn_ptr(ty::Binder(
270                 tcx.mk_fn_sig(
271                     [
272                         tcx.types.isize,
273                         tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))
274                     ].iter().cloned(),
275                     tcx.types.isize,
276                     false,
277                     hir::Unsafety::Normal,
278                     Abi::Rust
279                 )
280             ));
281
282             require_same_types(
283                 tcx,
284                 &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
285                 se_ty,
286                 tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)));
287         }
288         _ => {
289             span_bug!(start_span,
290                       "start has a non-function type: found `{}`",
291                       start_t);
292         }
293     }
294 }
295
296 fn check_for_entry_fn<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
297     if let Some((id, sp)) = *tcx.sess.entry_fn.borrow() {
298         match tcx.sess.entry_type.get() {
299             Some(config::EntryMain) => check_main_fn_ty(tcx, id, sp),
300             Some(config::EntryStart) => check_start_fn_ty(tcx, id, sp),
301             Some(config::EntryNone) => {}
302             None => bug!("entry function without a type")
303         }
304     }
305 }
306
307 pub fn provide(providers: &mut Providers) {
308     collect::provide(providers);
309     coherence::provide(providers);
310     check::provide(providers);
311     variance::provide(providers);
312     outlives::provide(providers);
313 }
314
315 pub fn check_crate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>)
316                              -> Result<(), CompileIncomplete>
317 {
318     // this ensures that later parts of type checking can assume that items
319     // have valid types and not error
320     tcx.sess.track_errors(|| {
321         time(tcx.sess, "type collecting", ||
322              collect::collect_item_types(tcx));
323
324     })?;
325
326     tcx.sess.track_errors(|| {
327         time(tcx.sess, "outlives testing", ||
328             outlives::test::test_inferred_outlives(tcx));
329     })?;
330
331     tcx.sess.track_errors(|| {
332         time(tcx.sess, "impl wf inference", ||
333              impl_wf_check::impl_wf_check(tcx));
334     })?;
335
336     tcx.sess.track_errors(|| {
337       time(tcx.sess, "coherence checking", ||
338           coherence::check_coherence(tcx));
339     })?;
340
341     tcx.sess.track_errors(|| {
342         time(tcx.sess, "variance testing", ||
343              variance::test::test_variance(tcx));
344     })?;
345
346     time(tcx.sess, "wf checking", || check::check_wf_new(tcx))?;
347
348     time(tcx.sess, "item-types checking", || check::check_item_types(tcx))?;
349
350     time(tcx.sess, "item-bodies checking", || check::check_item_bodies(tcx))?;
351
352     check_unused::check_crate(tcx);
353     check_for_entry_fn(tcx);
354
355     tcx.sess.compile_status()
356 }
357
358 /// A quasi-deprecated helper used in rustdoc and save-analysis to get
359 /// the type from a HIR node.
360 pub fn hir_ty_to_ty<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_ty: &hir::Ty) -> Ty<'tcx> {
361     // In case there are any projections etc, find the "environment"
362     // def-id that will be used to determine the traits/predicates in
363     // scope.  This is derived from the enclosing item-like thing.
364     let env_node_id = tcx.hir.get_parent(hir_ty.id);
365     let env_def_id = tcx.hir.local_def_id(env_node_id);
366     let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
367     astconv::AstConv::ast_ty_to_ty(&item_cx, hir_ty)
368 }
369
370 pub fn hir_trait_to_predicates<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, hir_trait: &hir::TraitRef)
371         -> (ty::PolyTraitRef<'tcx>, Vec<ty::PolyProjectionPredicate<'tcx>>) {
372     // In case there are any projections etc, find the "environment"
373     // def-id that will be used to determine the traits/predicates in
374     // scope.  This is derived from the enclosing item-like thing.
375     let env_node_id = tcx.hir.get_parent(hir_trait.ref_id);
376     let env_def_id = tcx.hir.local_def_id(env_node_id);
377     let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id);
378     let mut projections = Vec::new();
379     let principal = astconv::AstConv::instantiate_poly_trait_ref_inner(
380         &item_cx, hir_trait, tcx.types.err, &mut projections, true
381     );
382     (principal, projections)
383 }
384
385 __build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }