]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/lib.rs
Rollup merge of #63055 - Mark-Simulacrum:save-analysis-clean-2, r=Xanewok
[rust.git] / src / librustc_typeck / lib.rs
1 /*!
2
3 # typeck
4
5 The type checker is responsible for:
6
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)
11
12 The main entry point is `check_crate()`. Type checking operates in
13 several major phases:
14
15 1. The collect phase first passes over all items and determines their
16    type, without examining their "innards".
17
18 2. Variance inference then runs to compute the variance of each parameter.
19
20 3. Coherence checks for overlapping or orphaned impls.
21
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.
29
30 The type checker is defined into various submodules which are documented
31 independently:
32
33 - astconv: converts the AST representation of types
34   into the `ty` representation.
35
36 - collect: computes the types of each top-level item and enters them into
37   the `tcx.types` table for later use.
38
39 - coherence: enforces coherence rules, builds some tables.
40
41 - variance: variance inference
42
43 - outlives: outlives inference
44
45 - check: walks over function bodies and type checks them, inferring types for
46   local variables, type parameters, etc as necessary.
47
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.
51
52 ## Note
53
54 This API is completely unstable and subject to change.
55
56 */
57
58 #![doc(html_root_url = "https://doc.rust-lang.org/nightly/")]
59
60 #![allow(non_camel_case_types)]
61
62 #![feature(box_patterns)]
63 #![feature(box_syntax)]
64 #![feature(crate_visibility_modifier)]
65 #![feature(exhaustive_patterns)]
66 #![feature(in_band_lifetimes)]
67 #![feature(nll)]
68 #![feature(rustc_diagnostic_macros)]
69 #![feature(slice_patterns)]
70 #![feature(never_type)]
71 #![feature(inner_deref)]
72 #![feature(mem_take)]
73
74 #![recursion_limit="256"]
75
76 #[macro_use] extern crate log;
77 #[macro_use] extern crate syntax;
78
79 #[macro_use] extern crate rustc;
80
81 // N.B., this module needs to be declared first so diagnostics are
82 // registered before they are used.
83 mod error_codes;
84
85 mod astconv;
86 mod check;
87 mod check_unused;
88 mod coherence;
89 mod collect;
90 mod constrained_generic_params;
91 mod structured_errors;
92 mod impl_wf_check;
93 mod namespace;
94 mod outlives;
95 mod variance;
96
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;
101 use rustc::lint;
102 use rustc::middle;
103 use rustc::session;
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;
110 use rustc::util;
111 use syntax_pos::Span;
112 use util::common::time;
113
114 use std::iter;
115
116 use astconv::{AstConv, Bounds};
117 pub use collect::checked_type_of;
118
119 pub struct TypeAndSubsts<'tcx> {
120     substs: SubstsRef<'tcx>,
121     ty: Ty<'tcx>,
122 }
123
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();
129     }
130 }
131
132 fn require_same_types<'tcx>(
133     tcx: TyCtxt<'tcx>,
134     cause: &ObligationCause<'tcx>,
135     expected: Ty<'tcx>,
136     actual: Ty<'tcx>,
137 ) -> bool {
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);
144             }
145             Err(err) => {
146                 infcx.report_mismatched_types(cause, expected, actual, err).emit();
147                 return false;
148             }
149         }
150
151         match fulfill_cx.select_all_or_error(infcx) {
152             Ok(()) => true,
153             Err(errors) => {
154                 infcx.report_fulfillment_errors(&errors, None, false);
155                 false
156             }
157         }
158     })
159 }
160
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);
165     match main_t.sty {
166         ty::FnDef(..) => {
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)
176                             .emit();
177                         error = true;
178                     }
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")
183                             .emit();
184                         error = true;
185                     }
186                     if error {
187                         return;
188                     }
189                 }
190             }
191
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
195                 // in `check_fn`
196                 actual.output().skip_binder()
197             } else {
198                 // standard () main return type
199                 tcx.mk_unit()
200             };
201
202             let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
203                 tcx.mk_fn_sig(
204                     iter::empty(),
205                     expected_return_type,
206                     false,
207                     hir::Unsafety::Normal,
208                     Abi::Rust
209                 )
210             ));
211
212             require_same_types(
213                 tcx,
214                 &ObligationCause::new(main_span, main_id, ObligationCauseCode::MainFunctionType),
215                 se_ty,
216                 tcx.mk_fn_ptr(actual));
217         }
218         _ => {
219             span_bug!(main_span,
220                       "main has a non-function type: found `{}`",
221                       main_t);
222         }
223     }
224 }
225
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);
230     match start_t.sty {
231         ty::FnDef(..) => {
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")
240                             .emit();
241                         error = true;
242                     }
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")
247                             .emit();
248                         error = true;
249                     }
250                     if error {
251                         return;
252                     }
253                 }
254             }
255
256             let se_ty = tcx.mk_fn_ptr(ty::Binder::bind(
257                 tcx.mk_fn_sig(
258                     [
259                         tcx.types.isize,
260                         tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))
261                     ].iter().cloned(),
262                     tcx.types.isize,
263                     false,
264                     hir::Unsafety::Normal,
265                     Abi::Rust
266                 )
267             ));
268
269             require_same_types(
270                 tcx,
271                 &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
272                 se_ty,
273                 tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)));
274         }
275         _ => {
276             span_bug!(start_span,
277                       "start has a non-function type: found `{}`",
278                       start_t);
279         }
280     }
281 }
282
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),
287         _ => {}
288     }
289 }
290
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);
298 }
299
300 pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorReported> {
301     tcx.sess.profiler(|p| p.start_activity("type-check crate"));
302
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));
310             }
311         });
312     })?;
313
314     if tcx.features().rustc_attrs {
315         tcx.sess.track_errors(|| {
316             time(tcx.sess, "outlives testing", ||
317                 outlives::test::test_inferred_outlives(tcx));
318         })?;
319     }
320
321     tcx.sess.track_errors(|| {
322         time(tcx.sess, "impl wf inference", ||
323              impl_wf_check::impl_wf_check(tcx));
324     })?;
325
326     tcx.sess.track_errors(|| {
327       time(tcx.sess, "coherence checking", ||
328           coherence::check_coherence(tcx));
329     })?;
330
331     if tcx.features().rustc_attrs {
332         tcx.sess.track_errors(|| {
333             time(tcx.sess, "variance testing", ||
334                 variance::test::test_variance(tcx));
335         })?;
336     }
337
338     tcx.sess.track_errors(|| {
339         time(tcx.sess, "wf checking", || check::check_wf_new(tcx));
340     })?;
341
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));
345         }
346     });
347
348     time(tcx.sess, "item-bodies checking", || tcx.typeck_item_bodies(LOCAL_CRATE));
349
350     check_unused::check_crate(tcx);
351     check_for_entry_fn(tcx);
352
353     tcx.sess.profiler(|p| p.end_activity("type-check crate"));
354
355     if tcx.sess.err_count() == 0 {
356         Ok(())
357     } else {
358         Err(ErrorReported)
359     }
360 }
361
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);
371
372     astconv::AstConv::ast_ty_to_ty(&item_cx, hir_ty)
373 }
374
375 pub fn hir_trait_to_predicates<'tcx>(
376     tcx: TyCtxt<'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
388     );
389
390     (principal, bounds)
391 }
392
393 __build_diagnostic_array! { librustc_typeck, DIAGNOSTICS }