]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/lib.rs
bbfe5295fe107f6ec9e1ad223120a7402968ec2b
[rust.git] / compiler / rustc_typeck / src / 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/nightly-rustc/")]
59 #![feature(bool_to_option)]
60 #![feature(crate_visibility_modifier)]
61 #![feature(if_let_guard)]
62 #![feature(is_sorted)]
63 #![feature(let_else)]
64 #![feature(min_specialization)]
65 #![feature(nll)]
66 #![feature(try_blocks)]
67 #![feature(never_type)]
68 #![feature(slice_partition_dedup)]
69 #![feature(control_flow_enum)]
70 #![feature(hash_drain_filter)]
71 #![feature(once_cell)]
72 #![recursion_limit = "256"]
73 #![cfg_attr(not(bootstrap), allow(rustc::potential_query_instability))]
74
75 #[macro_use]
76 extern crate tracing;
77
78 #[macro_use]
79 extern crate rustc_middle;
80
81 // These are used by Clippy.
82 pub mod check;
83 pub mod expr_use_visitor;
84
85 mod astconv;
86 mod bounds;
87 mod check_unused;
88 mod coherence;
89 mod collect;
90 mod constrained_generic_params;
91 mod errors;
92 pub mod hir_wf_check;
93 mod impl_wf_check;
94 mod mem_categorization;
95 mod outlives;
96 mod structured_errors;
97 mod variance;
98
99 use rustc_errors::{struct_span_err, ErrorReported};
100 use rustc_hir as hir;
101 use rustc_hir::def_id::DefId;
102 use rustc_hir::{Node, CRATE_HIR_ID};
103 use rustc_infer::infer::{InferOk, TyCtxtInferExt};
104 use rustc_infer::traits::TraitEngineExt as _;
105 use rustc_middle::middle;
106 use rustc_middle::ty::query::Providers;
107 use rustc_middle::ty::{self, Ty, TyCtxt};
108 use rustc_middle::util;
109 use rustc_session::config::EntryFnType;
110 use rustc_span::{symbol::sym, Span, DUMMY_SP};
111 use rustc_target::spec::abi::Abi;
112 use rustc_trait_selection::infer::InferCtxtExt;
113 use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _;
114 use rustc_trait_selection::traits::{
115     self, ObligationCause, ObligationCauseCode, TraitEngine, TraitEngineExt as _,
116 };
117
118 use std::iter;
119
120 use astconv::AstConv;
121 use bounds::Bounds;
122
123 fn require_c_abi_if_c_variadic(tcx: TyCtxt<'_>, decl: &hir::FnDecl<'_>, abi: Abi, span: Span) {
124     match (decl.c_variadic, abi) {
125         // The function has the correct calling convention, or isn't a "C-variadic" function.
126         (false, _) | (true, Abi::C { .. }) | (true, Abi::Cdecl { .. }) => {}
127         // The function is a "C-variadic" function with an incorrect calling convention.
128         (true, _) => {
129             let mut err = struct_span_err!(
130                 tcx.sess,
131                 span,
132                 E0045,
133                 "C-variadic function must have C or cdecl calling convention"
134             );
135             err.span_label(span, "C-variadics require C or cdecl calling convention").emit();
136         }
137     }
138 }
139
140 fn require_same_types<'tcx>(
141     tcx: TyCtxt<'tcx>,
142     cause: &ObligationCause<'tcx>,
143     expected: Ty<'tcx>,
144     actual: Ty<'tcx>,
145 ) -> bool {
146     tcx.infer_ctxt().enter(|ref infcx| {
147         let param_env = ty::ParamEnv::empty();
148         let mut fulfill_cx = <dyn TraitEngine<'_>>::new(infcx.tcx);
149         match infcx.at(cause, param_env).eq(expected, actual) {
150             Ok(InferOk { obligations, .. }) => {
151                 fulfill_cx.register_predicate_obligations(infcx, obligations);
152             }
153             Err(err) => {
154                 infcx.report_mismatched_types(cause, expected, actual, err).emit();
155                 return false;
156             }
157         }
158
159         match fulfill_cx.select_all_or_error(infcx).as_slice() {
160             [] => true,
161             errors => {
162                 infcx.report_fulfillment_errors(errors, None, false);
163                 false
164             }
165         }
166     })
167 }
168
169 fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) {
170     let main_fnsig = tcx.fn_sig(main_def_id);
171     let main_span = tcx.def_span(main_def_id);
172
173     fn main_fn_diagnostics_hir_id(tcx: TyCtxt<'_>, def_id: DefId, sp: Span) -> hir::HirId {
174         if let Some(local_def_id) = def_id.as_local() {
175             let hir_id = tcx.hir().local_def_id_to_hir_id(local_def_id);
176             let hir_type = tcx.type_of(local_def_id);
177             if !matches!(hir_type.kind(), ty::FnDef(..)) {
178                 span_bug!(sp, "main has a non-function type: found `{}`", hir_type);
179             }
180             hir_id
181         } else {
182             CRATE_HIR_ID
183         }
184     }
185
186     fn main_fn_generics_params_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
187         if !def_id.is_local() {
188             return None;
189         }
190         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
191         match tcx.hir().find(hir_id) {
192             Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, ref generics, _), .. })) => {
193                 if !generics.params.is_empty() {
194                     Some(generics.span)
195                 } else {
196                     None
197                 }
198             }
199             _ => {
200                 span_bug!(tcx.def_span(def_id), "main has a non-function type");
201             }
202         }
203     }
204
205     fn main_fn_where_clauses_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
206         if !def_id.is_local() {
207             return None;
208         }
209         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
210         match tcx.hir().find(hir_id) {
211             Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(_, ref generics, _), .. })) => {
212                 generics.where_clause.span()
213             }
214             _ => {
215                 span_bug!(tcx.def_span(def_id), "main has a non-function type");
216             }
217         }
218     }
219
220     fn main_fn_asyncness_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
221         if !def_id.is_local() {
222             return None;
223         }
224         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
225         match tcx.hir().find(hir_id) {
226             Some(Node::Item(hir::Item { span: item_span, .. })) => {
227                 Some(tcx.sess.source_map().guess_head_span(*item_span))
228             }
229             _ => {
230                 span_bug!(tcx.def_span(def_id), "main has a non-function type");
231             }
232         }
233     }
234
235     fn main_fn_return_type_span(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Span> {
236         if !def_id.is_local() {
237             return None;
238         }
239         let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
240         match tcx.hir().find(hir_id) {
241             Some(Node::Item(hir::Item { kind: hir::ItemKind::Fn(ref fn_sig, _, _), .. })) => {
242                 Some(fn_sig.decl.output.span())
243             }
244             _ => {
245                 span_bug!(tcx.def_span(def_id), "main has a non-function type");
246             }
247         }
248     }
249
250     let mut error = false;
251     let main_diagnostics_hir_id = main_fn_diagnostics_hir_id(tcx, main_def_id, main_span);
252     let main_fn_generics = tcx.generics_of(main_def_id);
253     let main_fn_predicates = tcx.predicates_of(main_def_id);
254     if main_fn_generics.count() != 0 || !main_fnsig.bound_vars().is_empty() {
255         let generics_param_span = main_fn_generics_params_span(tcx, main_def_id);
256         let msg = "`main` function is not allowed to have generic \
257             parameters";
258         let mut diag =
259             struct_span_err!(tcx.sess, generics_param_span.unwrap_or(main_span), E0131, "{}", msg);
260         if let Some(generics_param_span) = generics_param_span {
261             let label = "`main` cannot have generic parameters".to_string();
262             diag.span_label(generics_param_span, label);
263         }
264         diag.emit();
265         error = true;
266     } else if !main_fn_predicates.predicates.is_empty() {
267         // generics may bring in implicit predicates, so we skip this check if generics is present.
268         let generics_where_clauses_span = main_fn_where_clauses_span(tcx, main_def_id);
269         let mut diag = struct_span_err!(
270             tcx.sess,
271             generics_where_clauses_span.unwrap_or(main_span),
272             E0646,
273             "`main` function is not allowed to have a `where` clause"
274         );
275         if let Some(generics_where_clauses_span) = generics_where_clauses_span {
276             diag.span_label(generics_where_clauses_span, "`main` cannot have a `where` clause");
277         }
278         diag.emit();
279         error = true;
280     }
281
282     let main_asyncness = tcx.asyncness(main_def_id);
283     if let hir::IsAsync::Async = main_asyncness {
284         let mut diag = struct_span_err!(
285             tcx.sess,
286             main_span,
287             E0752,
288             "`main` function is not allowed to be `async`"
289         );
290         let asyncness_span = main_fn_asyncness_span(tcx, main_def_id);
291         if let Some(asyncness_span) = asyncness_span {
292             diag.span_label(asyncness_span, "`main` function is not allowed to be `async`");
293         }
294         diag.emit();
295         error = true;
296     }
297
298     for attr in tcx.get_attrs(main_def_id) {
299         if attr.has_name(sym::track_caller) {
300             tcx.sess
301                 .struct_span_err(
302                     attr.span,
303                     "`main` function is not allowed to be `#[track_caller]`",
304                 )
305                 .span_label(main_span, "`main` function is not allowed to be `#[track_caller]`")
306                 .emit();
307             error = true;
308         }
309     }
310
311     if error {
312         return;
313     }
314
315     let expected_return_type;
316     if let Some(term_id) = tcx.lang_items().termination() {
317         let return_ty = main_fnsig.output();
318         let return_ty_span = main_fn_return_type_span(tcx, main_def_id).unwrap_or(main_span);
319         if !return_ty.bound_vars().is_empty() {
320             let msg = "`main` function return type is not allowed to have generic \
321                     parameters"
322                 .to_owned();
323             struct_span_err!(tcx.sess, return_ty_span, E0131, "{}", msg).emit();
324             error = true;
325         }
326         let return_ty = return_ty.skip_binder();
327         tcx.infer_ctxt().enter(|infcx| {
328             let cause = traits::ObligationCause::new(
329                 return_ty_span,
330                 main_diagnostics_hir_id,
331                 ObligationCauseCode::MainFunctionType,
332             );
333             let mut fulfillment_cx = traits::FulfillmentContext::new();
334             // normalize any potential projections in the return type, then add
335             // any possible obligations to the fulfillment context.
336             // HACK(ThePuzzlemaker) this feels symptomatic of a problem within
337             // checking trait fulfillment, not this here. I'm not sure why it
338             // works in the example in `fn test()` given in #88609? This also
339             // probably isn't the best way to do this.
340             let InferOk { value: norm_return_ty, obligations } = infcx
341                 .partially_normalize_associated_types_in(
342                     cause.clone(),
343                     ty::ParamEnv::empty(),
344                     return_ty,
345                 );
346             fulfillment_cx.register_predicate_obligations(&infcx, obligations);
347             fulfillment_cx.register_bound(
348                 &infcx,
349                 ty::ParamEnv::empty(),
350                 norm_return_ty,
351                 term_id,
352                 cause,
353             );
354             let errors = fulfillment_cx.select_all_or_error(&infcx);
355             if !errors.is_empty() {
356                 infcx.report_fulfillment_errors(&errors, None, false);
357                 error = true;
358             }
359         });
360         // now we can take the return type of the given main function
361         expected_return_type = main_fnsig.output();
362     } else {
363         // standard () main return type
364         expected_return_type = ty::Binder::dummy(tcx.mk_unit());
365     }
366
367     if error {
368         return;
369     }
370
371     let se_ty = tcx.mk_fn_ptr(expected_return_type.map_bound(|expected_return_type| {
372         tcx.mk_fn_sig(iter::empty(), expected_return_type, false, hir::Unsafety::Normal, Abi::Rust)
373     }));
374
375     require_same_types(
376         tcx,
377         &ObligationCause::new(
378             main_span,
379             main_diagnostics_hir_id,
380             ObligationCauseCode::MainFunctionType,
381         ),
382         se_ty,
383         tcx.mk_fn_ptr(main_fnsig),
384     );
385 }
386 fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) {
387     let start_def_id = start_def_id.expect_local();
388     let start_id = tcx.hir().local_def_id_to_hir_id(start_def_id);
389     let start_span = tcx.def_span(start_def_id);
390     let start_t = tcx.type_of(start_def_id);
391     match start_t.kind() {
392         ty::FnDef(..) => {
393             if let Some(Node::Item(it)) = tcx.hir().find(start_id) {
394                 if let hir::ItemKind::Fn(ref sig, ref generics, _) = it.kind {
395                     let mut error = false;
396                     if !generics.params.is_empty() {
397                         struct_span_err!(
398                             tcx.sess,
399                             generics.span,
400                             E0132,
401                             "start function is not allowed to have type parameters"
402                         )
403                         .span_label(generics.span, "start function cannot have type parameters")
404                         .emit();
405                         error = true;
406                     }
407                     if let Some(sp) = generics.where_clause.span() {
408                         struct_span_err!(
409                             tcx.sess,
410                             sp,
411                             E0647,
412                             "start function is not allowed to have a `where` clause"
413                         )
414                         .span_label(sp, "start function cannot have a `where` clause")
415                         .emit();
416                         error = true;
417                     }
418                     if let hir::IsAsync::Async = sig.header.asyncness {
419                         let span = tcx.sess.source_map().guess_head_span(it.span);
420                         struct_span_err!(
421                             tcx.sess,
422                             span,
423                             E0752,
424                             "`start` is not allowed to be `async`"
425                         )
426                         .span_label(span, "`start` is not allowed to be `async`")
427                         .emit();
428                         error = true;
429                     }
430
431                     let attrs = tcx.hir().attrs(start_id);
432                     for attr in attrs {
433                         if attr.has_name(sym::track_caller) {
434                             tcx.sess
435                                 .struct_span_err(
436                                     attr.span,
437                                     "`start` is not allowed to be `#[track_caller]`",
438                                 )
439                                 .span_label(
440                                     start_span,
441                                     "`start` is not allowed to be `#[track_caller]`",
442                                 )
443                                 .emit();
444                             error = true;
445                         }
446                     }
447
448                     if error {
449                         return;
450                     }
451                 }
452             }
453
454             let se_ty = tcx.mk_fn_ptr(ty::Binder::dummy(tcx.mk_fn_sig(
455                 [tcx.types.isize, tcx.mk_imm_ptr(tcx.mk_imm_ptr(tcx.types.u8))].iter().cloned(),
456                 tcx.types.isize,
457                 false,
458                 hir::Unsafety::Normal,
459                 Abi::Rust,
460             )));
461
462             require_same_types(
463                 tcx,
464                 &ObligationCause::new(start_span, start_id, ObligationCauseCode::StartFunctionType),
465                 se_ty,
466                 tcx.mk_fn_ptr(tcx.fn_sig(start_def_id)),
467             );
468         }
469         _ => {
470             span_bug!(start_span, "start has a non-function type: found `{}`", start_t);
471         }
472     }
473 }
474
475 fn check_for_entry_fn(tcx: TyCtxt<'_>) {
476     match tcx.entry_fn(()) {
477         Some((def_id, EntryFnType::Main)) => check_main_fn_ty(tcx, def_id),
478         Some((def_id, EntryFnType::Start)) => check_start_fn_ty(tcx, def_id),
479         _ => {}
480     }
481 }
482
483 pub fn provide(providers: &mut Providers) {
484     collect::provide(providers);
485     coherence::provide(providers);
486     check::provide(providers);
487     variance::provide(providers);
488     outlives::provide(providers);
489     impl_wf_check::provide(providers);
490     hir_wf_check::provide(providers);
491 }
492
493 pub fn check_crate(tcx: TyCtxt<'_>) -> Result<(), ErrorReported> {
494     let _prof_timer = tcx.sess.timer("type_check_crate");
495
496     // this ensures that later parts of type checking can assume that items
497     // have valid types and not error
498     // FIXME(matthewjasper) We shouldn't need to use `track_errors`.
499     tcx.sess.track_errors(|| {
500         tcx.sess.time("type_collecting", || {
501             tcx.hir().for_each_module(|module| tcx.ensure().collect_mod_item_types(module))
502         });
503     })?;
504
505     if tcx.features().rustc_attrs {
506         tcx.sess.track_errors(|| {
507             tcx.sess.time("outlives_testing", || outlives::test::test_inferred_outlives(tcx));
508         })?;
509     }
510
511     tcx.sess.track_errors(|| {
512         tcx.sess.time("impl_wf_inference", || impl_wf_check::impl_wf_check(tcx));
513     })?;
514
515     tcx.sess.track_errors(|| {
516         tcx.sess.time("coherence_checking", || coherence::check_coherence(tcx));
517     })?;
518
519     if tcx.features().rustc_attrs {
520         tcx.sess.track_errors(|| {
521             tcx.sess.time("variance_testing", || variance::test::test_variance(tcx));
522         })?;
523     }
524
525     tcx.sess.track_errors(|| {
526         tcx.sess.time("wf_checking", || check::check_wf_new(tcx));
527     })?;
528
529     // NOTE: This is copy/pasted in librustdoc/core.rs and should be kept in sync.
530     tcx.sess.time("item_types_checking", || {
531         tcx.hir().for_each_module(|module| tcx.ensure().check_mod_item_types(module))
532     });
533
534     tcx.sess.time("item_bodies_checking", || tcx.typeck_item_bodies(()));
535
536     check_unused::check_crate(tcx);
537     check_for_entry_fn(tcx);
538
539     if tcx.sess.err_count() == 0 { Ok(()) } else { Err(ErrorReported) }
540 }
541
542 /// A quasi-deprecated helper used in rustdoc and clippy to get
543 /// the type from a HIR node.
544 pub fn hir_ty_to_ty<'tcx>(tcx: TyCtxt<'tcx>, hir_ty: &hir::Ty<'_>) -> Ty<'tcx> {
545     // In case there are any projections, etc., find the "environment"
546     // def-ID that will be used to determine the traits/predicates in
547     // scope.  This is derived from the enclosing item-like thing.
548     let env_def_id = tcx.hir().get_parent_item(hir_ty.hir_id);
549     let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.to_def_id());
550     <dyn AstConv<'_>>::ast_ty_to_ty(&item_cx, hir_ty)
551 }
552
553 pub fn hir_trait_to_predicates<'tcx>(
554     tcx: TyCtxt<'tcx>,
555     hir_trait: &hir::TraitRef<'_>,
556     self_ty: Ty<'tcx>,
557 ) -> Bounds<'tcx> {
558     // In case there are any projections, etc., find the "environment"
559     // def-ID that will be used to determine the traits/predicates in
560     // scope.  This is derived from the enclosing item-like thing.
561     let env_def_id = tcx.hir().get_parent_item(hir_trait.hir_ref_id);
562     let item_cx = self::collect::ItemCtxt::new(tcx, env_def_id.to_def_id());
563     let mut bounds = Bounds::default();
564     let _ = <dyn AstConv<'_>>::instantiate_poly_trait_ref(
565         &item_cx,
566         hir_trait,
567         DUMMY_SP,
568         ty::BoundConstness::NotConst,
569         self_ty,
570         &mut bounds,
571         true,
572     );
573
574     bounds
575 }