]> git.proxmox.com Git - rustc.git/blame - src/librustc_typeck/check/mod.rs
Imported Upstream version 1.10.0+dfsg1
[rustc.git] / src / librustc_typeck / check / mod.rs
CommitLineData
85aaf69f 1// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
1a4d82fc
JJ
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# check.rs
14
15Within the check phase of type check, we check each item one at a time
16(bodies of function expressions are checked as part of the containing
17function). Inference is used to supply types wherever they are
18unknown.
19
20By far the most complex case is checking the body of a function. This
21can be broken down into several distinct phases:
22
23- gather: creates type variables to represent the type of each local
24 variable and pattern binding.
25
26- main: the main pass does the lion's share of the work: it
27 determines the types of all expressions, resolves
28 methods, checks for most invalid conditions, and so forth. In
29 some cases, where a type is unknown, it may create a type or region
30 variable and use that as the type of an expression.
31
32 In the process of checking, various constraints will be placed on
33 these type variables through the subtyping relationships requested
34 through the `demand` module. The `infer` module is in charge
35 of resolving those constraints.
36
37- regionck: after main is complete, the regionck pass goes over all
38 types looking for regions and making sure that they did not escape
39 into places they are not in scope. This may also influence the
40 final assignments of the various region variables if there is some
41 flexibility.
42
43- vtable: find and records the impls to use for each trait bound that
44 appears on a type parameter.
45
46- writeback: writes the final types within a function body, replacing
47 type variables with their final inferred types. These final types
48 are written into the `tcx.node_types` table, which should *never* contain
49 any reference to a type variable.
50
51## Intermediate types
52
53While type checking a function, the intermediate types for the
54expressions, blocks, and so forth contained within the function are
55stored in `fcx.node_types` and `fcx.item_substs`. These types
56may contain unresolved type variables. After type checking is
57complete, the functions in the writeback module are used to take the
58types from this table, resolve them, and then write them into their
59permanent home in the type context `ccx.tcx`.
60
61This means that during inferencing you should use `fcx.write_ty()`
62and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
63nodes within the function.
64
65The types of top-level items, which never contain unbound type
66variables, are stored directly into the `tcx` tables.
67
68n.b.: A type variable is not the same thing as a type parameter. A
69type variable is rather an "instance" of a type parameter: that is,
70given a generic function `fn foo<T>(t: T)`: while checking the
71function `foo`, the type `ty_param(0)` refers to the type `T`, which
72is treated in abstract. When `foo()` is called, however, `T` will be
73substituted for a fresh type variable `N`. This variable will
74eventually be resolved to some concrete type (which might itself be
75type parameter).
76
77*/
78
1a4d82fc 79pub use self::Expectation::*;
d9579d0f 80pub use self::compare_method::{compare_impl_method, compare_const_impl};
1a4d82fc
JJ
81use self::TupleArgumentsFlag::*;
82
a7813a04
XL
83use astconv::{AstConv, ast_region_to_region, PathParamMode};
84use check::_match::PatCtxt;
9cc50fc6 85use dep_graph::DepNode;
85aaf69f 86use fmt_macros::{Parser, Piece, Position};
92a42be0 87use middle::cstore::LOCAL_CRATE;
54a0048b
SL
88use hir::def::{self, Def};
89use hir::def_id::DefId;
a7813a04 90use rustc::infer::{self, InferCtxt, InferOk, TypeOrigin, TypeTrace, type_variable};
54a0048b
SL
91use hir::pat_util::{self, pat_id_map};
92use rustc::ty::subst::{self, Subst, Substs, VecPerParamSpace, ParamSpace};
a7813a04 93use rustc::traits::{self, ProjectionMode};
54a0048b
SL
94use rustc::ty::{GenericPredicates, TypeScheme};
95use rustc::ty::{ParamTy, ParameterEnvironment};
96use rustc::ty::{LvaluePreference, NoPreference, PreferMutLvalue};
97use rustc::ty::{self, ToPolyTraitRef, Ty, TyCtxt, Visibility};
98use rustc::ty::{MethodCall, MethodCallee};
99use rustc::ty::adjustment;
a7813a04 100use rustc::ty::fold::TypeFoldable;
54a0048b 101use rustc::ty::util::{Representability, IntTypeExt};
c1a9b12d
SL
102use require_c_abi_if_variadic;
103use rscope::{ElisionFailureInfo, RegionScope};
7453a54e 104use session::{Session, CompileResult};
e9174d1e 105use {CrateCtxt, lookup_full_def};
1a4d82fc 106use TypeAndSubsts;
1a4d82fc 107use lint;
c34b1796 108use util::common::{block_query, ErrorReported, indenter, loop_query};
1a4d82fc
JJ
109use util::nodemap::{DefIdMap, FnvHashMap, NodeMap};
110
111use std::cell::{Cell, Ref, RefCell};
e9174d1e 112use std::collections::{HashSet};
1a4d82fc 113use std::mem::replace;
a7813a04 114use std::ops::Deref;
7453a54e 115use syntax::abi::Abi;
e9174d1e 116use syntax::ast;
b039eaaf
SL
117use syntax::attr;
118use syntax::attr::AttrMetaMethods;
119use syntax::codemap::{self, Span, Spanned};
9cc50fc6 120use syntax::errors::DiagnosticBuilder;
a7813a04 121use syntax::parse::token::{self, InternedString, keywords};
1a4d82fc 122use syntax::ptr::P;
9cc50fc6 123use syntax::util::lev_distance::find_best_match_for_name;
e9174d1e 124
54a0048b
SL
125use rustc::hir::intravisit::{self, Visitor};
126use rustc::hir::{self, PatKind};
127use rustc::hir::print as pprust;
b039eaaf 128use rustc_back::slice;
54a0048b 129use rustc_const_eval::eval_repeat_count;
1a4d82fc
JJ
130
131mod assoc;
85aaf69f 132pub mod dropck;
1a4d82fc 133pub mod _match;
1a4d82fc 134pub mod writeback;
1a4d82fc 135pub mod regionck;
85aaf69f 136pub mod coercion;
1a4d82fc
JJ
137pub mod demand;
138pub mod method;
139mod upvar;
e9174d1e 140mod wfcheck;
9346a6ac 141mod cast;
1a4d82fc
JJ
142mod closure;
143mod callee;
85aaf69f 144mod compare_method;
e9174d1e 145mod intrinsic;
c34b1796 146mod op;
1a4d82fc 147
1a4d82fc
JJ
148/// closures defined within the function. For example:
149///
150/// fn foo() {
151/// bar(move|| { ... })
152/// }
153///
154/// Here, the function `foo()` and the closure passed to
155/// `bar()` will each have their own `FnCtxt`, but they will
156/// share the inherited fields.
a7813a04
XL
157pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
158 ccx: &'a CrateCtxt<'a, 'gcx>,
159 infcx: InferCtxt<'a, 'gcx, 'tcx>,
1a4d82fc 160 locals: RefCell<NodeMap<Ty<'tcx>>>,
1a4d82fc 161
7453a54e
SL
162 fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
163
85aaf69f
SL
164 // When we process a call like `c()` where `c` is a closure type,
165 // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
166 // `FnOnce` closure. In that case, we defer full resolution of the
167 // call until upvar inference can kick in and make the
168 // decision. We keep these deferred resolutions grouped by the
169 // def-id of the closure, so that once we decide, we can easily go
170 // back and process them.
a7813a04 171 deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
c34b1796 172
9346a6ac 173 deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
85aaf69f
SL
174}
175
a7813a04
XL
176impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
177 type Target = InferCtxt<'a, 'gcx, 'tcx>;
178 fn deref(&self) -> &Self::Target {
179 &self.infcx
180 }
181}
182
183trait DeferredCallResolution<'gcx, 'tcx> {
184 fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
1a4d82fc
JJ
185}
186
a7813a04 187type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
85aaf69f 188
1a4d82fc
JJ
189/// When type-checking an expression, we propagate downward
190/// whatever type hint we are able in the form of an `Expectation`.
62682a34 191#[derive(Copy, Clone, Debug)]
c34b1796 192pub enum Expectation<'tcx> {
1a4d82fc
JJ
193 /// We know nothing about what type this expression should have.
194 NoExpectation,
195
196 /// This expression should have the type given (or some subtype)
197 ExpectHasType(Ty<'tcx>),
198
199 /// This expression will be cast to the `Ty`
200 ExpectCastableToType(Ty<'tcx>),
201
202 /// This rvalue expression will be wrapped in `&` or `Box` and coerced
203 /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
204 ExpectRvalueLikeUnsized(Ty<'tcx>),
205}
206
a7813a04 207impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
1a4d82fc
JJ
208 // Disregard "castable to" expectations because they
209 // can lead us astray. Consider for example `if cond
210 // {22} else {c} as u8` -- if we propagate the
211 // "castable to u8" constraint to 22, it will pick the
212 // type 22u8, which is overly constrained (c might not
213 // be a u8). In effect, the problem is that the
214 // "castable to" expectation is not the tightest thing
215 // we can say, so we want to drop it in this case.
216 // The tightest thing we can say is "must unify with
217 // else branch". Note that in the case of a "has type"
218 // constraint, this limitation does not hold.
219
220 // If the expected type is just a type variable, then don't use
221 // an expected type. Otherwise, we might write parts of the type
222 // when checking the 'then' block which are incompatible with the
223 // 'else' branch.
a7813a04 224 fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
1a4d82fc
JJ
225 match *self {
226 ExpectHasType(ety) => {
a7813a04 227 let ety = fcx.shallow_resolve(ety);
c1a9b12d 228 if !ety.is_ty_var() {
1a4d82fc
JJ
229 ExpectHasType(ety)
230 } else {
231 NoExpectation
232 }
233 }
234 ExpectRvalueLikeUnsized(ety) => {
235 ExpectRvalueLikeUnsized(ety)
236 }
237 _ => NoExpectation
238 }
239 }
a7813a04
XL
240
241 /// Provide an expectation for an rvalue expression given an *optional*
242 /// hint, which is not required for type safety (the resulting type might
243 /// be checked higher up, as is the case with `&expr` and `box expr`), but
244 /// is useful in determining the concrete type.
245 ///
246 /// The primary use case is where the expected type is a fat pointer,
247 /// like `&[isize]`. For example, consider the following statement:
248 ///
249 /// let x: &[isize] = &[1, 2, 3];
250 ///
251 /// In this case, the expected type for the `&[1, 2, 3]` expression is
252 /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
253 /// expectation `ExpectHasType([isize])`, that would be too strong --
254 /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
255 /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
256 /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
257 /// which still is useful, because it informs integer literals and the like.
258 /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
259 /// for examples of where this comes up,.
260 fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
261 match fcx.tcx.struct_tail(ty).sty {
262 ty::TySlice(_) | ty::TyStr | ty::TyTrait(..) => {
263 ExpectRvalueLikeUnsized(ty)
264 }
265 _ => ExpectHasType(ty)
266 }
267 }
268
269 // Resolves `expected` by a single level if it is a variable. If
270 // there is no expected type or resolution is not possible (e.g.,
271 // no constraints yet present), just returns `None`.
272 fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
273 match self {
274 NoExpectation => {
275 NoExpectation
276 }
277 ExpectCastableToType(t) => {
278 ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
279 }
280 ExpectHasType(t) => {
281 ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
282 }
283 ExpectRvalueLikeUnsized(t) => {
284 ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
285 }
286 }
287 }
288
289 fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
290 match self.resolve(fcx) {
291 NoExpectation => None,
292 ExpectCastableToType(ty) |
293 ExpectHasType(ty) |
294 ExpectRvalueLikeUnsized(ty) => Some(ty),
295 }
296 }
297
298 fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
299 match self.resolve(fcx) {
300 ExpectHasType(ty) => Some(ty),
301 _ => None
302 }
303 }
1a4d82fc
JJ
304}
305
306#[derive(Copy, Clone)]
307pub struct UnsafetyState {
308 pub def: ast::NodeId,
e9174d1e 309 pub unsafety: hir::Unsafety,
c1a9b12d 310 pub unsafe_push_count: u32,
1a4d82fc
JJ
311 from_fn: bool
312}
313
314impl UnsafetyState {
e9174d1e 315 pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
c1a9b12d 316 UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
1a4d82fc
JJ
317 }
318
e9174d1e 319 pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
1a4d82fc
JJ
320 match self.unsafety {
321 // If this unsafe, then if the outer function was already marked as
322 // unsafe we shouldn't attribute the unsafe'ness to the block. This
323 // way the block can be warned about instead of ignoring this
324 // extraneous block (functions are never warned about).
e9174d1e 325 hir::Unsafety::Unsafe if self.from_fn => *self,
1a4d82fc
JJ
326
327 unsafety => {
c1a9b12d 328 let (unsafety, def, count) = match blk.rules {
e9174d1e 329 hir::PushUnsafeBlock(..) =>
c1a9b12d 330 (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
e9174d1e 331 hir::PopUnsafeBlock(..) =>
c1a9b12d 332 (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
e9174d1e
SL
333 hir::UnsafeBlock(..) =>
334 (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
b039eaaf 335 hir::DefaultBlock | hir::PushUnstableBlock | hir:: PopUnstableBlock =>
c1a9b12d 336 (unsafety, self.def, self.unsafe_push_count),
1a4d82fc
JJ
337 };
338 UnsafetyState{ def: def,
c1a9b12d
SL
339 unsafety: unsafety,
340 unsafe_push_count: count,
341 from_fn: false }
1a4d82fc
JJ
342 }
343 }
344 }
345}
346
1a4d82fc 347#[derive(Clone)]
a7813a04
XL
348pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
349 ast_ty_to_ty_cache: RefCell<NodeMap<Ty<'tcx>>>,
350
1a4d82fc
JJ
351 body_id: ast::NodeId,
352
353 // This flag is set to true if, during the writeback phase, we encounter
354 // a type error in this function.
355 writeback_errors: Cell<bool>,
356
357 // Number of errors that had been reported when we started
358 // checking this function. On exit, if we find that *more* errors
359 // have been reported, we will skip regionck and other work that
360 // expects the types within the function to be consistent.
c34b1796 361 err_count_on_creation: usize,
1a4d82fc
JJ
362
363 ret_ty: ty::FnOutput<'tcx>,
364
365 ps: RefCell<UnsafetyState>,
366
a7813a04
XL
367 inh: &'a Inherited<'a, 'gcx, 'tcx>,
368}
369
370impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
371 type Target = Inherited<'a, 'gcx, 'tcx>;
372 fn deref(&self) -> &Self::Target {
373 &self.inh
374 }
375}
1a4d82fc 376
a7813a04
XL
377/// Helper type of a temporary returned by ccx.inherited(...).
378/// Necessary because we can't write the following bound:
379/// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
380pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
381 ccx: &'a CrateCtxt<'a, 'gcx>,
382 infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>
1a4d82fc
JJ
383}
384
a7813a04
XL
385impl<'a, 'gcx, 'tcx> CrateCtxt<'a, 'gcx> {
386 pub fn inherited(&'a self, param_env: Option<ty::ParameterEnvironment<'gcx>>)
387 -> InheritedBuilder<'a, 'gcx, 'tcx> {
388 InheritedBuilder {
389 ccx: self,
390 infcx: self.tcx.infer_ctxt(Some(ty::Tables::empty()),
391 param_env,
392 ProjectionMode::AnyFinal)
1a4d82fc
JJ
393 }
394 }
a7813a04
XL
395}
396
397impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
398 fn enter<F, R>(&'tcx mut self, f: F) -> R
399 where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
400 {
401 let ccx = self.ccx;
402 self.infcx.enter(|infcx| {
403 f(Inherited {
404 ccx: ccx,
405 infcx: infcx,
406 fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
407 locals: RefCell::new(NodeMap()),
408 deferred_call_resolutions: RefCell::new(DefIdMap()),
409 deferred_cast_checks: RefCell::new(Vec::new()),
410 })
411 })
412 }
413}
1a4d82fc 414
a7813a04 415impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
1a4d82fc 416 fn normalize_associated_types_in<T>(&self,
1a4d82fc
JJ
417 span: Span,
418 body_id: ast::NodeId,
419 value: &T)
420 -> T
9cc50fc6 421 where T : TypeFoldable<'tcx>
1a4d82fc 422 {
a7813a04 423 assoc::normalize_associated_types_in(self,
7453a54e 424 &mut self.fulfillment_cx.borrow_mut(),
c1a9b12d 425 span,
1a4d82fc
JJ
426 body_id,
427 value)
428 }
429
430}
431
1a4d82fc 432struct CheckItemTypesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
9346a6ac 433struct CheckItemBodiesVisitor<'a, 'tcx: 'a> { ccx: &'a CrateCtxt<'a, 'tcx> }
1a4d82fc 434
85aaf69f 435impl<'a, 'tcx> Visitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
e9174d1e 436 fn visit_item(&mut self, i: &'tcx hir::Item) {
9346a6ac 437 check_item_type(self.ccx, i);
92a42be0 438 intravisit::walk_item(self, i);
1a4d82fc
JJ
439 }
440
e9174d1e 441 fn visit_ty(&mut self, t: &'tcx hir::Ty) {
1a4d82fc 442 match t.node {
e9174d1e 443 hir::TyFixedLengthVec(_, ref expr) => {
7453a54e 444 check_const_in_type(self.ccx, &expr, self.ccx.tcx.types.usize);
1a4d82fc
JJ
445 }
446 _ => {}
447 }
448
92a42be0 449 intravisit::walk_ty(self, t);
1a4d82fc
JJ
450 }
451}
452
9346a6ac 453impl<'a, 'tcx> Visitor<'tcx> for CheckItemBodiesVisitor<'a, 'tcx> {
e9174d1e 454 fn visit_item(&mut self, i: &'tcx hir::Item) {
9346a6ac 455 check_item_body(self.ccx, i);
9346a6ac
AL
456 }
457}
458
7453a54e
SL
459pub fn check_wf_new(ccx: &CrateCtxt) -> CompileResult {
460 ccx.tcx.sess.track_errors(|| {
9cc50fc6
SL
461 let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(ccx);
462 ccx.tcx.visit_all_items_in_krate(DepNode::WfCheck, &mut visit);
7453a54e 463 })
e9174d1e 464}
c34b1796 465
7453a54e
SL
466pub fn check_item_types(ccx: &CrateCtxt) -> CompileResult {
467 ccx.tcx.sess.track_errors(|| {
9cc50fc6
SL
468 let mut visit = CheckItemTypesVisitor { ccx: ccx };
469 ccx.tcx.visit_all_items_in_krate(DepNode::TypeckItemType, &mut visit);
7453a54e 470 })
e9174d1e
SL
471}
472
7453a54e
SL
473pub fn check_item_bodies(ccx: &CrateCtxt) -> CompileResult {
474 ccx.tcx.sess.track_errors(|| {
9cc50fc6
SL
475 let mut visit = CheckItemBodiesVisitor { ccx: ccx };
476 ccx.tcx.visit_all_items_in_krate(DepNode::TypeckItemBody, &mut visit);
7453a54e 477 })
e9174d1e 478}
9346a6ac 479
7453a54e
SL
480pub fn check_drop_impls(ccx: &CrateCtxt) -> CompileResult {
481 ccx.tcx.sess.track_errors(|| {
9cc50fc6
SL
482 let _task = ccx.tcx.dep_graph.in_task(DepNode::Dropck);
483 let drop_trait = match ccx.tcx.lang_items.drop_trait() {
484 Some(id) => ccx.tcx.lookup_trait_def(id), None => { return }
485 };
486 drop_trait.for_each_impl(ccx.tcx, |drop_impl_did| {
487 let _task = ccx.tcx.dep_graph.in_task(DepNode::DropckImpl(drop_impl_did));
488 if drop_impl_did.is_local() {
a7813a04 489 match dropck::check_drop_impl(ccx, drop_impl_did) {
9cc50fc6
SL
490 Ok(()) => {}
491 Err(()) => {
492 assert!(ccx.tcx.sess.has_errors());
493 }
c34b1796
AL
494 }
495 }
9cc50fc6 496 });
7453a54e 497 })
1a4d82fc
JJ
498}
499
500fn check_bare_fn<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
e9174d1e
SL
501 decl: &'tcx hir::FnDecl,
502 body: &'tcx hir::Block,
85aaf69f
SL
503 fn_id: ast::NodeId,
504 fn_span: Span,
1a4d82fc 505 raw_fty: Ty<'tcx>,
a7813a04 506 param_env: ty::ParameterEnvironment<'tcx>)
85aaf69f 507{
a7813a04
XL
508 let fn_ty = match raw_fty.sty {
509 ty::TyFnDef(_, _, f) => f,
54a0048b 510 _ => span_bug!(body.span, "check_bare_fn: function type expected")
a7813a04
XL
511 };
512
513 ccx.inherited(Some(param_env)).enter(|inh| {
514 // Compute the fty from point of view of inside fn.
515 let fn_scope = inh.tcx.region_maps.call_site_extent(fn_id, body.id);
516 let fn_sig =
517 fn_ty.sig.subst(inh.tcx, &inh.parameter_environment.free_substs);
518 let fn_sig =
519 inh.tcx.liberate_late_bound_regions(fn_scope, &fn_sig);
520 let fn_sig =
521 inh.normalize_associated_types_in(body.span, body.id, &fn_sig);
522
523 let fcx = check_fn(&inh, fn_ty.unsafety, fn_id, &fn_sig, decl, fn_id, body);
524
525 fcx.select_all_obligations_and_apply_defaults();
526 fcx.closure_analyze_fn(body);
527 fcx.select_obligations_where_possible();
528 fcx.check_casts();
529 fcx.select_all_obligations_or_error(); // Casts can introduce new obligations.
530
531 fcx.regionck_fn(fn_id, fn_span, decl, body);
532 fcx.resolve_type_vars_in_fn(decl, body);
533 });
1a4d82fc
JJ
534}
535
a7813a04
XL
536struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
537 fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
1a4d82fc
JJ
538}
539
a7813a04 540impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
1a4d82fc
JJ
541 fn assign(&mut self, _span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
542 match ty_opt {
543 None => {
544 // infer the variable's type
a7813a04
XL
545 let var_ty = self.fcx.next_ty_var();
546 self.fcx.locals.borrow_mut().insert(nid, var_ty);
1a4d82fc
JJ
547 var_ty
548 }
549 Some(typ) => {
550 // take type that the user specified
a7813a04 551 self.fcx.locals.borrow_mut().insert(nid, typ);
1a4d82fc
JJ
552 typ
553 }
554 }
555 }
556}
557
a7813a04 558impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
1a4d82fc 559 // Add explicitly-declared locals.
a7813a04 560 fn visit_local(&mut self, local: &'gcx hir::Local) {
1a4d82fc 561 let o_ty = match local.ty {
7453a54e 562 Some(ref ty) => Some(self.fcx.to_ty(&ty)),
1a4d82fc
JJ
563 None => None
564 };
565 self.assign(local.span, local.id, o_ty);
62682a34
SL
566 debug!("Local variable {:?} is assigned type {}",
567 local.pat,
a7813a04
XL
568 self.fcx.ty_to_string(
569 self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
92a42be0 570 intravisit::walk_local(self, local);
1a4d82fc
JJ
571 }
572
573 // Add pattern bindings.
a7813a04 574 fn visit_pat(&mut self, p: &'gcx hir::Pat) {
7453a54e 575 if let PatKind::Ident(_, ref path1, _) = p.node {
a7813a04 576 if pat_util::pat_is_binding(&self.fcx.tcx.def_map.borrow(), p) {
1a4d82fc
JJ
577 let var_ty = self.assign(p.span, p.id, None);
578
579 self.fcx.require_type_is_sized(var_ty, p.span,
580 traits::VariableType(p.id));
581
62682a34 582 debug!("Pattern binding {} is assigned to {} with type {:?}",
c1a9b12d 583 path1.node,
a7813a04
XL
584 self.fcx.ty_to_string(
585 self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
62682a34 586 var_ty);
1a4d82fc
JJ
587 }
588 }
92a42be0 589 intravisit::walk_pat(self, p);
1a4d82fc
JJ
590 }
591
a7813a04 592 fn visit_block(&mut self, b: &'gcx hir::Block) {
1a4d82fc
JJ
593 // non-obvious: the `blk` variable maps to region lb, so
594 // we have to keep this up-to-date. This
595 // is... unfortunate. It'd be nice to not need this.
92a42be0 596 intravisit::walk_block(self, b);
1a4d82fc
JJ
597 }
598
599 // Since an expr occurs as part of the type fixed size arrays we
600 // need to record the type for that node
a7813a04 601 fn visit_ty(&mut self, t: &'gcx hir::Ty) {
1a4d82fc 602 match t.node {
e9174d1e 603 hir::TyFixedLengthVec(ref ty, ref count_expr) => {
7453a54e 604 self.visit_ty(&ty);
a7813a04 605 self.fcx.check_expr_with_hint(&count_expr, self.fcx.tcx.types.usize);
1a4d82fc 606 }
b039eaaf 607 hir::TyBareFn(ref function_declaration) => {
92a42be0 608 intravisit::walk_fn_decl_nopat(self, &function_declaration.decl);
b039eaaf
SL
609 walk_list!(self, visit_lifetime_def, &function_declaration.lifetimes);
610 }
92a42be0 611 _ => intravisit::walk_ty(self, t)
1a4d82fc
JJ
612 }
613 }
614
92a42be0 615 // Don't descend into the bodies of nested closures
a7813a04
XL
616 fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
617 _: &'gcx hir::Block, _: Span, _: ast::NodeId) { }
1a4d82fc
JJ
618}
619
620/// Helper used by check_bare_fn and check_expr_fn. Does the grungy work of checking a function
621/// body and returns the function context used for that purpose, since in the case of a fn item
622/// there is still a bit more to do.
623///
624/// * ...
625/// * inherited: other fields inherited from the enclosing fn (if any)
a7813a04
XL
626fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
627 unsafety: hir::Unsafety,
628 unsafety_id: ast::NodeId,
629 fn_sig: &ty::FnSig<'tcx>,
630 decl: &'gcx hir::FnDecl,
631 fn_id: ast::NodeId,
632 body: &'gcx hir::Block)
633 -> FnCtxt<'a, 'gcx, 'tcx>
1a4d82fc 634{
a7813a04 635 let tcx = inherited.tcx;
1a4d82fc 636
c34b1796 637 let arg_tys = &fn_sig.inputs;
1a4d82fc
JJ
638 let ret_ty = fn_sig.output;
639
62682a34
SL
640 debug!("check_fn(arg_tys={:?}, ret_ty={:?}, fn_id={})",
641 arg_tys,
642 ret_ty,
1a4d82fc
JJ
643 fn_id);
644
645 // Create the function context. This is either derived from scratch or,
646 // in the case of function expressions, based on the outer context.
a7813a04
XL
647 let fcx = FnCtxt::new(inherited, ret_ty, body.id);
648 *fcx.ps.borrow_mut() = UnsafetyState::function(unsafety, unsafety_id);
1a4d82fc 649
1a4d82fc
JJ
650 if let ty::FnConverging(ret_ty) = ret_ty {
651 fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
1a4d82fc
JJ
652 }
653
92a42be0 654 debug!("fn-sig-map: fn_id={} fn_sig={:?}", fn_id, fn_sig);
1a4d82fc 655
92a42be0 656 inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig.clone());
1a4d82fc
JJ
657
658 {
659 let mut visit = GatherLocalsVisitor { fcx: &fcx, };
660
661 // Add formal parameters.
62682a34 662 for (arg_ty, input) in arg_tys.iter().zip(&decl.inputs) {
e9174d1e
SL
663 // The type of the argument must be well-formed.
664 //
665 // NB -- this is now checked in wfcheck, but that
666 // currently only results in warnings, so we issue an
667 // old-style WF obligation here so that we still get the
668 // errors that we used to get.
669 fcx.register_old_wf_obligation(arg_ty, input.ty.span, traits::MiscObligation);
670
1a4d82fc
JJ
671 // Create type variables for each argument.
672 pat_util::pat_bindings(
673 &tcx.def_map,
7453a54e 674 &input.pat,
1a4d82fc
JJ
675 |_bm, pat_id, sp, _path| {
676 let var_ty = visit.assign(sp, pat_id, None);
677 fcx.require_type_is_sized(var_ty, sp,
678 traits::VariableType(pat_id));
679 });
680
681 // Check the pattern.
a7813a04 682 let pcx = PatCtxt {
1a4d82fc 683 fcx: &fcx,
7453a54e 684 map: pat_id_map(&tcx.def_map, &input.pat),
1a4d82fc 685 };
a7813a04 686 pcx.check_pat(&input.pat, *arg_ty);
1a4d82fc
JJ
687 }
688
689 visit.visit_block(body);
690 }
691
a7813a04 692 fcx.check_block_with_expected(body, match ret_ty {
1a4d82fc
JJ
693 ty::FnConverging(result_type) => ExpectHasType(result_type),
694 ty::FnDiverging => NoExpectation
695 });
696
62682a34
SL
697 for (input, arg) in decl.inputs.iter().zip(arg_tys) {
698 fcx.write_ty(input.id, arg);
1a4d82fc
JJ
699 }
700
701 fcx
702}
703
704pub fn check_struct(ccx: &CrateCtxt, id: ast::NodeId, span: Span) {
705 let tcx = ccx.tcx;
706
707 check_representable(tcx, span, id, "struct");
1a4d82fc 708
b039eaaf 709 if tcx.lookup_simd(ccx.tcx.map.local_def_id(id)) {
1a4d82fc
JJ
710 check_simd(tcx, span, id);
711 }
712}
713
e9174d1e 714pub fn check_item_type<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx hir::Item) {
b039eaaf 715 debug!("check_item_type(it.id={}, it.name={})",
1a4d82fc 716 it.id,
b039eaaf 717 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(it.id)));
1a4d82fc 718 let _indenter = indenter();
1a4d82fc 719 match it.node {
9346a6ac 720 // Consts can play a role in type-checking, so they are included here.
e9174d1e 721 hir::ItemStatic(_, _, ref e) |
7453a54e 722 hir::ItemConst(_, ref e) => check_const(ccx, it.span, &e, it.id),
e9174d1e 723 hir::ItemEnum(ref enum_definition, _) => {
1a4d82fc
JJ
724 check_enum_variants(ccx,
725 it.span,
c34b1796 726 &enum_definition.variants,
1a4d82fc
JJ
727 it.id);
728 }
e9174d1e
SL
729 hir::ItemFn(..) => {} // entirely within check_item_body
730 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
b039eaaf 731 debug!("ItemImpl {} with id {}", it.name, it.id);
54a0048b
SL
732 let impl_def_id = ccx.tcx.map.local_def_id(it.id);
733 match ccx.tcx.impl_trait_ref(impl_def_id) {
1a4d82fc 734 Some(impl_trait_ref) => {
a7813a04
XL
735 let trait_def_id = impl_trait_ref.def_id;
736
737 check_impl_items_against_trait(ccx,
738 it.span,
739 impl_def_id,
740 &impl_trait_ref,
741 impl_items);
742 check_on_unimplemented(
743 ccx,
744 &ccx.tcx.lookup_trait_def(trait_def_id).generics,
745 it,
746 ccx.tcx.item_name(trait_def_id));
1a4d82fc
JJ
747 }
748 None => { }
749 }
1a4d82fc 750 }
a7813a04
XL
751 hir::ItemTrait(..) => {
752 let def_id = ccx.tcx.map.local_def_id(it.id);
753 let generics = &ccx.tcx.lookup_trait_def(def_id).generics;
754 check_on_unimplemented(ccx, generics, it, it.name);
1a4d82fc 755 }
e9174d1e 756 hir::ItemStruct(..) => {
1a4d82fc
JJ
757 check_struct(ccx, it.id, it.span);
758 }
92a42be0 759 hir::ItemTy(_, ref generics) => {
c1a9b12d 760 let pty_ty = ccx.tcx.node_id_to_type(it.id);
92a42be0 761 check_bounds_are_used(ccx, &generics.ty_params, pty_ty);
1a4d82fc 762 }
e9174d1e 763 hir::ItemForeignMod(ref m) => {
7453a54e 764 if m.abi == Abi::RustIntrinsic {
85aaf69f 765 for item in &m.items {
92a42be0 766 intrinsic::check_intrinsic_type(ccx, item);
e9174d1e 767 }
7453a54e 768 } else if m.abi == Abi::PlatformIntrinsic {
e9174d1e 769 for item in &m.items {
92a42be0 770 intrinsic::check_platform_intrinsic_type(ccx, item);
1a4d82fc
JJ
771 }
772 } else {
85aaf69f 773 for item in &m.items {
b039eaaf 774 let pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(item.id));
1a4d82fc 775 if !pty.generics.types.is_empty() {
9cc50fc6 776 let mut err = struct_span_err!(ccx.tcx.sess, item.span, E0044,
1a4d82fc 777 "foreign items may not have type parameters");
9cc50fc6 778 span_help!(&mut err, item.span,
e9174d1e
SL
779 "consider using specialization instead of \
780 type parameters");
9cc50fc6 781 err.emit();
1a4d82fc
JJ
782 }
783
e9174d1e 784 if let hir::ForeignItemFn(ref fn_decl, _) = item.node {
c1a9b12d 785 require_c_abi_if_variadic(ccx.tcx, fn_decl, m.abi, item.span);
1a4d82fc
JJ
786 }
787 }
788 }
789 }
790 _ => {/* nothing to do */ }
791 }
792}
793
e9174d1e 794pub fn check_item_body<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>, it: &'tcx hir::Item) {
b039eaaf 795 debug!("check_item_body(it.id={}, it.name={})",
9346a6ac 796 it.id,
b039eaaf 797 ccx.tcx.item_path_str(ccx.tcx.map.local_def_id(it.id)));
9346a6ac
AL
798 let _indenter = indenter();
799 match it.node {
e9174d1e 800 hir::ItemFn(ref decl, _, _, _, _, ref body) => {
b039eaaf 801 let fn_pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(it.id));
9346a6ac 802 let param_env = ParameterEnvironment::for_item(ccx.tcx, it.id);
7453a54e 803 check_bare_fn(ccx, &decl, &body, it.id, it.span, fn_pty.ty, param_env);
9346a6ac 804 }
e9174d1e 805 hir::ItemImpl(_, _, _, _, _, ref impl_items) => {
b039eaaf 806 debug!("ItemImpl {} with id {}", it.name, it.id);
9346a6ac 807
b039eaaf 808 let impl_pty = ccx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(it.id));
9346a6ac
AL
809
810 for impl_item in impl_items {
811 match impl_item.node {
92a42be0 812 hir::ImplItemKind::Const(_, ref expr) => {
7453a54e 813 check_const(ccx, impl_item.span, &expr, impl_item.id)
d9579d0f 814 }
92a42be0 815 hir::ImplItemKind::Method(ref sig, ref body) => {
9346a6ac
AL
816 check_method_body(ccx, &impl_pty.generics, sig, body,
817 impl_item.id, impl_item.span);
818 }
92a42be0 819 hir::ImplItemKind::Type(_) => {
9346a6ac
AL
820 // Nothing to do here.
821 }
822 }
823 }
824 }
e9174d1e 825 hir::ItemTrait(_, _, _, ref trait_items) => {
b039eaaf 826 let trait_def = ccx.tcx.lookup_trait_def(ccx.tcx.map.local_def_id(it.id));
9346a6ac
AL
827 for trait_item in trait_items {
828 match trait_item.node {
e9174d1e 829 hir::ConstTraitItem(_, Some(ref expr)) => {
7453a54e 830 check_const(ccx, trait_item.span, &expr, trait_item.id)
9346a6ac 831 }
e9174d1e 832 hir::MethodTraitItem(ref sig, Some(ref body)) => {
62682a34
SL
833 check_trait_fn_not_const(ccx, trait_item.span, sig.constness);
834
9346a6ac
AL
835 check_method_body(ccx, &trait_def.generics, sig, body,
836 trait_item.id, trait_item.span);
837 }
e9174d1e 838 hir::MethodTraitItem(ref sig, None) => {
62682a34
SL
839 check_trait_fn_not_const(ccx, trait_item.span, sig.constness);
840 }
e9174d1e
SL
841 hir::ConstTraitItem(_, None) |
842 hir::TypeTraitItem(..) => {
9346a6ac
AL
843 // Nothing to do.
844 }
845 }
846 }
847 }
848 _ => {/* nothing to do */ }
849 }
850}
851
62682a34
SL
852fn check_trait_fn_not_const<'a,'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
853 span: Span,
e9174d1e 854 constness: hir::Constness)
62682a34
SL
855{
856 match constness {
e9174d1e 857 hir::Constness::NotConst => {
62682a34
SL
858 // good
859 }
e9174d1e 860 hir::Constness::Const => {
62682a34
SL
861 span_err!(ccx.tcx.sess, span, E0379, "trait fns cannot be declared const");
862 }
863 }
864}
865
a7813a04
XL
866fn check_on_unimplemented<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
867 generics: &ty::Generics,
868 item: &hir::Item,
869 name: ast::Name) {
85aaf69f
SL
870 if let Some(ref attr) = item.attrs.iter().find(|a| {
871 a.check_name("rustc_on_unimplemented")
872 }) {
873 if let Some(ref istring) = attr.value_str() {
874 let parser = Parser::new(&istring);
a7813a04 875 let types = &generics.types;
85aaf69f
SL
876 for token in parser {
877 match token {
878 Piece::String(_) => (), // Normal string, no need to check it
879 Piece::NextArgument(a) => match a.position {
880 // `{Self}` is allowed
881 Position::ArgumentNamed(s) if s == "Self" => (),
882 // So is `{A}` if A is a type parameter
883 Position::ArgumentNamed(s) => match types.iter().find(|t| {
b039eaaf 884 t.name.as_str() == s
85aaf69f
SL
885 }) {
886 Some(_) => (),
887 None => {
888 span_err!(ccx.tcx.sess, attr.span, E0230,
889 "there is no type parameter \
890 {} on trait {}",
a7813a04 891 s, name);
85aaf69f
SL
892 }
893 },
894 // `{:1}` and `{}` are not to be used
895 Position::ArgumentIs(_) | Position::ArgumentNext => {
896 span_err!(ccx.tcx.sess, attr.span, E0231,
897 "only named substitution \
898 parameters are allowed");
899 }
900 }
901 }
902 }
903 } else {
904 span_err!(ccx.tcx.sess, attr.span, E0232,
905 "this attribute must have a value, \
906 eg `#[rustc_on_unimplemented = \"foo\"]`")
907 }
908 }
909}
910
1a4d82fc
JJ
911/// Type checks a method body.
912///
913/// # Parameters
914///
915/// * `item_generics`: generics defined on the impl/trait that contains
916/// the method
917/// * `self_bound`: bound for the `Self` type parameter, if any
918/// * `method`: the method definition
919fn check_method_body<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
920 item_generics: &ty::Generics<'tcx>,
e9174d1e
SL
921 sig: &'tcx hir::MethodSig,
922 body: &'tcx hir::Block,
c34b1796 923 id: ast::NodeId, span: Span) {
62682a34
SL
924 debug!("check_method_body(item_generics={:?}, id={})",
925 item_generics, id);
c34b1796
AL
926 let param_env = ParameterEnvironment::for_item(ccx.tcx, id);
927
c1a9b12d 928 let fty = ccx.tcx.node_id_to_type(id);
62682a34 929 debug!("check_method_body: fty={:?}", fty);
1a4d82fc 930
c34b1796 931 check_bare_fn(ccx, &sig.decl, body, id, span, fty, param_env);
1a4d82fc
JJ
932}
933
a7813a04
XL
934fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
935 impl_item: &hir::ImplItem,
936 parent_impl: DefId)
54a0048b
SL
937{
938 let mut err = struct_span_err!(
939 tcx.sess, impl_item.span, E0520,
940 "item `{}` is provided by an `impl` that specializes \
941 another, but the item in the parent `impl` is not \
942 marked `default` and so it cannot be specialized.",
943 impl_item.name);
944
945 match tcx.span_of_impl(parent_impl) {
946 Ok(span) => {
947 err.span_note(span, "parent implementation is here:");
948 }
949 Err(cname) => {
950 err.note(&format!("parent implementation is in crate `{}`", cname));
951 }
952 }
953
954 err.emit();
955}
956
a7813a04
XL
957fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
958 trait_def: &ty::TraitDef<'tcx>,
959 impl_id: DefId,
960 impl_item: &hir::ImplItem)
54a0048b
SL
961{
962 let ancestors = trait_def.ancestors(impl_id);
963
964 let parent = match impl_item.node {
965 hir::ImplItemKind::Const(..) => {
966 ancestors.const_defs(tcx, impl_item.name).skip(1).next()
967 .map(|node_item| node_item.map(|parent| parent.defaultness))
968 }
969 hir::ImplItemKind::Method(..) => {
970 ancestors.fn_defs(tcx, impl_item.name).skip(1).next()
971 .map(|node_item| node_item.map(|parent| parent.defaultness))
972
973 }
974 hir::ImplItemKind::Type(_) => {
975 ancestors.type_defs(tcx, impl_item.name).skip(1).next()
976 .map(|node_item| node_item.map(|parent| parent.defaultness))
977 }
978 };
979
980 if let Some(parent) = parent {
981 if parent.item.is_final() {
982 report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
983 }
984 }
985
986}
987
1a4d82fc
JJ
988fn check_impl_items_against_trait<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
989 impl_span: Span,
54a0048b 990 impl_id: DefId,
1a4d82fc 991 impl_trait_ref: &ty::TraitRef<'tcx>,
92a42be0 992 impl_items: &[hir::ImplItem]) {
54a0048b
SL
993 // If the trait reference itself is erroneous (so the compilation is going
994 // to fail), skip checking the items here -- the `impl_item` table in `tcx`
995 // isn't populated for such impls.
996 if impl_trait_ref.references_error() { return; }
997
998 // Locate trait definition and items
1a4d82fc 999 let tcx = ccx.tcx;
54a0048b 1000 let trait_def = tcx.lookup_trait_def(impl_trait_ref.def_id);
c1a9b12d
SL
1001 let trait_items = tcx.trait_items(impl_trait_ref.def_id);
1002 let mut overridden_associated_type = None;
1a4d82fc
JJ
1003
1004 // Check existing impl methods to see if they are both present in trait
1005 // and compatible with trait signature
85aaf69f 1006 for impl_item in impl_items {
b039eaaf 1007 let ty_impl_item = ccx.tcx.impl_or_trait_item(ccx.tcx.map.local_def_id(impl_item.id));
c1a9b12d 1008 let ty_trait_item = trait_items.iter()
9cc50fc6 1009 .find(|ac| ac.name() == ty_impl_item.name());
d9579d0f 1010
54a0048b 1011 // Check that impl definition matches trait definition
9cc50fc6
SL
1012 if let Some(ty_trait_item) = ty_trait_item {
1013 match impl_item.node {
1014 hir::ImplItemKind::Const(..) => {
1015 let impl_const = match ty_impl_item {
1016 ty::ConstTraitItem(ref cti) => cti,
54a0048b 1017 _ => span_bug!(impl_item.span, "non-const impl-item for const")
9cc50fc6
SL
1018 };
1019
1020 // Find associated const definition.
1021 if let &ty::ConstTraitItem(ref trait_const) = ty_trait_item {
a7813a04 1022 compare_const_impl(ccx,
9cc50fc6
SL
1023 &impl_const,
1024 impl_item.span,
1025 trait_const,
7453a54e 1026 &impl_trait_ref);
9cc50fc6
SL
1027 } else {
1028 span_err!(tcx.sess, impl_item.span, E0323,
1029 "item `{}` is an associated const, \
1030 which doesn't match its trait `{:?}`",
1031 impl_const.name,
1032 impl_trait_ref)
1033 }
d9579d0f 1034 }
9cc50fc6
SL
1035 hir::ImplItemKind::Method(ref sig, ref body) => {
1036 check_trait_fn_not_const(ccx, impl_item.span, sig.constness);
62682a34 1037
9cc50fc6
SL
1038 let impl_method = match ty_impl_item {
1039 ty::MethodTraitItem(ref mti) => mti,
54a0048b 1040 _ => span_bug!(impl_item.span, "non-method impl-item for method")
9cc50fc6 1041 };
c1a9b12d 1042
9cc50fc6 1043 if let &ty::MethodTraitItem(ref trait_method) = ty_trait_item {
a7813a04 1044 compare_impl_method(ccx,
9cc50fc6
SL
1045 &impl_method,
1046 impl_item.span,
1047 body.id,
1048 &trait_method,
1049 &impl_trait_ref);
1050 } else {
1051 span_err!(tcx.sess, impl_item.span, E0324,
1052 "item `{}` is an associated method, \
1053 which doesn't match its trait `{:?}`",
1054 impl_method.name,
1055 impl_trait_ref)
1056 }
1a4d82fc 1057 }
9cc50fc6
SL
1058 hir::ImplItemKind::Type(_) => {
1059 let impl_type = match ty_impl_item {
1060 ty::TypeTraitItem(ref tti) => tti,
54a0048b 1061 _ => span_bug!(impl_item.span, "non-type impl-item for type")
9cc50fc6 1062 };
c1a9b12d 1063
9cc50fc6
SL
1064 if let &ty::TypeTraitItem(ref at) = ty_trait_item {
1065 if let Some(_) = at.ty {
1066 overridden_associated_type = Some(impl_item);
1067 }
1068 } else {
1069 span_err!(tcx.sess, impl_item.span, E0325,
1070 "item `{}` is an associated type, \
1071 which doesn't match its trait `{:?}`",
1072 impl_type.name,
1073 impl_trait_ref)
1a4d82fc
JJ
1074 }
1075 }
1076 }
1077 }
54a0048b
SL
1078
1079 check_specialization_validity(tcx, trait_def, impl_id, impl_item);
1a4d82fc
JJ
1080 }
1081
1082 // Check for missing items from trait
c1a9b12d 1083 let provided_methods = tcx.provided_trait_methods(impl_trait_ref.def_id);
62682a34 1084 let mut missing_items = Vec::new();
c1a9b12d
SL
1085 let mut invalidated_items = Vec::new();
1086 let associated_type_overridden = overridden_associated_type.is_some();
62682a34 1087 for trait_item in trait_items.iter() {
54a0048b
SL
1088 let is_implemented;
1089 let is_provided;
1090
1a4d82fc 1091 match *trait_item {
d9579d0f 1092 ty::ConstTraitItem(ref associated_const) => {
54a0048b
SL
1093 is_provided = associated_const.has_value;
1094 is_implemented = impl_items.iter().any(|ii| {
d9579d0f 1095 match ii.node {
92a42be0 1096 hir::ImplItemKind::Const(..) => {
b039eaaf 1097 ii.name == associated_const.name
d9579d0f
AL
1098 }
1099 _ => false,
1100 }
1101 });
d9579d0f 1102 }
1a4d82fc 1103 ty::MethodTraitItem(ref trait_method) => {
54a0048b
SL
1104 is_provided = provided_methods.iter().any(|m| m.name == trait_method.name);
1105 is_implemented = trait_def.ancestors(impl_id)
1106 .fn_defs(tcx, trait_method.name)
1107 .next()
1108 .map(|node_item| !node_item.node.is_from_trait())
1109 .unwrap_or(false);
1a4d82fc 1110 }
54a0048b
SL
1111 ty::TypeTraitItem(ref trait_assoc_ty) => {
1112 is_provided = trait_assoc_ty.ty.is_some();
1113 is_implemented = trait_def.ancestors(impl_id)
1114 .type_defs(tcx, trait_assoc_ty.name)
1115 .next()
1116 .map(|node_item| !node_item.node.is_from_trait())
1117 .unwrap_or(false);
1118 }
1119 }
1120
1121 if !is_implemented {
1122 if !is_provided {
1123 missing_items.push(trait_item.name());
1124 } else if associated_type_overridden {
1125 invalidated_items.push(trait_item.name());
1a4d82fc
JJ
1126 }
1127 }
1128 }
1129
62682a34 1130 if !missing_items.is_empty() {
1a4d82fc 1131 span_err!(tcx.sess, impl_span, E0046,
c1a9b12d
SL
1132 "not all trait items implemented, missing: `{}`",
1133 missing_items.iter()
1134 .map(|name| name.to_string())
1135 .collect::<Vec<_>>().join("`, `"))
1136 }
1137
1138 if !invalidated_items.is_empty() {
1139 let invalidator = overridden_associated_type.unwrap();
1140 span_err!(tcx.sess, invalidator.span, E0399,
1141 "the following trait items need to be reimplemented \
1142 as `{}` was overridden: `{}`",
b039eaaf 1143 invalidator.name,
c1a9b12d
SL
1144 invalidated_items.iter()
1145 .map(|name| name.to_string())
1146 .collect::<Vec<_>>().join("`, `"))
1a4d82fc
JJ
1147 }
1148}
1149
a7813a04
XL
1150/// Checks a constant appearing in a type. At the moment this is just the
1151/// length expression in a fixed-length vector, but someday it might be
1152/// extended to type-level numeric literals.
1153fn check_const_in_type<'a,'tcx>(ccx: &'a CrateCtxt<'a,'tcx>,
1154 expr: &'tcx hir::Expr,
1155 expected_type: Ty<'tcx>) {
1156 ccx.inherited(None).enter(|inh| {
1157 let fcx = FnCtxt::new(&inh, ty::FnConverging(expected_type), expr.id);
1158 fcx.check_const_with_ty(expr.span, expr, expected_type);
1159 });
1160}
1161
1162fn check_const<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>,
1163 sp: Span,
1164 e: &'tcx hir::Expr,
1165 id: ast::NodeId) {
1166 let param_env = ParameterEnvironment::for_item(ccx.tcx, id);
1167 ccx.inherited(Some(param_env)).enter(|inh| {
1168 let rty = ccx.tcx.node_id_to_type(id);
1169 let fcx = FnCtxt::new(&inh, ty::FnConverging(rty), e.id);
1170 let declty = fcx.tcx.lookup_item_type(ccx.tcx.map.local_def_id(id)).ty;
1171 fcx.check_const_with_ty(sp, e, declty);
1172 });
1173}
1174
1175/// Checks whether a type can be represented in memory. In particular, it
1176/// identifies types that contain themselves without indirection through a
1177/// pointer, which would mean their size is unbounded.
1178pub fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1179 sp: Span,
1180 item_id: ast::NodeId,
1181 _designation: &str) -> bool {
1182 let rty = tcx.node_id_to_type(item_id);
1183
1184 // Check that it is possible to represent this type. This call identifies
1185 // (1) types that contain themselves and (2) types that contain a different
1186 // recursive type. It is only necessary to throw an error on those that
1187 // contain themselves. For case 2, there must be an inner type that will be
1188 // caught by case 1.
1189 match rty.is_representable(tcx, sp) {
1190 Representability::SelfRecursive => {
1191 let item_def_id = tcx.map.local_def_id(item_id);
1192 tcx.recursive_type_with_infinite_size_error(item_def_id).emit();
1193 return false
1194 }
1195 Representability::Representable | Representability::ContainsRecursive => (),
1196 }
1197 return true
1198}
1199
1200pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, id: ast::NodeId) {
1201 let t = tcx.node_id_to_type(id);
1202 match t.sty {
1203 ty::TyStruct(def, substs) => {
1204 let fields = &def.struct_variant().fields;
1205 if fields.is_empty() {
1206 span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
1207 return;
1208 }
1209 let e = fields[0].ty(tcx, substs);
1210 if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
1211 span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous");
1212 return;
1213 }
1214 match e.sty {
1215 ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
1216 _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
1217 _ => {
1218 span_err!(tcx.sess, sp, E0077,
1219 "SIMD vector element type should be machine type");
1220 return;
d9579d0f 1221 }
1a4d82fc
JJ
1222 }
1223 }
a7813a04
XL
1224 _ => ()
1225 }
1226}
1227
1228#[allow(trivial_numeric_casts)]
1229pub fn check_enum_variants<'a,'tcx>(ccx: &CrateCtxt<'a,'tcx>,
1230 sp: Span,
1231 vs: &'tcx [hir::Variant],
1232 id: ast::NodeId) {
1233 let def_id = ccx.tcx.map.local_def_id(id);
1234 let hint = *ccx.tcx.lookup_repr_hints(def_id).get(0).unwrap_or(&attr::ReprAny);
1235
1236 if hint != attr::ReprAny && vs.is_empty() {
1237 span_err!(ccx.tcx.sess, sp, E0084,
1238 "unsupported representation for zero-variant enum");
1239 }
1240
1241 ccx.inherited(None).enter(|inh| {
1242 let rty = ccx.tcx.node_id_to_type(id);
1243 let fcx = FnCtxt::new(&inh, ty::FnConverging(rty), id);
1244
1245 let repr_type_ty = ccx.tcx.enum_repr_type(Some(&hint)).to_ty(ccx.tcx);
1246 for v in vs {
1247 if let Some(ref e) = v.node.disr_expr {
1248 fcx.check_const_with_ty(e.span, e, repr_type_ty);
d9579d0f 1249 }
1a4d82fc 1250 }
a7813a04
XL
1251
1252 let def_id = ccx.tcx.map.local_def_id(id);
1253
1254 let variants = &ccx.tcx.lookup_adt_def(def_id).variants;
1255 let mut disr_vals: Vec<ty::Disr> = Vec::new();
1256 for (v, variant) in vs.iter().zip(variants.iter()) {
1257 let current_disr_val = variant.disr_val;
1258
1259 // Check for duplicate discriminant values
1260 if let Some(i) = disr_vals.iter().position(|&x| x == current_disr_val) {
1261 let mut err = struct_span_err!(ccx.tcx.sess, v.span, E0081,
1262 "discriminant value `{}` already exists", disr_vals[i]);
1263 let variant_i_node_id = ccx.tcx.map.as_local_node_id(variants[i].did).unwrap();
1264 span_note!(&mut err, ccx.tcx.map.span(variant_i_node_id),
1265 "conflicting discriminant here");
1266 err.emit();
1267 }
1268 disr_vals.push(current_disr_val);
1a4d82fc 1269 }
a7813a04
XL
1270 });
1271
1272 check_representable(ccx.tcx, sp, id, "enum");
1a4d82fc
JJ
1273}
1274
a7813a04
XL
1275impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
1276 fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
1a4d82fc 1277
a7813a04
XL
1278 fn ast_ty_to_ty_cache(&self) -> &RefCell<NodeMap<Ty<'tcx>>> {
1279 &self.ast_ty_to_ty_cache
1280 }
1a4d82fc 1281
e9174d1e 1282 fn get_item_type_scheme(&self, _: Span, id: DefId)
c34b1796
AL
1283 -> Result<ty::TypeScheme<'tcx>, ErrorReported>
1284 {
c1a9b12d 1285 Ok(self.tcx().lookup_item_type(id))
1a4d82fc
JJ
1286 }
1287
e9174d1e 1288 fn get_trait_def(&self, _: Span, id: DefId)
d9579d0f 1289 -> Result<&'tcx ty::TraitDef<'tcx>, ErrorReported>
c34b1796 1290 {
c1a9b12d 1291 Ok(self.tcx().lookup_trait_def(id))
c34b1796
AL
1292 }
1293
e9174d1e 1294 fn ensure_super_predicates(&self, _: Span, _: DefId) -> Result<(), ErrorReported> {
c34b1796
AL
1295 // all super predicates are ensured during collect pass
1296 Ok(())
1a4d82fc
JJ
1297 }
1298
1299 fn get_free_substs(&self) -> Option<&Substs<'tcx>> {
a7813a04 1300 Some(&self.parameter_environment.free_substs)
1a4d82fc
JJ
1301 }
1302
c34b1796
AL
1303 fn get_type_parameter_bounds(&self,
1304 _: Span,
1305 node_id: ast::NodeId)
1306 -> Result<Vec<ty::PolyTraitRef<'tcx>>, ErrorReported>
1307 {
a7813a04
XL
1308 let def = self.tcx.type_parameter_def(node_id);
1309 let r = self.parameter_environment
c1a9b12d 1310 .caller_bounds
c34b1796
AL
1311 .iter()
1312 .filter_map(|predicate| {
1313 match *predicate {
1314 ty::Predicate::Trait(ref data) => {
1315 if data.0.self_ty().is_param(def.space, def.index) {
1316 Some(data.to_poly_trait_ref())
1317 } else {
1318 None
1319 }
1320 }
1321 _ => {
1322 None
1323 }
1324 }
1325 })
1326 .collect();
1327 Ok(r)
1328 }
1329
1330 fn trait_defines_associated_type_named(&self,
e9174d1e 1331 trait_def_id: DefId,
c34b1796
AL
1332 assoc_name: ast::Name)
1333 -> bool
1334 {
a7813a04 1335 let trait_def = self.tcx().lookup_trait_def(trait_def_id);
c34b1796
AL
1336 trait_def.associated_type_names.contains(&assoc_name)
1337 }
1338
c1a9b12d
SL
1339 fn ty_infer(&self,
1340 ty_param_def: Option<ty::TypeParameterDef<'tcx>>,
1341 substs: Option<&mut subst::Substs<'tcx>>,
1342 space: Option<subst::ParamSpace>,
1343 span: Span) -> Ty<'tcx> {
1344 // Grab the default doing subsitution
1345 let default = ty_param_def.and_then(|def| {
1346 def.default.map(|ty| type_variable::Default {
1347 ty: ty.subst_spanned(self.tcx(), substs.as_ref().unwrap(), Some(span)),
1348 origin_span: span,
1349 def_id: def.default_def_id
1350 })
1351 });
1352
a7813a04 1353 let ty_var = self.next_ty_var_with_default(default);
c1a9b12d
SL
1354
1355 // Finally we add the type variable to the substs
1356 match substs {
1357 None => ty_var,
1358 Some(substs) => { substs.types.push(space.unwrap(), ty_var); ty_var }
1359 }
1a4d82fc
JJ
1360 }
1361
1362 fn projected_ty_from_poly_trait_ref(&self,
1363 span: Span,
1364 poly_trait_ref: ty::PolyTraitRef<'tcx>,
1365 item_name: ast::Name)
1366 -> Ty<'tcx>
1367 {
1368 let (trait_ref, _) =
a7813a04 1369 self.replace_late_bound_regions_with_fresh_var(
1a4d82fc
JJ
1370 span,
1371 infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
1372 &poly_trait_ref);
1373
1374 self.normalize_associated_type(span, trait_ref, item_name)
1375 }
1376
1377 fn projected_ty(&self,
1378 span: Span,
d9579d0f 1379 trait_ref: ty::TraitRef<'tcx>,
1a4d82fc
JJ
1380 item_name: ast::Name)
1381 -> Ty<'tcx>
1382 {
1383 self.normalize_associated_type(span, trait_ref, item_name)
1384 }
a7813a04
XL
1385
1386 fn set_tainted_by_errors(&self) {
1387 self.infcx.set_tainted_by_errors()
1388 }
1389}
1390
1391impl<'a, 'gcx, 'tcx> RegionScope for FnCtxt<'a, 'gcx, 'tcx> {
1392 fn object_lifetime_default(&self, span: Span) -> Option<ty::Region> {
1393 Some(self.base_object_lifetime_default(span))
1394 }
1395
1396 fn base_object_lifetime_default(&self, span: Span) -> ty::Region {
1397 // RFC #599 specifies that object lifetime defaults take
1398 // precedence over other defaults. But within a fn body we
1399 // don't have a *default* region, rather we use inference to
1400 // find the *correct* region, which is strictly more general
1401 // (and anyway, within a fn body the right region may not even
1402 // be something the user can write explicitly, since it might
1403 // be some expression).
1404 self.next_region_var(infer::MiscVariable(span))
1405 }
1406
1407 fn anon_regions(&self, span: Span, count: usize)
1408 -> Result<Vec<ty::Region>, Option<Vec<ElisionFailureInfo>>> {
1409 Ok((0..count).map(|_| {
1410 self.next_region_var(infer::MiscVariable(span))
1411 }).collect())
1412 }
1413}
1414
1415/// Whether `autoderef` requires types to resolve.
1416#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1417pub enum UnresolvedTypeAction {
1418 /// Produce an error and return `TyError` whenever a type cannot
1419 /// be resolved (i.e. it is `TyInfer`).
1420 Error,
1421 /// Go on without emitting any errors, and return the unresolved
1422 /// type. Useful for probing, e.g. in coercions.
1423 Ignore
1a4d82fc
JJ
1424}
1425
a7813a04
XL
1426/// Controls whether the arguments are tupled. This is used for the call
1427/// operator.
1428///
1429/// Tupling means that all call-side arguments are packed into a tuple and
1430/// passed as a single parameter. For example, if tupling is enabled, this
1431/// function:
1432///
1433/// fn f(x: (isize, isize))
1434///
1435/// Can be called as:
1436///
1437/// f(1, 2);
1438///
1439/// Instead of:
1440///
1441/// f((1, 2));
1442#[derive(Clone, Eq, PartialEq)]
1443enum TupleArgumentsFlag {
1444 DontTupleArguments,
1445 TupleArguments,
1446}
1a4d82fc 1447
a7813a04
XL
1448impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
1449 pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
1450 rty: ty::FnOutput<'tcx>,
1451 body_id: ast::NodeId)
1452 -> FnCtxt<'a, 'gcx, 'tcx> {
1453 FnCtxt {
1454 ast_ty_to_ty_cache: RefCell::new(NodeMap()),
1455 body_id: body_id,
1456 writeback_errors: Cell::new(false),
1457 err_count_on_creation: inh.tcx.sess.err_count(),
1458 ret_ty: rty,
1459 ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal, 0)),
1460 inh: inh,
1461 }
1a4d82fc
JJ
1462 }
1463
a7813a04
XL
1464 pub fn param_env(&self) -> &ty::ParameterEnvironment<'tcx> {
1465 &self.parameter_environment
1a4d82fc
JJ
1466 }
1467
1468 pub fn sess(&self) -> &Session {
a7813a04 1469 &self.tcx.sess
1a4d82fc
JJ
1470 }
1471
c34b1796 1472 pub fn err_count_since_creation(&self) -> usize {
a7813a04 1473 self.tcx.sess.err_count() - self.err_count_on_creation
1a4d82fc
JJ
1474 }
1475
85aaf69f 1476 /// Resolves type variables in `ty` if possible. Unlike the infcx
a7813a04
XL
1477 /// version (resolve_type_vars_if_possible), this version will
1478 /// also select obligations if it seems useful, in an effort
1479 /// to get more type information.
1480 fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
1481 debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
c34b1796 1482
c1a9b12d
SL
1483 // No TyInfer()? Nothing needs doing.
1484 if !ty.has_infer_types() {
a7813a04 1485 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
85aaf69f
SL
1486 return ty;
1487 }
1488
1489 // If `ty` is a type variable, see whether we already know what it is.
a7813a04 1490 ty = self.resolve_type_vars_if_possible(&ty);
c1a9b12d 1491 if !ty.has_infer_types() {
a7813a04 1492 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
85aaf69f
SL
1493 return ty;
1494 }
1495
7453a54e 1496 // If not, try resolving pending obligations as much as
85aaf69f
SL
1497 // possible. This can help substantially when there are
1498 // indirect dependencies that don't seem worth tracking
1499 // precisely.
d9579d0f 1500 self.select_obligations_where_possible();
a7813a04 1501 ty = self.resolve_type_vars_if_possible(&ty);
c34b1796 1502
a7813a04 1503 debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
c34b1796 1504 ty
85aaf69f
SL
1505 }
1506
85aaf69f 1507 fn record_deferred_call_resolution(&self,
e9174d1e 1508 closure_def_id: DefId,
a7813a04
XL
1509 r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
1510 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
c34b1796 1511 deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
85aaf69f
SL
1512 }
1513
1514 fn remove_deferred_call_resolutions(&self,
e9174d1e 1515 closure_def_id: DefId)
a7813a04 1516 -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
85aaf69f 1517 {
a7813a04 1518 let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
85aaf69f
SL
1519 deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
1520 }
1521
1a4d82fc 1522 pub fn tag(&self) -> String {
c34b1796
AL
1523 let self_ptr: *const FnCtxt = self;
1524 format!("{:?}", self_ptr)
1a4d82fc
JJ
1525 }
1526
1527 pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
a7813a04 1528 match self.locals.borrow().get(&nid) {
1a4d82fc
JJ
1529 Some(&t) => t,
1530 None => {
a7813a04 1531 span_err!(self.tcx.sess, span, E0513,
b039eaaf
SL
1532 "no type for local variable {}",
1533 nid);
a7813a04 1534 self.tcx.types.err
1a4d82fc
JJ
1535 }
1536 }
1537 }
1538
1a4d82fc
JJ
1539 #[inline]
1540 pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
62682a34
SL
1541 debug!("write_ty({}, {:?}) in fcx {}",
1542 node_id, ty, self.tag());
a7813a04 1543 self.tables.borrow_mut().node_types.insert(node_id, ty);
1a4d82fc
JJ
1544 }
1545
1a4d82fc
JJ
1546 pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
1547 if !substs.substs.is_noop() {
62682a34 1548 debug!("write_substs({}, {:?}) in fcx {}",
1a4d82fc 1549 node_id,
62682a34 1550 substs,
1a4d82fc
JJ
1551 self.tag());
1552
a7813a04 1553 self.tables.borrow_mut().item_substs.insert(node_id, substs);
1a4d82fc
JJ
1554 }
1555 }
1556
1557 pub fn write_autoderef_adjustment(&self,
1558 node_id: ast::NodeId,
c34b1796 1559 derefs: usize) {
1a4d82fc
JJ
1560 self.write_adjustment(
1561 node_id,
e9174d1e 1562 adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
1a4d82fc 1563 autoderefs: derefs,
9346a6ac
AL
1564 autoref: None,
1565 unsize: None
1566 })
1a4d82fc
JJ
1567 );
1568 }
1569
1570 pub fn write_adjustment(&self,
1571 node_id: ast::NodeId,
e9174d1e 1572 adj: adjustment::AutoAdjustment<'tcx>) {
62682a34 1573 debug!("write_adjustment(node_id={}, adj={:?})", node_id, adj);
1a4d82fc
JJ
1574
1575 if adj.is_identity() {
1576 return;
1577 }
1578
a7813a04 1579 self.tables.borrow_mut().adjustments.insert(node_id, adj);
1a4d82fc
JJ
1580 }
1581
1582 /// Basically whenever we are converting from a type scheme into
1583 /// the fn body space, we always want to normalize associated
1584 /// types as well. This function combines the two.
1585 fn instantiate_type_scheme<T>(&self,
1586 span: Span,
1587 substs: &Substs<'tcx>,
1588 value: &T)
1589 -> T
9cc50fc6 1590 where T : TypeFoldable<'tcx>
1a4d82fc 1591 {
a7813a04 1592 let value = value.subst(self.tcx, substs);
1a4d82fc 1593 let result = self.normalize_associated_types_in(span, &value);
62682a34
SL
1594 debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
1595 value,
1596 substs,
1597 result);
1a4d82fc
JJ
1598 result
1599 }
1600
1601 /// As `instantiate_type_scheme`, but for the bounds found in a
1602 /// generic type scheme.
1603 fn instantiate_bounds(&self,
1604 span: Span,
1605 substs: &Substs<'tcx>,
85aaf69f
SL
1606 bounds: &ty::GenericPredicates<'tcx>)
1607 -> ty::InstantiatedPredicates<'tcx>
1a4d82fc 1608 {
85aaf69f
SL
1609 ty::InstantiatedPredicates {
1610 predicates: self.instantiate_type_scheme(span, substs, &bounds.predicates)
1a4d82fc
JJ
1611 }
1612 }
1613
1614
1615 fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
9cc50fc6 1616 where T : TypeFoldable<'tcx>
1a4d82fc 1617 {
c1a9b12d 1618 self.inh.normalize_associated_types_in(span, self.body_id, value)
1a4d82fc
JJ
1619 }
1620
1621 fn normalize_associated_type(&self,
1622 span: Span,
d9579d0f 1623 trait_ref: ty::TraitRef<'tcx>,
1a4d82fc
JJ
1624 item_name: ast::Name)
1625 -> Ty<'tcx>
1626 {
1627 let cause = traits::ObligationCause::new(span,
1628 self.body_id,
1629 traits::ObligationCauseCode::MiscObligation);
a7813a04 1630 self.fulfillment_cx
1a4d82fc 1631 .borrow_mut()
a7813a04 1632 .normalize_projection_type(self,
1a4d82fc
JJ
1633 ty::ProjectionTy {
1634 trait_ref: trait_ref,
1635 item_name: item_name,
1636 },
1637 cause)
1638 }
1639
e9174d1e
SL
1640 /// Instantiates the type in `did` with the generics in `path` and returns
1641 /// it (registering the necessary trait obligations along the way).
1a4d82fc 1642 ///
e9174d1e
SL
1643 /// Note that this function is only intended to be used with type-paths,
1644 /// not with value-paths.
1a4d82fc 1645 pub fn instantiate_type(&self,
e9174d1e
SL
1646 did: DefId,
1647 path: &hir::Path)
1648 -> Ty<'tcx>
1a4d82fc 1649 {
e9174d1e 1650 debug!("instantiate_type(did={:?}, path={:?})", did, path);
1a4d82fc 1651 let type_scheme =
a7813a04 1652 self.tcx.lookup_item_type(did);
85aaf69f 1653 let type_predicates =
a7813a04
XL
1654 self.tcx.lookup_predicates(did);
1655 let substs = AstConv::ast_path_substs_for_ty(self, self,
e9174d1e
SL
1656 path.span,
1657 PathParamMode::Optional,
1658 &type_scheme.generics,
1659 path.segments.last().unwrap());
1660 debug!("instantiate_type: ty={:?} substs={:?}", &type_scheme.ty, &substs);
1a4d82fc 1661 let bounds =
e9174d1e 1662 self.instantiate_bounds(path.span, &substs, &type_predicates);
1a4d82fc
JJ
1663 self.add_obligations_for_parameters(
1664 traits::ObligationCause::new(
e9174d1e 1665 path.span,
1a4d82fc 1666 self.body_id,
e9174d1e 1667 traits::ItemObligation(did)),
1a4d82fc 1668 &bounds);
1a4d82fc 1669
e9174d1e 1670 self.instantiate_type_scheme(path.span, &substs, &type_scheme.ty)
1a4d82fc
JJ
1671 }
1672
e9174d1e
SL
1673 /// Return the dict-like variant corresponding to a given `Def`.
1674 pub fn def_struct_variant(&self,
7453a54e
SL
1675 def: Def,
1676 _span: Span)
e9174d1e 1677 -> Option<(ty::AdtDef<'tcx>, ty::VariantDef<'tcx>)>
1a4d82fc 1678 {
e9174d1e 1679 let (adt, variant) = match def {
7453a54e 1680 Def::Variant(enum_id, variant_id) => {
a7813a04 1681 let adt = self.tcx.lookup_adt_def(enum_id);
e9174d1e
SL
1682 (adt, adt.variant_with_id(variant_id))
1683 }
7453a54e 1684 Def::Struct(did) | Def::TyAlias(did) => {
a7813a04 1685 let typ = self.tcx.lookup_item_type(did);
e9174d1e
SL
1686 if let ty::TyStruct(adt, _) = typ.ty.sty {
1687 (adt, adt.struct_variant())
1688 } else {
1689 return None;
1690 }
1691 }
1692 _ => return None
1693 };
1a4d82fc 1694
b039eaaf
SL
1695 let var_kind = variant.kind();
1696 if var_kind == ty::VariantKind::Struct {
e9174d1e 1697 Some((adt, variant))
b039eaaf 1698 } else if var_kind == ty::VariantKind::Unit {
b039eaaf
SL
1699 Some((adt, variant))
1700 } else {
1701 None
1702 }
1703 }
e9174d1e 1704
1a4d82fc 1705 pub fn write_nil(&self, node_id: ast::NodeId) {
a7813a04 1706 self.write_ty(node_id, self.tcx.mk_nil());
1a4d82fc
JJ
1707 }
1708 pub fn write_error(&self, node_id: ast::NodeId) {
a7813a04 1709 self.write_ty(node_id, self.tcx.types.err);
1a4d82fc
JJ
1710 }
1711
1712 pub fn require_type_meets(&self,
1713 ty: Ty<'tcx>,
1714 span: Span,
1715 code: traits::ObligationCauseCode<'tcx>,
1716 bound: ty::BuiltinBound)
1717 {
1718 self.register_builtin_bound(
1719 ty,
1720 bound,
1721 traits::ObligationCause::new(span, self.body_id, code));
1722 }
1723
1724 pub fn require_type_is_sized(&self,
1725 ty: Ty<'tcx>,
1726 span: Span,
1727 code: traits::ObligationCauseCode<'tcx>)
1728 {
1729 self.require_type_meets(ty, span, code, ty::BoundSized);
1730 }
1731
1732 pub fn require_expr_have_sized_type(&self,
e9174d1e 1733 expr: &hir::Expr,
1a4d82fc
JJ
1734 code: traits::ObligationCauseCode<'tcx>)
1735 {
1736 self.require_type_is_sized(self.expr_ty(expr), expr.span, code);
1737 }
1738
1a4d82fc
JJ
1739 pub fn register_builtin_bound(&self,
1740 ty: Ty<'tcx>,
1741 builtin_bound: ty::BuiltinBound,
1742 cause: traits::ObligationCause<'tcx>)
1743 {
a7813a04
XL
1744 self.fulfillment_cx.borrow_mut()
1745 .register_builtin_bound(self, ty, builtin_bound, cause);
1a4d82fc
JJ
1746 }
1747
1748 pub fn register_predicate(&self,
1749 obligation: traits::PredicateObligation<'tcx>)
1750 {
62682a34
SL
1751 debug!("register_predicate({:?})",
1752 obligation);
a7813a04 1753 self.fulfillment_cx
1a4d82fc 1754 .borrow_mut()
a7813a04 1755 .register_predicate_obligation(self, obligation);
1a4d82fc
JJ
1756 }
1757
e9174d1e 1758 pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
a7813a04 1759 let t = AstConv::ast_ty_to_ty(self, self, ast_t);
b039eaaf 1760 self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
1a4d82fc
JJ
1761 t
1762 }
1763
e9174d1e 1764 pub fn expr_ty(&self, ex: &hir::Expr) -> Ty<'tcx> {
a7813a04 1765 match self.tables.borrow().node_types.get(&ex.id) {
1a4d82fc
JJ
1766 Some(&t) => t,
1767 None => {
54a0048b 1768 bug!("no type for expr in fcx {}", self.tag());
1a4d82fc
JJ
1769 }
1770 }
1771 }
1772
1773 /// Apply `adjustment` to the type of `expr`
1774 pub fn adjust_expr_ty(&self,
e9174d1e
SL
1775 expr: &hir::Expr,
1776 adjustment: Option<&adjustment::AutoAdjustment<'tcx>>)
1a4d82fc
JJ
1777 -> Ty<'tcx>
1778 {
1779 let raw_ty = self.expr_ty(expr);
a7813a04
XL
1780 let raw_ty = self.shallow_resolve(raw_ty);
1781 let resolve_ty = |ty: Ty<'tcx>| self.resolve_type_vars_if_possible(&ty);
1782 raw_ty.adjust(self.tcx, expr.span, expr.id, adjustment, |method_call| {
1783 self.tables.borrow().method_map.get(&method_call)
c1a9b12d
SL
1784 .map(|method| resolve_ty(method.ty))
1785 })
1a4d82fc
JJ
1786 }
1787
1788 pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
a7813a04 1789 match self.tables.borrow().node_types.get(&id) {
1a4d82fc 1790 Some(&t) => t,
a7813a04 1791 None if self.err_count_since_creation() != 0 => self.tcx.types.err,
1a4d82fc 1792 None => {
54a0048b 1793 bug!("no type for node {}: {} in fcx {}",
a7813a04 1794 id, self.tcx.map.node_to_string(id),
54a0048b 1795 self.tag());
1a4d82fc
JJ
1796 }
1797 }
1798 }
1799
1800 pub fn item_substs(&self) -> Ref<NodeMap<ty::ItemSubsts<'tcx>>> {
c1a9b12d
SL
1801 // NOTE: @jroesch this is hack that appears to be fixed on nightly, will monitor if
1802 // it changes when we upgrade the snapshot compiler
1803 fn project_item_susbts<'a, 'tcx>(tables: &'a ty::Tables<'tcx>)
1804 -> &'a NodeMap<ty::ItemSubsts<'tcx>> {
1805 &tables.item_substs
1806 }
1807
a7813a04 1808 Ref::map(self.tables.borrow(), project_item_susbts)
1a4d82fc
JJ
1809 }
1810
1811 pub fn opt_node_ty_substs<F>(&self,
1812 id: ast::NodeId,
1813 f: F) where
1814 F: FnOnce(&ty::ItemSubsts<'tcx>),
1815 {
a7813a04 1816 match self.tables.borrow().item_substs.get(&id) {
1a4d82fc
JJ
1817 Some(s) => { f(s) }
1818 None => { }
1819 }
1820 }
1821
1a4d82fc
JJ
1822 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1823 /// outlive the region `r`.
1824 pub fn register_region_obligation(&self,
1825 ty: Ty<'tcx>,
1826 region: ty::Region,
1827 cause: traits::ObligationCause<'tcx>)
1828 {
a7813a04 1829 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
62682a34 1830 fulfillment_cx.register_region_obligation(ty, region, cause);
1a4d82fc
JJ
1831 }
1832
e9174d1e
SL
1833 /// Registers an obligation for checking later, during regionck, that the type `ty` must
1834 /// outlive the region `r`.
1835 pub fn register_wf_obligation(&self,
1836 ty: Ty<'tcx>,
1837 span: Span,
1838 code: traits::ObligationCauseCode<'tcx>)
1839 {
1840 // WF obligations never themselves fail, so no real need to give a detailed cause:
1841 let cause = traits::ObligationCause::new(span, self.body_id, code);
1842 self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
1843 }
1844
1845 pub fn register_old_wf_obligation(&self,
1846 ty: Ty<'tcx>,
1847 span: Span,
1848 code: traits::ObligationCauseCode<'tcx>)
1849 {
1850 // Registers an "old-style" WF obligation that uses the
1851 // implicator code. This is basically a buggy version of
1852 // `register_wf_obligation` that is being kept around
1853 // temporarily just to help with phasing in the newer rules.
1854 //
1855 // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
1856 let cause = traits::ObligationCause::new(span, self.body_id, code);
1857 self.register_region_obligation(ty, ty::ReEmpty, cause);
1858 }
1859
1860 /// Registers obligations that all types appearing in `substs` are well-formed.
1861 pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
1a4d82fc 1862 {
62682a34 1863 for &ty in &substs.types {
e9174d1e 1864 self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
1a4d82fc
JJ
1865 }
1866 }
1867
1868 /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
1869 /// type/region parameter was instantiated (`substs`), creates and registers suitable
1870 /// trait/region obligations.
1871 ///
1872 /// For example, if there is a function:
1873 ///
1874 /// ```
1875 /// fn foo<'a,T:'a>(...)
1876 /// ```
1877 ///
1878 /// and a reference:
1879 ///
1880 /// ```
1881 /// let f = foo;
1882 /// ```
1883 ///
1884 /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
1885 /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
1886 pub fn add_obligations_for_parameters(&self,
1887 cause: traits::ObligationCause<'tcx>,
85aaf69f 1888 predicates: &ty::InstantiatedPredicates<'tcx>)
1a4d82fc 1889 {
85aaf69f 1890 assert!(!predicates.has_escaping_regions());
1a4d82fc 1891
62682a34
SL
1892 debug!("add_obligations_for_parameters(predicates={:?})",
1893 predicates);
1a4d82fc 1894
62682a34
SL
1895 for obligation in traits::predicates_for_generics(cause, predicates) {
1896 self.register_predicate(obligation);
1897 }
1a4d82fc 1898 }
85aaf69f 1899
e9174d1e 1900 // FIXME(arielb1): use this instead of field.ty everywhere
54a0048b
SL
1901 // Only for fields! Returns <none> for methods>
1902 // Indifferent to privacy flags
e9174d1e
SL
1903 pub fn field_ty(&self,
1904 span: Span,
1905 field: ty::FieldDef<'tcx>,
1906 substs: &Substs<'tcx>)
1907 -> Ty<'tcx>
85aaf69f 1908 {
e9174d1e 1909 self.normalize_associated_types_in(span,
a7813a04 1910 &field.ty(self.tcx, substs))
85aaf69f 1911 }
c34b1796
AL
1912
1913 fn check_casts(&self) {
a7813a04 1914 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
62682a34
SL
1915 for cast in deferred_cast_checks.drain(..) {
1916 cast.check(self);
c34b1796 1917 }
c34b1796 1918 }
d9579d0f 1919
c1a9b12d
SL
1920 /// Apply "fallbacks" to some types
1921 /// ! gets replaced with (), unconstrained ints with i32, and unconstrained floats with f64.
1922 fn default_type_parameters(&self) {
54a0048b
SL
1923 use rustc::ty::error::UnconstrainedNumeric::Neither;
1924 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
a7813a04
XL
1925
1926 // Defaulting inference variables becomes very dubious if we have
1927 // encountered type-checking errors. Therefore, if we think we saw
1928 // some errors in this function, just resolve all uninstanted type
1929 // varibles to TyError.
1930 if self.is_tainted_by_errors() {
1931 for ty in &self.unsolved_variables() {
1932 if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
1933 debug!("default_type_parameters: defaulting `{:?}` to error", ty);
1934 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx().types.err);
1935 }
1936 }
1937 return;
1938 }
1939
1940 for ty in &self.unsolved_variables() {
1941 let resolved = self.resolve_type_vars_if_possible(ty);
1942 if self.type_var_diverges(resolved) {
1943 debug!("default_type_parameters: defaulting `{:?}` to `()` because it diverges",
1944 resolved);
1945 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.mk_nil());
c1a9b12d 1946 } else {
a7813a04 1947 match self.type_is_unconstrained_numeric(resolved) {
c1a9b12d 1948 UnconstrainedInt => {
a7813a04
XL
1949 debug!("default_type_parameters: defaulting `{:?}` to `i32`",
1950 resolved);
1951 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.i32)
c1a9b12d
SL
1952 },
1953 UnconstrainedFloat => {
a7813a04
XL
1954 debug!("default_type_parameters: defaulting `{:?}` to `f32`",
1955 resolved);
1956 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.f64)
c1a9b12d
SL
1957 }
1958 Neither => { }
1959 }
1960 }
1961 }
1962 }
1963
d9579d0f 1964 fn select_all_obligations_and_apply_defaults(&self) {
a7813a04 1965 if self.tcx.sess.features.borrow().default_type_parameter_fallback {
c1a9b12d
SL
1966 self.new_select_all_obligations_and_apply_defaults();
1967 } else {
1968 self.old_select_all_obligations_and_apply_defaults();
1969 }
1970 }
d9579d0f 1971
c1a9b12d
SL
1972 // Implements old type inference fallback algorithm
1973 fn old_select_all_obligations_and_apply_defaults(&self) {
d9579d0f
AL
1974 self.select_obligations_where_possible();
1975 self.default_type_parameters();
1976 self.select_obligations_where_possible();
1977 }
1978
c1a9b12d 1979 fn new_select_all_obligations_and_apply_defaults(&self) {
54a0048b
SL
1980 use rustc::ty::error::UnconstrainedNumeric::Neither;
1981 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
c1a9b12d 1982
e9174d1e 1983 // For the time being this errs on the side of being memory wasteful but provides better
c1a9b12d 1984 // error reporting.
a7813a04 1985 // let type_variables = self.type_variables.clone();
c1a9b12d
SL
1986
1987 // There is a possibility that this algorithm will have to run an arbitrary number of times
1988 // to terminate so we bound it by the compiler's recursion limit.
a7813a04 1989 for _ in 0..self.tcx.sess.recursion_limit.get() {
c1a9b12d
SL
1990 // First we try to solve all obligations, it is possible that the last iteration
1991 // has made it possible to make more progress.
1992 self.select_obligations_where_possible();
1993
1994 let mut conflicts = Vec::new();
1995
1996 // Collect all unsolved type, integral and floating point variables.
a7813a04 1997 let unsolved_variables = self.unsolved_variables();
c1a9b12d
SL
1998
1999 // We must collect the defaults *before* we do any unification. Because we have
2000 // directly attached defaults to the type variables any unification that occurs
2001 // will erase defaults causing conflicting defaults to be completely ignored.
2002 let default_map: FnvHashMap<_, _> =
2003 unsolved_variables
2004 .iter()
a7813a04 2005 .filter_map(|t| self.default(t).map(|d| (t, d)))
c1a9b12d
SL
2006 .collect();
2007
2008 let mut unbound_tyvars = HashSet::new();
2009
2010 debug!("select_all_obligations_and_apply_defaults: defaults={:?}", default_map);
2011
2012 // We loop over the unsolved variables, resolving them and if they are
7453a54e 2013 // and unconstrainted numeric type we add them to the set of unbound
c1a9b12d
SL
2014 // variables. We do this so we only apply literal fallback to type
2015 // variables without defaults.
2016 for ty in &unsolved_variables {
a7813a04
XL
2017 let resolved = self.resolve_type_vars_if_possible(ty);
2018 if self.type_var_diverges(resolved) {
2019 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.mk_nil());
c1a9b12d 2020 } else {
a7813a04 2021 match self.type_is_unconstrained_numeric(resolved) {
c1a9b12d
SL
2022 UnconstrainedInt | UnconstrainedFloat => {
2023 unbound_tyvars.insert(resolved);
2024 },
2025 Neither => {}
2026 }
2027 }
2028 }
2029
2030 // We now remove any numeric types that also have defaults, and instead insert
2031 // the type variable with a defined fallback.
2032 for ty in &unsolved_variables {
2033 if let Some(_default) = default_map.get(ty) {
a7813a04 2034 let resolved = self.resolve_type_vars_if_possible(ty);
c1a9b12d 2035
a7813a04
XL
2036 debug!("select_all_obligations_and_apply_defaults: \
2037 ty: {:?} with default: {:?}",
c1a9b12d
SL
2038 ty, _default);
2039
2040 match resolved.sty {
2041 ty::TyInfer(ty::TyVar(_)) => {
2042 unbound_tyvars.insert(ty);
2043 }
2044
2045 ty::TyInfer(ty::IntVar(_)) | ty::TyInfer(ty::FloatVar(_)) => {
2046 unbound_tyvars.insert(ty);
2047 if unbound_tyvars.contains(resolved) {
2048 unbound_tyvars.remove(resolved);
2049 }
2050 }
2051
2052 _ => {}
2053 }
2054 }
2055 }
2056
2057 // If there are no more fallbacks to apply at this point we have applied all possible
b039eaaf 2058 // defaults and type inference will proceed as normal.
c1a9b12d
SL
2059 if unbound_tyvars.is_empty() {
2060 break;
2061 }
2062
2063 // Finally we go through each of the unbound type variables and unify them with
2064 // the proper fallback, reporting a conflicting default error if any of the
2065 // unifications fail. We know it must be a conflicting default because the
2066 // variable would only be in `unbound_tyvars` and have a concrete value if
2067 // it had been solved by previously applying a default.
2068
2069 // We wrap this in a transaction for error reporting, if we detect a conflict
2070 // we will rollback the inference context to its prior state so we can probe
2071 // for conflicts and correctly report them.
2072
2073
a7813a04 2074 let _ = self.commit_if_ok(|_: &infer::CombinedSnapshot| {
c1a9b12d 2075 for ty in &unbound_tyvars {
a7813a04
XL
2076 if self.type_var_diverges(ty) {
2077 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.mk_nil());
c1a9b12d 2078 } else {
a7813a04 2079 match self.type_is_unconstrained_numeric(ty) {
c1a9b12d 2080 UnconstrainedInt => {
a7813a04 2081 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.i32)
c1a9b12d
SL
2082 },
2083 UnconstrainedFloat => {
a7813a04 2084 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.f64)
c1a9b12d
SL
2085 }
2086 Neither => {
2087 if let Some(default) = default_map.get(ty) {
2088 let default = default.clone();
a7813a04
XL
2089 match self.eq_types(false,
2090 TypeOrigin::Misc(default.origin_span),
2091 ty, default.ty) {
54a0048b
SL
2092 Ok(InferOk { obligations, .. }) => {
2093 // FIXME(#32730) propagate obligations
2094 assert!(obligations.is_empty())
2095 },
c1a9b12d
SL
2096 Err(_) => {
2097 conflicts.push((*ty, default));
2098 }
2099 }
2100 }
2101 }
2102 }
2103 }
2104 }
2105
2106 // If there are conflicts we rollback, otherwise commit
2107 if conflicts.len() > 0 {
2108 Err(())
2109 } else {
2110 Ok(())
2111 }
2112 });
2113
2114 if conflicts.len() > 0 {
2115 // Loop through each conflicting default, figuring out the default that caused
2116 // a unification failure and then report an error for each.
2117 for (conflict, default) in conflicts {
2118 let conflicting_default =
2119 self.find_conflicting_default(&unbound_tyvars, &default_map, conflict)
2120 .unwrap_or(type_variable::Default {
a7813a04 2121 ty: self.next_ty_var(),
c1a9b12d 2122 origin_span: codemap::DUMMY_SP,
a7813a04 2123 def_id: self.tcx.map.local_def_id(0) // what do I put here?
c1a9b12d
SL
2124 });
2125
2126 // This is to ensure that we elimnate any non-determinism from the error
2127 // reporting by fixing an order, it doesn't matter what order we choose
2128 // just that it is consistent.
2129 let (first_default, second_default) =
2130 if default.def_id < conflicting_default.def_id {
2131 (default, conflicting_default)
2132 } else {
2133 (conflicting_default, default)
2134 };
2135
2136
a7813a04 2137 self.report_conflicting_default_types(
c1a9b12d
SL
2138 first_default.origin_span,
2139 first_default,
2140 second_default)
2141 }
2142 }
2143 }
2144
2145 self.select_obligations_where_possible();
2146 }
2147
2148 // For use in error handling related to default type parameter fallback. We explicitly
2149 // apply the default that caused conflict first to a local version of the type variable
2150 // table then apply defaults until we find a conflict. That default must be the one
2151 // that caused conflict earlier.
2152 fn find_conflicting_default(&self,
2153 unbound_vars: &HashSet<Ty<'tcx>>,
2154 default_map: &FnvHashMap<&Ty<'tcx>, type_variable::Default<'tcx>>,
2155 conflict: Ty<'tcx>)
2156 -> Option<type_variable::Default<'tcx>> {
54a0048b
SL
2157 use rustc::ty::error::UnconstrainedNumeric::Neither;
2158 use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
c1a9b12d
SL
2159
2160 // Ensure that we apply the conflicting default first
2161 let mut unbound_tyvars = Vec::with_capacity(unbound_vars.len() + 1);
2162 unbound_tyvars.push(conflict);
2163 unbound_tyvars.extend(unbound_vars.iter());
2164
2165 let mut result = None;
2166 // We run the same code as above applying defaults in order, this time when
2167 // we find the conflict we just return it for error reporting above.
2168
2169 // We also run this inside snapshot that never commits so we can do error
2170 // reporting for more then one conflict.
2171 for ty in &unbound_tyvars {
a7813a04
XL
2172 if self.type_var_diverges(ty) {
2173 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.mk_nil());
c1a9b12d 2174 } else {
a7813a04 2175 match self.type_is_unconstrained_numeric(ty) {
c1a9b12d 2176 UnconstrainedInt => {
a7813a04 2177 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.i32)
c1a9b12d
SL
2178 },
2179 UnconstrainedFloat => {
a7813a04 2180 self.demand_eqtype(codemap::DUMMY_SP, *ty, self.tcx.types.f64)
c1a9b12d
SL
2181 },
2182 Neither => {
2183 if let Some(default) = default_map.get(ty) {
2184 let default = default.clone();
a7813a04
XL
2185 match self.eq_types(false,
2186 TypeOrigin::Misc(default.origin_span),
2187 ty, default.ty) {
54a0048b
SL
2188 // FIXME(#32730) propagate obligations
2189 Ok(InferOk { obligations, .. }) => assert!(obligations.is_empty()),
c1a9b12d
SL
2190 Err(_) => {
2191 result = Some(default);
2192 }
2193 }
2194 }
2195 }
2196 }
2197 }
2198 }
2199
2200 return result;
2201 }
2202
d9579d0f
AL
2203 fn select_all_obligations_or_error(&self) {
2204 debug!("select_all_obligations_or_error");
2205
2206 // upvar inference should have ensured that all deferred call
2207 // resolutions are handled by now.
a7813a04 2208 assert!(self.deferred_call_resolutions.borrow().is_empty());
d9579d0f
AL
2209
2210 self.select_all_obligations_and_apply_defaults();
c1a9b12d 2211
a7813a04
XL
2212 let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
2213 match fulfillment_cx.select_all_or_error(self) {
d9579d0f 2214 Ok(()) => { }
a7813a04
XL
2215 Err(errors) => { self.report_fulfillment_errors(&errors); }
2216 }
2217
2218 if let Err(ref errors) = fulfillment_cx.select_rfc1592_obligations(self) {
2219 self.report_fulfillment_errors_as_warnings(errors, self.body_id);
d9579d0f
AL
2220 }
2221 }
2222
2223 /// Select as many obligations as we can at present.
2224 fn select_obligations_where_possible(&self) {
a7813a04 2225 match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
d9579d0f 2226 Ok(()) => { }
a7813a04 2227 Err(errors) => { self.report_fulfillment_errors(&errors); }
d9579d0f
AL
2228 }
2229 }
62682a34 2230
a7813a04
XL
2231 /// Executes an autoderef loop for the type `t`. At each step, invokes `should_stop`
2232 /// to decide whether to terminate the loop. Returns the final type and number of
2233 /// derefs that it performed.
2234 ///
2235 /// Note: this method does not modify the adjustments table. The caller is responsible for
2236 /// inserting an AutoAdjustment record into the `self` using one of the suitable methods.
2237 pub fn autoderef<'b, E, I, T, F>(&self,
2238 sp: Span,
2239 base_ty: Ty<'tcx>,
2240 maybe_exprs: E,
2241 unresolved_type_action: UnresolvedTypeAction,
2242 mut lvalue_pref: LvaluePreference,
2243 mut should_stop: F)
2244 -> (Ty<'tcx>, usize, Option<T>)
2245 // FIXME(eddyb) use copyable iterators when that becomes ergonomic.
2246 where E: Fn() -> I,
2247 I: IntoIterator<Item=&'b hir::Expr>,
2248 F: FnMut(Ty<'tcx>, usize) -> Option<T>,
2249 {
2250 debug!("autoderef(base_ty={:?}, lvalue_pref={:?})",
2251 base_ty, lvalue_pref);
2252
2253 let mut t = base_ty;
2254 for autoderefs in 0..self.tcx.sess.recursion_limit.get() {
2255 let resolved_t = match unresolved_type_action {
2256 UnresolvedTypeAction::Error => {
2257 self.structurally_resolved_type(sp, t)
2258 }
2259 UnresolvedTypeAction::Ignore => {
2260 // We can continue even when the type cannot be resolved
2261 // (i.e. it is an inference variable) because `Ty::builtin_deref`
2262 // and `try_overloaded_deref` both simply return `None`
2263 // in such a case without producing spurious errors.
2264 self.resolve_type_vars_if_possible(&t)
2265 }
2266 };
2267 if resolved_t.references_error() {
2268 return (resolved_t, autoderefs, None);
2269 }
1a4d82fc 2270
a7813a04
XL
2271 match should_stop(resolved_t, autoderefs) {
2272 Some(x) => return (resolved_t, autoderefs, Some(x)),
2273 None => {}
2274 }
1a4d82fc 2275
a7813a04
XL
2276 // Otherwise, deref if type is derefable:
2277
2278 // Super subtle: it might seem as though we should
2279 // pass `opt_expr` to `try_overloaded_deref`, so that
2280 // the (implicit) autoref of using an overloaded deref
2281 // would get added to the adjustment table. However we
2282 // do not do that, because it's kind of a
2283 // "meta-adjustment" -- instead, we just leave it
2284 // unrecorded and know that there "will be" an
2285 // autoref. regionck and other bits of the code base,
2286 // when they encounter an overloaded autoderef, have
2287 // to do some reconstructive surgery. This is a pretty
2288 // complex mess that is begging for a proper MIR.
2289 let mt = if let Some(mt) = resolved_t.builtin_deref(false, lvalue_pref) {
2290 mt
2291 } else if let Some(method) = self.try_overloaded_deref(sp, None,
2292 resolved_t, lvalue_pref) {
2293 for expr in maybe_exprs() {
2294 let method_call = MethodCall::autoderef(expr.id, autoderefs as u32);
2295 self.tables.borrow_mut().method_map.insert(method_call, method);
2296 }
2297 self.make_overloaded_lvalue_return_type(method)
2298 } else {
2299 return (resolved_t, autoderefs, None);
2300 };
85aaf69f 2301
a7813a04
XL
2302 t = mt.ty;
2303 if mt.mutbl == hir::MutImmutable {
2304 lvalue_pref = NoPreference;
85aaf69f 2305 }
d9579d0f 2306 }
1a4d82fc 2307
a7813a04
XL
2308 // We've reached the recursion limit, error gracefully.
2309 span_err!(self.tcx.sess, sp, E0055,
2310 "reached the recursion limit while auto-dereferencing {:?}",
2311 base_ty);
2312 (self.tcx.types.err, 0, None)
2313 }
1a4d82fc 2314
a7813a04
XL
2315 fn try_overloaded_deref(&self,
2316 span: Span,
2317 base_expr: Option<&hir::Expr>,
2318 base_ty: Ty<'tcx>,
2319 lvalue_pref: LvaluePreference)
2320 -> Option<MethodCallee<'tcx>>
2321 {
2322 // Try DerefMut first, if preferred.
2323 let method = match (lvalue_pref, self.tcx.lang_items.deref_mut_trait()) {
2324 (PreferMutLvalue, Some(trait_did)) => {
2325 self.lookup_method_in_trait(span, base_expr,
2326 token::intern("deref_mut"), trait_did,
2327 base_ty, None)
1a4d82fc 2328 }
a7813a04 2329 _ => None
1a4d82fc 2330 };
54a0048b 2331
a7813a04
XL
2332 // Otherwise, fall back to Deref.
2333 let method = match (method, self.tcx.lang_items.deref_trait()) {
2334 (None, Some(trait_did)) => {
2335 self.lookup_method_in_trait(span, base_expr,
2336 token::intern("deref"), trait_did,
2337 base_ty, None)
2338 }
2339 (method, _) => method
2340 };
2341
2342 method
1a4d82fc
JJ
2343 }
2344
a7813a04
XL
2345 /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
2346 /// returns a type of `&T`, but the actual type we assign to the
2347 /// *expression* is `T`. So this function just peels off the return
2348 /// type by one layer to yield `T`.
2349 fn make_overloaded_lvalue_return_type(&self,
2350 method: MethodCallee<'tcx>)
2351 -> ty::TypeAndMut<'tcx>
2352 {
2353 // extract method return type, which will be &T;
2354 // all LB regions should have been instantiated during method lookup
2355 let ret_ty = method.ty.fn_ret();
2356 let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap().unwrap();
2357
2358 // method returns &T, but the type as visible to user is T, so deref
2359 ret_ty.builtin_deref(true, NoPreference).unwrap()
2360 }
2361
2362 fn lookup_indexing(&self,
2363 expr: &hir::Expr,
2364 base_expr: &'gcx hir::Expr,
2365 base_ty: Ty<'tcx>,
2366 idx_ty: Ty<'tcx>,
2367 lvalue_pref: LvaluePreference)
2368 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2369 {
2370 // FIXME(#18741) -- this is almost but not quite the same as the
2371 // autoderef that normal method probing does. They could likely be
2372 // consolidated.
2373
2374 let (ty, autoderefs, final_mt) = self.autoderef(base_expr.span,
2375 base_ty,
2376 || Some(base_expr),
2377 UnresolvedTypeAction::Error,
2378 lvalue_pref,
2379 |adj_ty, idx| {
2380 self.try_index_step(MethodCall::expr(expr.id), expr, base_expr,
2381 adj_ty, idx, false, lvalue_pref, idx_ty)
2382 });
1a4d82fc 2383
a7813a04
XL
2384 if final_mt.is_some() {
2385 return final_mt;
1a4d82fc 2386 }
1a4d82fc 2387
a7813a04
XL
2388 // After we have fully autoderef'd, if the resulting type is [T; n], then
2389 // do a final unsized coercion to yield [T].
2390 if let ty::TyArray(element_ty, _) = ty.sty {
2391 let adjusted_ty = self.tcx.mk_slice(element_ty);
2392 self.try_index_step(MethodCall::expr(expr.id), expr, base_expr,
2393 adjusted_ty, autoderefs, true, lvalue_pref, idx_ty)
2394 } else {
2395 None
1a4d82fc 2396 }
1a4d82fc 2397 }
1a4d82fc 2398
a7813a04
XL
2399 /// To type-check `base_expr[index_expr]`, we progressively autoderef
2400 /// (and otherwise adjust) `base_expr`, looking for a type which either
2401 /// supports builtin indexing or overloaded indexing.
2402 /// This loop implements one step in that search; the autoderef loop
2403 /// is implemented by `lookup_indexing`.
2404 fn try_index_step(&self,
2405 method_call: MethodCall,
2406 expr: &hir::Expr,
2407 base_expr: &'gcx hir::Expr,
2408 adjusted_ty: Ty<'tcx>,
2409 autoderefs: usize,
2410 unsize: bool,
2411 lvalue_pref: LvaluePreference,
2412 index_ty: Ty<'tcx>)
2413 -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
2414 {
2415 let tcx = self.tcx;
2416 debug!("try_index_step(expr={:?}, base_expr.id={:?}, adjusted_ty={:?}, \
2417 autoderefs={}, unsize={}, index_ty={:?})",
2418 expr,
2419 base_expr,
2420 adjusted_ty,
2421 autoderefs,
2422 unsize,
2423 index_ty);
2424
2425 let input_ty = self.next_ty_var();
2426
2427 // First, try built-in indexing.
2428 match (adjusted_ty.builtin_index(), &index_ty.sty) {
2429 (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
2430 debug!("try_index_step: success, using built-in indexing");
2431 // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
2432 assert!(!unsize);
2433 self.write_autoderef_adjustment(base_expr.id, autoderefs);
2434 return Some((tcx.types.usize, ty));
2435 }
2436 _ => {}
1a4d82fc 2437 }
1a4d82fc 2438
a7813a04
XL
2439 // Try `IndexMut` first, if preferred.
2440 let method = match (lvalue_pref, tcx.lang_items.index_mut_trait()) {
2441 (PreferMutLvalue, Some(trait_did)) => {
2442 self.lookup_method_in_trait_adjusted(expr.span,
2443 Some(&base_expr),
2444 token::intern("index_mut"),
2445 trait_did,
2446 autoderefs,
2447 unsize,
2448 adjusted_ty,
2449 Some(vec![input_ty]))
2450 }
2451 _ => None,
1a4d82fc
JJ
2452 };
2453
a7813a04
XL
2454 // Otherwise, fall back to `Index`.
2455 let method = match (method, tcx.lang_items.index_trait()) {
2456 (None, Some(trait_did)) => {
2457 self.lookup_method_in_trait_adjusted(expr.span,
2458 Some(&base_expr),
2459 token::intern("index"),
2460 trait_did,
2461 autoderefs,
2462 unsize,
2463 adjusted_ty,
2464 Some(vec![input_ty]))
1a4d82fc 2465 }
a7813a04
XL
2466 (method, _) => method,
2467 };
2468
2469 // If some lookup succeeds, write callee into table and extract index/element
2470 // type from the method signature.
2471 // If some lookup succeeded, install method in table
2472 method.map(|method| {
2473 debug!("try_index_step: success, using overloaded indexing");
2474 self.tables.borrow_mut().method_map.insert(method_call, method);
2475 (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
2476 })
2477 }
2478
2479 fn check_method_argument_types(&self,
2480 sp: Span,
2481 method_fn_ty: Ty<'tcx>,
2482 callee_expr: &'gcx hir::Expr,
2483 args_no_rcvr: &'gcx [P<hir::Expr>],
2484 tuple_arguments: TupleArgumentsFlag,
2485 expected: Expectation<'tcx>)
2486 -> ty::FnOutput<'tcx> {
2487 if method_fn_ty.references_error() {
2488 let err_inputs = self.err_args(args_no_rcvr.len());
2489
2490 let err_inputs = match tuple_arguments {
2491 DontTupleArguments => err_inputs,
2492 TupleArguments => vec![self.tcx.mk_tup(err_inputs)],
2493 };
2494
2495 self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
2496 false, tuple_arguments);
2497 ty::FnConverging(self.tcx.types.err)
2498 } else {
2499 match method_fn_ty.sty {
2500 ty::TyFnDef(_, _, ref fty) => {
2501 // HACK(eddyb) ignore self in the definition (see above).
2502 let expected_arg_tys = self.expected_types_for_fn_args(sp, expected,
2503 fty.sig.0.output,
2504 &fty.sig.0.inputs[1..]);
2505 self.check_argument_types(sp, &fty.sig.0.inputs[1..], &expected_arg_tys[..],
2506 args_no_rcvr, fty.sig.0.variadic, tuple_arguments);
2507 fty.sig.0.output
2508 }
2509 _ => {
2510 span_bug!(callee_expr.span, "method without bare fn type");
2511 }
1a4d82fc
JJ
2512 }
2513 }
2514 }
1a4d82fc 2515
a7813a04
XL
2516 /// Generic function that factors out common logic from function calls,
2517 /// method calls and overloaded operators.
2518 fn check_argument_types(&self,
2519 sp: Span,
2520 fn_inputs: &[Ty<'tcx>],
2521 expected_arg_tys: &[Ty<'tcx>],
2522 args: &'gcx [P<hir::Expr>],
2523 variadic: bool,
2524 tuple_arguments: TupleArgumentsFlag) {
2525 let tcx = self.tcx;
2526
2527 // Grab the argument types, supplying fresh type variables
2528 // if the wrong number of arguments were supplied
2529 let supplied_arg_count = if tuple_arguments == DontTupleArguments {
2530 args.len()
2531 } else {
2532 1
2533 };
1a4d82fc 2534
a7813a04
XL
2535 // All the input types from the fn signature must outlive the call
2536 // so as to validate implied bounds.
2537 for &fn_input_ty in fn_inputs {
2538 self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
2539 }
2540
2541 let mut expected_arg_tys = expected_arg_tys;
2542 let expected_arg_count = fn_inputs.len();
2543 let formal_tys = if tuple_arguments == TupleArguments {
2544 let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
2545 match tuple_type.sty {
2546 ty::TyTuple(arg_types) => {
2547 if arg_types.len() != args.len() {
2548 span_err!(tcx.sess, sp, E0057,
2549 "this function takes {} parameter{} but {} parameter{} supplied",
2550 arg_types.len(),
2551 if arg_types.len() == 1 {""} else {"s"},
2552 args.len(),
2553 if args.len() == 1 {" was"} else {"s were"});
2554 expected_arg_tys = &[];
2555 self.err_args(args.len())
2556 } else {
2557 expected_arg_tys = match expected_arg_tys.get(0) {
2558 Some(&ty) => match ty.sty {
2559 ty::TyTuple(ref tys) => &tys,
2560 _ => &[]
2561 },
2562 None => &[]
2563 };
2564 arg_types.to_vec()
2565 }
2566 }
2567 _ => {
2568 span_err!(tcx.sess, sp, E0059,
2569 "cannot use call notation; the first type parameter \
2570 for the function trait is neither a tuple nor unit");
c34b1796 2571 expected_arg_tys = &[];
a7813a04 2572 self.err_args(args.len())
1a4d82fc
JJ
2573 }
2574 }
a7813a04
XL
2575 } else if expected_arg_count == supplied_arg_count {
2576 fn_inputs.to_vec()
2577 } else if variadic {
2578 if supplied_arg_count >= expected_arg_count {
2579 fn_inputs.to_vec()
2580 } else {
2581 span_err!(tcx.sess, sp, E0060,
2582 "this function takes at least {} parameter{} \
2583 but {} parameter{} supplied",
2584 expected_arg_count,
2585 if expected_arg_count == 1 {""} else {"s"},
2586 supplied_arg_count,
2587 if supplied_arg_count == 1 {" was"} else {"s were"});
c34b1796 2588 expected_arg_tys = &[];
a7813a04 2589 self.err_args(supplied_arg_count)
1a4d82fc 2590 }
1a4d82fc 2591 } else {
a7813a04
XL
2592 span_err!(tcx.sess, sp, E0061,
2593 "this function takes {} parameter{} but {} parameter{} supplied",
1a4d82fc
JJ
2594 expected_arg_count,
2595 if expected_arg_count == 1 {""} else {"s"},
2596 supplied_arg_count,
2597 if supplied_arg_count == 1 {" was"} else {"s were"});
c34b1796 2598 expected_arg_tys = &[];
a7813a04 2599 self.err_args(supplied_arg_count)
1a4d82fc 2600 };
a7813a04
XL
2601
2602 debug!("check_argument_types: formal_tys={:?}",
2603 formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
2604
2605 // Check the arguments.
2606 // We do this in a pretty awful way: first we typecheck any arguments
2607 // that are not anonymous functions, then we typecheck the anonymous
2608 // functions. This is so that we have more information about the types
2609 // of arguments when we typecheck the functions. This isn't really the
2610 // right way to do this.
2611 let xs = [false, true];
2612 let mut any_diverges = false; // has any of the arguments diverged?
2613 let mut warned = false; // have we already warned about unreachable code?
2614 for check_blocks in &xs {
2615 let check_blocks = *check_blocks;
2616 debug!("check_blocks={}", check_blocks);
2617
2618 // More awful hacks: before we check argument types, try to do
2619 // an "opportunistic" vtable resolution of any trait bounds on
2620 // the call. This helps coercions.
2621 if check_blocks {
2622 self.select_obligations_where_possible();
92a42be0 2623 }
a7813a04
XL
2624
2625 // For variadic functions, we don't have a declared type for all of
2626 // the arguments hence we only do our usual type checking with
2627 // the arguments who's types we do know.
2628 let t = if variadic {
2629 expected_arg_count
2630 } else if tuple_arguments == TupleArguments {
2631 args.len()
2632 } else {
2633 supplied_arg_count
1a4d82fc 2634 };
a7813a04
XL
2635 for (i, arg) in args.iter().take(t).enumerate() {
2636 if any_diverges && !warned {
2637 self.tcx
2638 .sess
2639 .add_lint(lint::builtin::UNREACHABLE_CODE,
2640 arg.id,
2641 arg.span,
2642 "unreachable expression".to_string());
2643 warned = true;
2644 }
2645 let is_block = match arg.node {
2646 hir::ExprClosure(..) => true,
2647 _ => false
2648 };
1a4d82fc 2649
a7813a04
XL
2650 if is_block == check_blocks {
2651 debug!("checking the argument");
2652 let formal_ty = formal_tys[i];
1a4d82fc 2653
a7813a04
XL
2654 // The special-cased logic below has three functions:
2655 // 1. Provide as good of an expected type as possible.
2656 let expected = expected_arg_tys.get(i).map(|&ty| {
2657 Expectation::rvalue_hint(self, ty)
2658 });
85aaf69f 2659
a7813a04
XL
2660 self.check_expr_with_expectation(&arg,
2661 expected.unwrap_or(ExpectHasType(formal_ty)));
2662 // 2. Coerce to the most detailed type that could be coerced
2663 // to, which is `expected_ty` if `rvalue_hint` returns an
2664 // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
2665 let coerce_ty = expected.and_then(|e| e.only_has_type(self));
2666 self.demand_coerce(&arg, coerce_ty.unwrap_or(formal_ty));
2667
2668 // 3. Relate the expected type and the formal one,
2669 // if the expected type was used for the coercion.
2670 coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
2671 }
92a42be0 2672
a7813a04
XL
2673 if let Some(&arg_ty) = self.tables.borrow().node_types.get(&arg.id) {
2674 any_diverges = any_diverges || self.type_var_diverges(arg_ty);
2675 }
92a42be0 2676 }
a7813a04
XL
2677 if any_diverges && !warned {
2678 let parent = self.tcx.map.get_parent_node(args[0].id);
2679 self.tcx
2680 .sess
2681 .add_lint(lint::builtin::UNREACHABLE_CODE,
2682 parent,
2683 sp,
2684 "unreachable call".to_string());
2685 warned = true;
2686 }
2687
92a42be0
SL
2688 }
2689
a7813a04
XL
2690 // We also need to make sure we at least write the ty of the other
2691 // arguments which we skipped above.
2692 if variadic {
2693 for arg in args.iter().skip(expected_arg_count) {
2694 self.check_expr(&arg);
1a4d82fc 2695
a7813a04
XL
2696 // There are a few types which get autopromoted when passed via varargs
2697 // in C but we just error out instead and require explicit casts.
2698 let arg_ty = self.structurally_resolved_type(arg.span,
2699 self.expr_ty(&arg));
2700 match arg_ty.sty {
2701 ty::TyFloat(ast::FloatTy::F32) => {
2702 self.type_error_message(arg.span, |t| {
2703 format!("can't pass an `{}` to variadic \
2704 function, cast to `c_double`", t)
2705 }, arg_ty, None);
2706 }
2707 ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
2708 self.type_error_message(arg.span, |t| {
2709 format!("can't pass `{}` to variadic \
2710 function, cast to `c_int`",
2711 t)
2712 }, arg_ty, None);
2713 }
2714 ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
2715 self.type_error_message(arg.span, |t| {
2716 format!("can't pass `{}` to variadic \
2717 function, cast to `c_uint`",
2718 t)
2719 }, arg_ty, None);
2720 }
2721 ty::TyFnDef(_, _, f) => {
2722 let ptr_ty = self.tcx.mk_fn_ptr(f);
2723 let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
2724 self.type_error_message(arg.span,
2725 |t| {
2726 format!("can't pass `{}` to variadic \
2727 function, cast to `{}`", t, ptr_ty)
2728 }, arg_ty, None);
2729 }
2730 _ => {}
54a0048b 2731 }
1a4d82fc
JJ
2732 }
2733 }
2734 }
1a4d82fc 2735
a7813a04
XL
2736 fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
2737 (0..len).map(|_| self.tcx.types.err).collect()
1a4d82fc 2738 }
1a4d82fc 2739
a7813a04
XL
2740 fn write_call(&self,
2741 call_expr: &hir::Expr,
2742 output: ty::FnOutput<'tcx>) {
2743 self.write_ty(call_expr.id, match output {
2744 ty::FnConverging(output_ty) => output_ty,
2745 ty::FnDiverging => self.next_diverging_ty_var()
2746 });
2747 }
1a4d82fc 2748
a7813a04
XL
2749 // AST fragment checking
2750 fn check_lit(&self,
2751 lit: &ast::Lit,
2752 expected: Expectation<'tcx>)
2753 -> Ty<'tcx>
2754 {
2755 let tcx = self.tcx;
85aaf69f 2756
a7813a04
XL
2757 match lit.node {
2758 ast::LitKind::Str(..) => tcx.mk_static_str(),
2759 ast::LitKind::ByteStr(ref v) => {
2760 tcx.mk_imm_ref(tcx.mk_region(ty::ReStatic),
2761 tcx.mk_array(tcx.types.u8, v.len()))
2762 }
2763 ast::LitKind::Byte(_) => tcx.types.u8,
2764 ast::LitKind::Char(_) => tcx.types.char,
2765 ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
2766 ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
2767 ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
2768 let opt_ty = expected.to_option(self).and_then(|ty| {
2769 match ty.sty {
2770 ty::TyInt(_) | ty::TyUint(_) => Some(ty),
2771 ty::TyChar => Some(tcx.types.u8),
2772 ty::TyRawPtr(..) => Some(tcx.types.usize),
2773 ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
2774 _ => None
2775 }
2776 });
2777 opt_ty.unwrap_or_else(
2778 || tcx.mk_int_var(self.next_int_var_id()))
2779 }
2780 ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
2781 ast::LitKind::FloatUnsuffixed(_) => {
2782 let opt_ty = expected.to_option(self).and_then(|ty| {
2783 match ty.sty {
2784 ty::TyFloat(_) => Some(ty),
2785 _ => None
2786 }
2787 });
2788 opt_ty.unwrap_or_else(
2789 || tcx.mk_float_var(self.next_float_var_id()))
2790 }
2791 ast::LitKind::Bool(_) => tcx.types.bool
2792 }
2793 }
2794
2795 fn check_expr_eq_type(&self,
2796 expr: &'gcx hir::Expr,
2797 expected: Ty<'tcx>) {
2798 self.check_expr_with_hint(expr, expected);
2799 self.demand_eqtype(expr.span, expected, self.expr_ty(expr));
2800 }
2801
2802 pub fn check_expr_has_type(&self,
2803 expr: &'gcx hir::Expr,
2804 expected: Ty<'tcx>) {
2805 self.check_expr_with_hint(expr, expected);
2806 self.demand_suptype(expr.span, expected, self.expr_ty(expr));
2807 }
2808
2809 fn check_expr_coercable_to_type(&self,
2810 expr: &'gcx hir::Expr,
2811 expected: Ty<'tcx>) {
2812 self.check_expr_with_hint(expr, expected);
2813 self.demand_coerce(expr, expected);
2814 }
2815
2816 fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
2817 expected: Ty<'tcx>) {
2818 self.check_expr_with_expectation(expr, ExpectHasType(expected))
2819 }
2820
2821 fn check_expr_with_expectation(&self,
2822 expr: &'gcx hir::Expr,
2823 expected: Expectation<'tcx>) {
2824 self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
2825 }
2826
2827 fn check_expr(&self, expr: &'gcx hir::Expr) {
2828 self.check_expr_with_expectation(expr, NoExpectation)
2829 }
2830
2831 fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
2832 lvalue_pref: LvaluePreference) {
2833 self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
2834 }
2835
2836 // determine the `self` type, using fresh variables for all variables
2837 // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
2838 // would return ($0, $1) where $0 and $1 are freshly instantiated type
2839 // variables.
2840 pub fn impl_self_ty(&self,
2841 span: Span, // (potential) receiver for this impl
2842 did: DefId)
2843 -> TypeAndSubsts<'tcx> {
2844 let tcx = self.tcx;
2845
2846 let ity = tcx.lookup_item_type(did);
2847 let (tps, rps, raw_ty) =
2848 (ity.generics.types.get_slice(subst::TypeSpace),
2849 ity.generics.regions.get_slice(subst::TypeSpace),
2850 ity.ty);
2851
2852 debug!("impl_self_ty: tps={:?} rps={:?} raw_ty={:?}", tps, rps, raw_ty);
2853
2854 let rps = self.region_vars_for_defs(span, rps);
2855 let mut substs = subst::Substs::new(
2856 VecPerParamSpace::empty(),
2857 VecPerParamSpace::new(rps, Vec::new(), Vec::new()));
2858 self.type_vars_for_defs(span, ParamSpace::TypeSpace, &mut substs, tps);
2859 let substd_ty = self.instantiate_type_scheme(span, &substs, &raw_ty);
2860
2861 TypeAndSubsts { substs: substs, ty: substd_ty }
2862 }
2863
2864 /// Unifies the return type with the expected type early, for more coercions
2865 /// and forward type information on the argument expressions.
2866 fn expected_types_for_fn_args(&self,
2867 call_span: Span,
2868 expected_ret: Expectation<'tcx>,
2869 formal_ret: ty::FnOutput<'tcx>,
2870 formal_args: &[Ty<'tcx>])
2871 -> Vec<Ty<'tcx>> {
2872 let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
2873 if let ty::FnConverging(formal_ret_ty) = formal_ret {
2874 self.commit_regions_if_ok(|| {
2875 // Attempt to apply a subtyping relationship between the formal
2876 // return type (likely containing type variables if the function
2877 // is polymorphic) and the expected return type.
2878 // No argument expectations are produced if unification fails.
2879 let origin = TypeOrigin::Misc(call_span);
2880 let ures = self.sub_types(false, origin, formal_ret_ty, ret_ty);
2881 // FIXME(#15760) can't use try! here, FromError doesn't default
2882 // to identity so the resulting type is not constrained.
2883 match ures {
2884 // FIXME(#32730) propagate obligations
2885 Ok(InferOk { obligations, .. }) => assert!(obligations.is_empty()),
2886 Err(e) => return Err(e),
2887 }
85aaf69f 2888
a7813a04
XL
2889 // Record all the argument types, with the substitutions
2890 // produced from the above subtyping unification.
2891 Ok(formal_args.iter().map(|ty| {
2892 self.resolve_type_vars_if_possible(ty)
2893 }).collect())
2894 }).ok()
2895 } else {
2896 None
2897 }
2898 }).unwrap_or(vec![]);
2899 debug!("expected_types_for_fn_args(formal={:?} -> {:?}, expected={:?} -> {:?})",
2900 formal_args, formal_ret,
2901 expected_args, expected_ret);
2902 expected_args
2903 }
1a4d82fc
JJ
2904
2905 // Checks a method call.
a7813a04
XL
2906 fn check_method_call(&self,
2907 expr: &'gcx hir::Expr,
2908 method_name: Spanned<ast::Name>,
2909 args: &'gcx [P<hir::Expr>],
2910 tps: &[P<hir::Ty>],
2911 expected: Expectation<'tcx>,
2912 lvalue_pref: LvaluePreference) {
7453a54e 2913 let rcvr = &args[0];
a7813a04 2914 self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
1a4d82fc
JJ
2915
2916 // no need to check for bot/err -- callee does that
a7813a04
XL
2917 let expr_t = self.structurally_resolved_type(expr.span, self.expr_ty(&rcvr));
2918
2919 let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
2920 let fn_ty = match self.lookup_method(method_name.span,
2921 method_name.node,
2922 expr_t,
2923 tps,
2924 expr,
2925 rcvr) {
1a4d82fc
JJ
2926 Ok(method) => {
2927 let method_ty = method.ty;
2928 let method_call = MethodCall::expr(expr.id);
a7813a04 2929 self.tables.borrow_mut().method_map.insert(method_call, method);
1a4d82fc
JJ
2930 method_ty
2931 }
2932 Err(error) => {
a7813a04
XL
2933 if method_name.node != keywords::Invalid.name() {
2934 self.report_method_error(method_name.span, expr_t,
2935 method_name.node, Some(rcvr), error);
7453a54e 2936 }
a7813a04
XL
2937 self.write_error(expr.id);
2938 self.tcx.types.err
1a4d82fc
JJ
2939 }
2940 };
2941
2942 // Call the generic checker.
a7813a04
XL
2943 let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
2944 expr, &args[1..],
2945 DontTupleArguments,
2946 expected);
1a4d82fc 2947
a7813a04 2948 self.write_call(expr, ret_ty);
1a4d82fc
JJ
2949 }
2950
2951 // A generic function for checking the then and else in an if
2952 // or if-else.
a7813a04
XL
2953 fn check_then_else(&self,
2954 cond_expr: &'gcx hir::Expr,
2955 then_blk: &'gcx hir::Block,
2956 opt_else_expr: Option<&'gcx hir::Expr>,
2957 id: ast::NodeId,
2958 sp: Span,
2959 expected: Expectation<'tcx>) {
2960 self.check_expr_has_type(cond_expr, self.tcx.types.bool);
2961
2962 let expected = expected.adjust_for_branches(self);
2963 self.check_block_with_expected(then_blk, expected);
2964 let then_ty = self.node_ty(then_blk.id);
2965
2966 let unit = self.tcx.mk_nil();
54a0048b
SL
2967 let (origin, expected, found, result) =
2968 if let Some(else_expr) = opt_else_expr {
a7813a04
XL
2969 self.check_expr_with_expectation(else_expr, expected);
2970 let else_ty = self.expr_ty(else_expr);
54a0048b
SL
2971 let origin = TypeOrigin::IfExpression(sp);
2972
2973 // Only try to coerce-unify if we have a then expression
2974 // to assign coercions to, otherwise it's () or diverging.
2975 let result = if let Some(ref then) = then_blk.expr {
a7813a04
XL
2976 let res = self.try_find_coercion_lub(origin, || Some(&**then),
2977 then_ty, else_expr);
54a0048b
SL
2978
2979 // In case we did perform an adjustment, we have to update
2980 // the type of the block, because old trans still uses it.
a7813a04 2981 let adj = self.tables.borrow().adjustments.get(&then.id).cloned();
54a0048b 2982 if res.is_ok() && adj.is_some() {
a7813a04 2983 self.write_ty(then_blk.id, self.adjust_expr_ty(then, adj.as_ref()));
54a0048b 2984 }
1a4d82fc 2985
54a0048b
SL
2986 res
2987 } else {
a7813a04 2988 self.commit_if_ok(|_| {
54a0048b 2989 let trace = TypeTrace::types(origin, true, then_ty, else_ty);
a7813a04 2990 self.lub(true, trace, &then_ty, &else_ty)
54a0048b
SL
2991 .map(|InferOk { value, obligations }| {
2992 // FIXME(#32730) propagate obligations
2993 assert!(obligations.is_empty());
2994 value
2995 })
2996 })
2997 };
2998 (origin, then_ty, else_ty, result)
1a4d82fc 2999 } else {
54a0048b
SL
3000 let origin = TypeOrigin::IfExpressionWithNoElse(sp);
3001 (origin, unit, then_ty,
a7813a04 3002 self.eq_types(true, origin, unit, then_ty)
54a0048b
SL
3003 .map(|InferOk { obligations, .. }| {
3004 // FIXME(#32730) propagate obligations
3005 assert!(obligations.is_empty());
3006 unit
3007 }))
3008 };
3009
3010 let if_ty = match result {
3011 Ok(ty) => {
a7813a04
XL
3012 if self.expr_ty(cond_expr).references_error() {
3013 self.tcx.types.err
54a0048b
SL
3014 } else {
3015 ty
3016 }
3017 }
3018 Err(e) => {
a7813a04
XL
3019 self.report_mismatched_types(origin, expected, found, e);
3020 self.tcx.types.err
54a0048b 3021 }
1a4d82fc
JJ
3022 };
3023
a7813a04 3024 self.write_ty(id, if_ty);
1a4d82fc
JJ
3025 }
3026
1a4d82fc 3027 // Check field access expressions
a7813a04
XL
3028 fn check_field(&self,
3029 expr: &'gcx hir::Expr,
3030 lvalue_pref: LvaluePreference,
3031 base: &'gcx hir::Expr,
3032 field: &Spanned<ast::Name>) {
3033 self.check_expr_with_lvalue_pref(base, lvalue_pref);
3034 let expr_t = self.structurally_resolved_type(expr.span,
3035 self.expr_ty(base));
54a0048b 3036 let mut private_candidate = None;
a7813a04
XL
3037 let (_, autoderefs, field_ty) = self.autoderef(expr.span,
3038 expr_t,
3039 || Some(base),
3040 UnresolvedTypeAction::Error,
3041 lvalue_pref,
3042 |base_t, _| {
54a0048b
SL
3043 if let ty::TyStruct(base_def, substs) = base_t.sty {
3044 debug!("struct named {:?}", base_t);
3045 if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
a7813a04
XL
3046 let field_ty = self.field_ty(expr.span, field, substs);
3047 if field.vis.is_accessible_from(self.body_id, &self.tcx().map) {
54a0048b
SL
3048 return Some(field_ty);
3049 }
3050 private_candidate = Some((base_def.did, field_ty));
1a4d82fc 3051 }
1a4d82fc 3052 }
54a0048b 3053 None
1a4d82fc
JJ
3054 });
3055 match field_ty {
3056 Some(field_ty) => {
a7813a04
XL
3057 self.write_ty(expr.id, field_ty);
3058 self.write_autoderef_adjustment(base.id, autoderefs);
1a4d82fc
JJ
3059 return;
3060 }
3061 None => {}
3062 }
3063
54a0048b 3064 if let Some((did, field_ty)) = private_candidate {
a7813a04
XL
3065 let struct_path = self.tcx().item_path_str(did);
3066 self.write_ty(expr.id, field_ty);
54a0048b 3067 let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
a7813a04
XL
3068 let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
3069 // Also check if an accessible method exists, which is often what is meant.
3070 if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
3071 err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
3072 field.node));
3073 }
3074 err.emit();
3075 } else if field.node == keywords::Invalid.name() {
3076 self.write_error(expr.id);
3077 } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
3078 self.type_error_struct(field.span, |actual| {
3079 format!("attempted to take value of method `{}` on type \
3080 `{}`", field.node, actual)
3081 }, expr_t, None)
3082 .help(
3083 "maybe a `()` to call it is missing? \
3084 If not, try an anonymous function")
9cc50fc6 3085 .emit();
a7813a04 3086 self.write_error(expr.id);
1a4d82fc 3087 } else {
a7813a04
XL
3088 let mut err = self.type_error_struct(expr.span, |actual| {
3089 format!("attempted access of field `{}` on type `{}`, \
3090 but no field with that name was found",
3091 field.node, actual)
3092 }, expr_t, None);
e9174d1e 3093 if let ty::TyStruct(def, _) = expr_t.sty {
a7813a04 3094 Self::suggest_field_names(&mut err, def.struct_variant(), field, vec![]);
85aaf69f 3095 }
9cc50fc6 3096 err.emit();
a7813a04 3097 self.write_error(expr.id);
1a4d82fc 3098 }
1a4d82fc
JJ
3099 }
3100
85aaf69f 3101 // displays hints about the closest matches in field names
a7813a04
XL
3102 fn suggest_field_names(err: &mut DiagnosticBuilder,
3103 variant: ty::VariantDef<'tcx>,
3104 field: &Spanned<ast::Name>,
3105 skip : Vec<InternedString>) {
b039eaaf 3106 let name = field.node.as_str();
a7813a04
XL
3107 let names = variant.fields.iter().filter_map(|field| {
3108 // ignore already set fields and private fields from non-local crates
3109 if skip.iter().any(|x| *x == field.name.as_str()) ||
3110 (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
3111 None
3112 } else {
3113 Some(&field.name)
3114 }
3115 });
9cc50fc6 3116
85aaf69f 3117 // only find fits with at least one matching letter
9cc50fc6
SL
3118 if let Some(name) = find_best_match_for_name(names, &name, Some(name.len())) {
3119 err.span_help(field.span,
3120 &format!("did you mean `{}`?", name));
85aaf69f
SL
3121 }
3122 }
3123
1a4d82fc 3124 // Check tuple index expressions
a7813a04
XL
3125 fn check_tup_field(&self,
3126 expr: &'gcx hir::Expr,
3127 lvalue_pref: LvaluePreference,
3128 base: &'gcx hir::Expr,
3129 idx: codemap::Spanned<usize>) {
3130 self.check_expr_with_lvalue_pref(base, lvalue_pref);
3131 let expr_t = self.structurally_resolved_type(expr.span,
3132 self.expr_ty(base));
54a0048b 3133 let mut private_candidate = None;
1a4d82fc 3134 let mut tuple_like = false;
a7813a04
XL
3135 let (_, autoderefs, field_ty) = self.autoderef(expr.span,
3136 expr_t,
3137 || Some(base),
3138 UnresolvedTypeAction::Error,
3139 lvalue_pref,
3140 |base_t, _| {
54a0048b
SL
3141 let (base_def, substs) = match base_t.sty {
3142 ty::TyStruct(base_def, substs) => (base_def, substs),
62682a34 3143 ty::TyTuple(ref v) => {
1a4d82fc 3144 tuple_like = true;
54a0048b 3145 return if idx.node < v.len() { Some(v[idx.node]) } else { None }
1a4d82fc 3146 }
54a0048b
SL
3147 _ => return None,
3148 };
3149
3150 tuple_like = base_def.struct_variant().is_tuple_struct();
3151 if !tuple_like { return None }
3152
3153 debug!("tuple struct named {:?}", base_t);
3154 if let Some(field) = base_def.struct_variant().fields.get(idx.node) {
a7813a04
XL
3155 let field_ty = self.field_ty(expr.span, field, substs);
3156 if field.vis.is_accessible_from(self.body_id, &self.tcx().map) {
54a0048b
SL
3157 return Some(field_ty);
3158 }
3159 private_candidate = Some((base_def.did, field_ty));
1a4d82fc 3160 }
54a0048b 3161 None
1a4d82fc
JJ
3162 });
3163 match field_ty {
3164 Some(field_ty) => {
a7813a04
XL
3165 self.write_ty(expr.id, field_ty);
3166 self.write_autoderef_adjustment(base.id, autoderefs);
1a4d82fc
JJ
3167 return;
3168 }
3169 None => {}
3170 }
54a0048b
SL
3171
3172 if let Some((did, field_ty)) = private_candidate {
a7813a04 3173 let struct_path = self.tcx().item_path_str(did);
54a0048b 3174 let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
a7813a04
XL
3175 self.tcx().sess.span_err(expr.span, &msg);
3176 self.write_ty(expr.id, field_ty);
54a0048b
SL
3177 return;
3178 }
3179
a7813a04 3180 self.type_error_message(
1a4d82fc
JJ
3181 expr.span,
3182 |actual| {
3183 if tuple_like {
3184 format!("attempted out-of-bounds tuple index `{}` on \
3185 type `{}`",
3186 idx.node,
3187 actual)
3188 } else {
3189 format!("attempted tuple index `{}` on type `{}`, but the \
3190 type was not a tuple or tuple struct",
3191 idx.node,
3192 actual)
3193 }
3194 },
3195 expr_t, None);
3196
a7813a04 3197 self.write_error(expr.id);
1a4d82fc
JJ
3198 }
3199
a7813a04
XL
3200 fn report_unknown_field(&self,
3201 ty: Ty<'tcx>,
3202 variant: ty::VariantDef<'tcx>,
3203 field: &hir::Field,
3204 skip_fields: &[hir::Field]) {
3205 let mut err = self.type_error_struct(
b039eaaf 3206 field.name.span,
e9174d1e
SL
3207 |actual| if let ty::TyEnum(..) = ty.sty {
3208 format!("struct variant `{}::{}` has no field named `{}`",
b039eaaf 3209 actual, variant.name.as_str(), field.name.node)
e9174d1e
SL
3210 } else {
3211 format!("structure `{}` has no field named `{}`",
b039eaaf 3212 actual, field.name.node)
e9174d1e
SL
3213 },
3214 ty,
3215 None);
3216 // prevent all specified fields from being suggested
b039eaaf 3217 let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
a7813a04 3218 Self::suggest_field_names(&mut err, variant, &field.name, skip_fields.collect());
9cc50fc6 3219 err.emit();
e9174d1e
SL
3220 }
3221
a7813a04
XL
3222 fn check_expr_struct_fields(&self,
3223 adt_ty: Ty<'tcx>,
3224 span: Span,
3225 variant: ty::VariantDef<'tcx>,
3226 ast_fields: &'gcx [hir::Field],
3227 check_completeness: bool) {
3228 let tcx = self.tcx;
e9174d1e
SL
3229 let substs = match adt_ty.sty {
3230 ty::TyStruct(_, substs) | ty::TyEnum(_, substs) => substs,
54a0048b 3231 _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
e9174d1e 3232 };
1a4d82fc 3233
e9174d1e
SL
3234 let mut remaining_fields = FnvHashMap();
3235 for field in &variant.fields {
3236 remaining_fields.insert(field.name, field);
1a4d82fc
JJ
3237 }
3238
3239 let mut error_happened = false;
3240
3241 // Typecheck each field.
85aaf69f 3242 for field in ast_fields {
e9174d1e
SL
3243 let expected_field_type;
3244
b039eaaf 3245 if let Some(v_field) = remaining_fields.remove(&field.name.node) {
a7813a04 3246 expected_field_type = self.field_ty(field.span, v_field, substs);
e9174d1e
SL
3247 } else {
3248 error_happened = true;
3249 expected_field_type = tcx.types.err;
b039eaaf 3250 if let Some(_) = variant.find_field_named(field.name.node) {
a7813a04 3251 span_err!(self.tcx.sess, field.name.span, E0062,
1a4d82fc 3252 "field `{}` specified more than once",
b039eaaf 3253 field.name.node);
e9174d1e 3254 } else {
a7813a04 3255 self.report_unknown_field(adt_ty, variant, field, ast_fields);
1a4d82fc
JJ
3256 }
3257 }
3258
3259 // Make sure to give a type to the field even if there's
3260 // an error, so we can continue typechecking
a7813a04 3261 self.check_expr_coercable_to_type(&field.expr, expected_field_type);
1a4d82fc
JJ
3262 }
3263
1a4d82fc 3264 // Make sure the programmer specified all the fields.
e9174d1e
SL
3265 if check_completeness &&
3266 !error_happened &&
3267 !remaining_fields.is_empty()
3268 {
3269 span_err!(tcx.sess, span, E0063,
9cc50fc6 3270 "missing field{} {} in initializer of `{}`",
e9174d1e
SL
3271 if remaining_fields.len() == 1 {""} else {"s"},
3272 remaining_fields.keys()
3273 .map(|n| format!("`{}`", n))
3274 .collect::<Vec<_>>()
9cc50fc6
SL
3275 .join(", "),
3276 adt_ty);
1a4d82fc
JJ
3277 }
3278
1a4d82fc
JJ
3279 }
3280
a7813a04
XL
3281 fn check_struct_fields_on_error(&self,
3282 id: ast::NodeId,
3283 fields: &'gcx [hir::Field],
3284 base_expr: &'gcx Option<P<hir::Expr>>) {
1a4d82fc
JJ
3285 // Make sure to still write the types
3286 // otherwise we might ICE
a7813a04 3287 self.write_error(id);
85aaf69f 3288 for field in fields {
a7813a04 3289 self.check_expr(&field.expr);
1a4d82fc
JJ
3290 }
3291 match *base_expr {
a7813a04 3292 Some(ref base) => self.check_expr(&base),
1a4d82fc
JJ
3293 None => {}
3294 }
3295 }
3296
a7813a04
XL
3297 fn check_expr_struct(&self,
3298 expr: &hir::Expr,
3299 path: &hir::Path,
3300 fields: &'gcx [hir::Field],
3301 base_expr: &'gcx Option<P<hir::Expr>>)
e9174d1e 3302 {
a7813a04 3303 let tcx = self.tcx;
e9174d1e
SL
3304
3305 // Find the relevant variant
3306 let def = lookup_full_def(tcx, path.span, expr.id);
7453a54e 3307 if def == Def::Err {
a7813a04
XL
3308 self.set_tainted_by_errors();
3309 self.check_struct_fields_on_error(expr.id, fields, base_expr);
9cc50fc6
SL
3310 return;
3311 }
a7813a04 3312 let variant = match self.def_struct_variant(def, path.span) {
7453a54e 3313 Some((_, variant)) => variant,
e9174d1e 3314 None => {
a7813a04 3315 span_err!(self.tcx.sess, path.span, E0071,
e9174d1e
SL
3316 "`{}` does not name a structure",
3317 pprust::path_to_string(path));
a7813a04 3318 self.check_struct_fields_on_error(expr.id, fields, base_expr);
e9174d1e
SL
3319 return;
3320 }
3321 };
3322
a7813a04
XL
3323 let expr_ty = self.instantiate_type(def.def_id(), path);
3324 self.write_ty(expr.id, expr_ty);
e9174d1e 3325
a7813a04
XL
3326 self.check_expr_struct_fields(expr_ty, path.span, variant, fields,
3327 base_expr.is_none());
e9174d1e 3328 if let &Some(ref base_expr) = base_expr {
a7813a04 3329 self.check_expr_has_type(base_expr, expr_ty);
7453a54e
SL
3330 match expr_ty.sty {
3331 ty::TyStruct(adt, substs) => {
a7813a04 3332 self.tables.borrow_mut().fru_field_types.insert(
7453a54e
SL
3333 expr.id,
3334 adt.struct_variant().fields.iter().map(|f| {
a7813a04 3335 self.normalize_associated_types_in(
7453a54e
SL
3336 expr.span, &f.ty(tcx, substs)
3337 )
3338 }).collect()
3339 );
3340 }
3341 _ => {
3342 span_err!(tcx.sess, base_expr.span, E0436,
3343 "functional record update syntax requires a struct");
3344 }
e9174d1e
SL
3345 }
3346 }
3347 }
3348
1a4d82fc 3349
a7813a04
XL
3350 /// Invariant:
3351 /// If an expression has any sub-expressions that result in a type error,
3352 /// inspecting that expression's type with `ty.references_error()` will return
3353 /// true. Likewise, if an expression is known to diverge, inspecting its
3354 /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
3355 /// strict, _|_ can appear in the type of an expression that does not,
3356 /// itself, diverge: for example, fn() -> _|_.)
3357 /// Note that inspecting a type's structure *directly* may expose the fact
3358 /// that there are actually multiple representations for `TyError`, so avoid
3359 /// that when err needs to be handled differently.
3360 fn check_expr_with_expectation_and_lvalue_pref(&self,
3361 expr: &'gcx hir::Expr,
3362 expected: Expectation<'tcx>,
3363 lvalue_pref: LvaluePreference) {
3364 debug!(">> typechecking: expr={:?} expected={:?}",
3365 expr, expected);
3366
3367 let tcx = self.tcx;
3368 let id = expr.id;
3369 match expr.node {
3370 hir::ExprBox(ref subexpr) => {
3371 let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
3372 match ty.sty {
3373 ty::TyBox(ty) => Expectation::rvalue_hint(self, ty),
3374 _ => NoExpectation
3375 }
3376 });
3377 self.check_expr_with_expectation(subexpr, expected_inner);
3378 let referent_ty = self.expr_ty(&subexpr);
3379 self.write_ty(id, tcx.mk_box(referent_ty));
3380 }
1a4d82fc 3381
a7813a04
XL
3382 hir::ExprLit(ref lit) => {
3383 let typ = self.check_lit(&lit, expected);
3384 self.write_ty(id, typ);
3385 }
3386 hir::ExprBinary(op, ref lhs, ref rhs) => {
3387 self.check_binop(expr, op, lhs, rhs);
3388 }
3389 hir::ExprAssignOp(op, ref lhs, ref rhs) => {
3390 self.check_binop_assign(expr, op, lhs, rhs);
3391 }
3392 hir::ExprUnary(unop, ref oprnd) => {
3393 let expected_inner = match unop {
3394 hir::UnNot | hir::UnNeg => {
3395 expected
3396 }
e9174d1e 3397 hir::UnDeref => {
a7813a04 3398 NoExpectation
1a4d82fc 3399 }
a7813a04
XL
3400 };
3401 let lvalue_pref = match unop {
3402 hir::UnDeref => lvalue_pref,
3403 _ => NoPreference
3404 };
3405 self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
3406 expected_inner,
3407 lvalue_pref);
3408 let mut oprnd_t = self.expr_ty(&oprnd);
3409
3410 if !oprnd_t.references_error() {
3411 match unop {
3412 hir::UnDeref => {
3413 oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
3414
3415 if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
3416 oprnd_t = mt.ty;
3417 } else if let Some(method) = self.try_overloaded_deref(
3418 expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
3419 oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
3420 self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
3421 method);
3422 } else {
3423 self.type_error_message(expr.span, |actual| {
3424 format!("type `{}` cannot be \
3425 dereferenced", actual)
3426 }, oprnd_t, None);
3427 oprnd_t = tcx.types.err;
3428 }
1a4d82fc 3429 }
a7813a04
XL
3430 hir::UnNot => {
3431 oprnd_t = self.structurally_resolved_type(oprnd.span,
3432 oprnd_t);
3433 if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
3434 oprnd_t = self.check_user_unop("!", "not",
3435 tcx.lang_items.not_trait(),
3436 expr, &oprnd, oprnd_t, unop);
3437 }
c34b1796 3438 }
a7813a04
XL
3439 hir::UnNeg => {
3440 oprnd_t = self.structurally_resolved_type(oprnd.span,
3441 oprnd_t);
3442 if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
3443 oprnd_t = self.check_user_unop("-", "neg",
3444 tcx.lang_items.neg_trait(),
3445 expr, &oprnd, oprnd_t, unop);
3446 }
1a4d82fc
JJ
3447 }
3448 }
1a4d82fc 3449 }
a7813a04
XL
3450 self.write_ty(id, oprnd_t);
3451 }
3452 hir::ExprAddrOf(mutbl, ref oprnd) => {
3453 let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
3454 match ty.sty {
3455 ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
3456 if self.tcx.expr_is_lval(&oprnd) {
3457 // Lvalues may legitimately have unsized types.
3458 // For example, dereferences of a fat pointer and
3459 // the last field of a struct can be unsized.
3460 ExpectHasType(mt.ty)
3461 } else {
3462 Expectation::rvalue_hint(self, mt.ty)
3463 }
3464 }
3465 _ => NoExpectation
c34b1796 3466 }
a7813a04
XL
3467 });
3468 let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
3469 self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
3470
3471 let tm = ty::TypeAndMut { ty: self.expr_ty(&oprnd), mutbl: mutbl };
3472 let oprnd_t = if tm.ty.references_error() {
3473 tcx.types.err
c34b1796 3474 } else {
a7813a04
XL
3475 // Note: at this point, we cannot say what the best lifetime
3476 // is to use for resulting pointer. We want to use the
3477 // shortest lifetime possible so as to avoid spurious borrowck
3478 // errors. Moreover, the longest lifetime will depend on the
3479 // precise details of the value whose address is being taken
3480 // (and how long it is valid), which we don't know yet until type
3481 // inference is complete.
3482 //
3483 // Therefore, here we simply generate a region variable. The
3484 // region inferencer will then select the ultimate value.
3485 // Finally, borrowck is charged with guaranteeing that the
3486 // value whose address was taken can actually be made to live
3487 // as long as it needs to live.
3488 let region = self.next_region_var(infer::AddrOfRegion(expr.span));
3489 tcx.mk_ref(tcx.mk_region(region), tm)
3490 };
3491 self.write_ty(id, oprnd_t);
c34b1796 3492 }
a7813a04
XL
3493 hir::ExprPath(ref maybe_qself, ref path) => {
3494 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
3495 self.to_ty(&qself.ty)
3496 });
3497
3498 let path_res = if let Some(&d) = tcx.def_map.borrow().get(&id) {
3499 d
3500 } else if let Some(hir::QSelf { position: 0, .. }) = *maybe_qself {
3501 // Create some fake resolution that can't possibly be a type.
3502 def::PathResolution {
3503 base_def: Def::Mod(tcx.map.local_def_id(ast::CRATE_NODE_ID)),
3504 depth: path.segments.len()
3505 }
3506 } else {
3507 span_bug!(expr.span, "unbound path {:?}", expr)
3508 };
3509
3510 if let Some((opt_ty, segments, def)) =
3511 self.resolve_ty_and_def_ufcs(path_res, opt_self_ty, path,
3512 expr.span, expr.id) {
3513 if def != Def::Err {
3514 let (scheme, predicates) = self.type_scheme_and_predicates_for_def(expr.span,
3515 def);
3516 self.instantiate_path(segments, scheme, &predicates,
3517 opt_ty, def, expr.span, id);
3518 } else {
3519 self.set_tainted_by_errors();
3520 self.write_ty(id, self.tcx.types.err);
3521 }
3522 }
1a4d82fc 3523
a7813a04
XL
3524 // We always require that the type provided as the value for
3525 // a type parameter outlives the moment of instantiation.
3526 self.opt_node_ty_substs(expr.id, |item_substs| {
3527 self.add_wf_bounds(&item_substs.substs, expr);
3528 });
1a4d82fc 3529 }
a7813a04
XL
3530 hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
3531 for output in outputs {
3532 self.check_expr(output);
3533 }
3534 for input in inputs {
3535 self.check_expr(input);
3536 }
3537 self.write_nil(id);
1a4d82fc 3538 }
a7813a04
XL
3539 hir::ExprBreak(_) => { self.write_ty(id, self.next_diverging_ty_var()); }
3540 hir::ExprAgain(_) => { self.write_ty(id, self.next_diverging_ty_var()); }
3541 hir::ExprRet(ref expr_opt) => {
3542 match self.ret_ty {
3543 ty::FnConverging(result_type) => {
3544 if let Some(ref e) = *expr_opt {
3545 self.check_expr_coercable_to_type(&e, result_type);
3546 } else {
3547 let eq_result = self.eq_types(false,
3548 TypeOrigin::Misc(expr.span),
3549 result_type,
3550 tcx.mk_nil())
3551 // FIXME(#32730) propagate obligations
3552 .map(|InferOk { obligations, .. }| assert!(obligations.is_empty()));
3553 if eq_result.is_err() {
1a4d82fc 3554 span_err!(tcx.sess, expr.span, E0069,
a7813a04
XL
3555 "`return;` in a function whose return type is not `()`");
3556 }
1a4d82fc
JJ
3557 }
3558 }
a7813a04
XL
3559 ty::FnDiverging => {
3560 if let Some(ref e) = *expr_opt {
3561 self.check_expr(&e);
3562 }
3563 span_err!(tcx.sess, expr.span, E0166,
3564 "`return` in a function declared as diverging");
1a4d82fc 3565 }
1a4d82fc 3566 }
a7813a04
XL
3567 self.write_ty(id, self.next_diverging_ty_var());
3568 }
3569 hir::ExprAssign(ref lhs, ref rhs) => {
3570 self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
1a4d82fc 3571
a7813a04
XL
3572 let tcx = self.tcx;
3573 if !tcx.expr_is_lval(&lhs) {
3574 span_err!(tcx.sess, expr.span, E0070,
3575 "invalid left-hand side expression");
3576 }
1a4d82fc 3577
a7813a04
XL
3578 let lhs_ty = self.expr_ty(&lhs);
3579 self.check_expr_coercable_to_type(&rhs, lhs_ty);
3580 let rhs_ty = self.expr_ty(&rhs);
1a4d82fc 3581
a7813a04 3582 self.require_expr_have_sized_type(&lhs, traits::AssignmentLhsSized);
e9174d1e 3583
a7813a04
XL
3584 if lhs_ty.references_error() || rhs_ty.references_error() {
3585 self.write_error(id);
3586 } else {
3587 self.write_nil(id);
3588 }
e9174d1e 3589 }
a7813a04
XL
3590 hir::ExprIf(ref cond, ref then_blk, ref opt_else_expr) => {
3591 self.check_then_else(&cond, &then_blk, opt_else_expr.as_ref().map(|e| &**e),
3592 id, expr.span, expected);
3593 }
3594 hir::ExprWhile(ref cond, ref body, _) => {
3595 self.check_expr_has_type(&cond, tcx.types.bool);
3596 self.check_block_no_value(&body);
3597 let cond_ty = self.expr_ty(&cond);
3598 let body_ty = self.node_ty(body.id);
3599 if cond_ty.references_error() || body_ty.references_error() {
3600 self.write_error(id);
1a4d82fc 3601 }
a7813a04
XL
3602 else {
3603 self.write_nil(id);
3604 }
3605 }
3606 hir::ExprLoop(ref body, _) => {
3607 self.check_block_no_value(&body);
3608 if !may_break(tcx, expr.id, &body) {
3609 self.write_ty(id, self.next_diverging_ty_var());
3610 } else {
3611 self.write_nil(id);
3612 }
3613 }
3614 hir::ExprMatch(ref discrim, ref arms, match_src) => {
3615 self.check_match(expr, &discrim, arms, expected, match_src);
3616 }
3617 hir::ExprClosure(capture, ref decl, ref body, _) => {
3618 self.check_expr_closure(expr, capture, &decl, &body, expected);
3619 }
3620 hir::ExprBlock(ref b) => {
3621 self.check_block_with_expected(&b, expected);
3622 self.write_ty(id, self.node_ty(b.id));
3623 }
3624 hir::ExprCall(ref callee, ref args) => {
3625 self.check_call(expr, &callee, &args[..], expected);
54a0048b 3626
a7813a04
XL
3627 // we must check that return type of called functions is WF:
3628 let ret_ty = self.expr_ty(expr);
3629 self.register_wf_obligation(ret_ty, expr.span, traits::MiscObligation);
3630 }
3631 hir::ExprMethodCall(name, ref tps, ref args) => {
3632 self.check_method_call(expr, name, &args[..], &tps[..], expected, lvalue_pref);
3633 let arg_tys = args.iter().map(|a| self.expr_ty(&a));
3634 let args_err = arg_tys.fold(false, |rest_err, a| rest_err || a.references_error());
3635 if args_err {
3636 self.write_error(id);
3637 }
3638 }
3639 hir::ExprCast(ref e, ref t) => {
3640 if let hir::TyFixedLengthVec(_, ref count_expr) = t.node {
3641 self.check_expr_with_hint(&count_expr, tcx.types.usize);
3642 }
54a0048b 3643
a7813a04
XL
3644 // Find the type of `e`. Supply hints based on the type we are casting to,
3645 // if appropriate.
3646 let t_cast = self.to_ty(t);
3647 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3648 self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
3649 let t_expr = self.expr_ty(e);
3650 let t_cast = self.resolve_type_vars_if_possible(&t_cast);
3651
3652 // Eagerly check for some obvious errors.
3653 if t_expr.references_error() || t_cast.references_error() {
3654 self.write_error(id);
54a0048b 3655 } else {
a7813a04
XL
3656 // Write a type for the whole expression, assuming everything is going
3657 // to work out Ok.
3658 self.write_ty(id, t_cast);
3659
3660 // Defer other checks until we're done type checking.
3661 let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
3662 match cast::CastCheck::new(self, e, t_expr, t_cast, t.span, expr.span) {
3663 Ok(cast_check) => {
3664 deferred_cast_checks.push(cast_check);
3665 }
3666 Err(ErrorReported) => {
3667 self.write_error(id);
3668 }
1a4d82fc 3669 }
1a4d82fc 3670 }
a7813a04
XL
3671 }
3672 hir::ExprType(ref e, ref t) => {
3673 let typ = self.to_ty(&t);
3674 self.check_expr_eq_type(&e, typ);
3675 self.write_ty(id, typ);
3676 }
3677 hir::ExprVec(ref args) => {
3678 let uty = expected.to_option(self).and_then(|uty| {
1a4d82fc 3679 match uty.sty {
62682a34 3680 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
1a4d82fc
JJ
3681 _ => None
3682 }
a7813a04 3683 });
1a4d82fc 3684
a7813a04
XL
3685 let mut unified = self.next_ty_var();
3686 let coerce_to = uty.unwrap_or(unified);
1a4d82fc 3687
a7813a04
XL
3688 for (i, e) in args.iter().enumerate() {
3689 self.check_expr_with_hint(e, coerce_to);
3690 let e_ty = self.expr_ty(e);
3691 let origin = TypeOrigin::Misc(e.span);
1a4d82fc 3692
a7813a04
XL
3693 // Special-case the first element, as it has no "previous expressions".
3694 let result = if i == 0 {
3695 self.try_coerce(e, coerce_to)
3696 } else {
3697 let prev_elems = || args[..i].iter().map(|e| &**e);
3698 self.try_find_coercion_lub(origin, prev_elems, unified, e)
3699 };
3700
3701 match result {
3702 Ok(ty) => unified = ty,
3703 Err(e) => {
3704 self.report_mismatched_types(origin, unified, e_ty, e);
3705 }
1a4d82fc 3706 }
a7813a04
XL
3707 }
3708 self.write_ty(id, tcx.mk_array(unified, args.len()));
3709 }
3710 hir::ExprRepeat(ref element, ref count_expr) => {
3711 self.check_expr_has_type(&count_expr, tcx.types.usize);
3712 let count = eval_repeat_count(self.tcx.global_tcx(), &count_expr);
3713
3714 let uty = match expected {
3715 ExpectHasType(uty) => {
3716 match uty.sty {
3717 ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
3718 _ => None
3719 }
1a4d82fc 3720 }
a7813a04 3721 _ => None
1a4d82fc 3722 };
1a4d82fc 3723
a7813a04
XL
3724 let (element_ty, t) = match uty {
3725 Some(uty) => {
3726 self.check_expr_coercable_to_type(&element, uty);
3727 (uty, uty)
3728 }
3729 None => {
3730 let t: Ty = self.next_ty_var();
3731 self.check_expr_has_type(&element, t);
3732 (self.expr_ty(&element), t)
3733 }
3734 };
1a4d82fc 3735
a7813a04
XL
3736 if count > 1 {
3737 // For [foo, ..n] where n > 1, `foo` must have
3738 // Copy type:
3739 self.require_type_meets(t, expr.span, traits::RepeatVec, ty::BoundCopy);
3740 }
62682a34 3741
a7813a04
XL
3742 if element_ty.references_error() {
3743 self.write_error(id);
3744 } else {
3745 let t = tcx.mk_array(t, count);
3746 self.write_ty(id, t);
3747 }
3748 }
3749 hir::ExprTup(ref elts) => {
3750 let flds = expected.only_has_type(self).and_then(|ty| {
3751 match ty.sty {
3752 ty::TyTuple(ref flds) => Some(&flds[..]),
3753 _ => None
7453a54e 3754 }
a7813a04
XL
3755 });
3756 let mut err_field = false;
3757
3758 let elt_ts = elts.iter().enumerate().map(|(i, e)| {
3759 let t = match flds {
3760 Some(ref fs) if i < fs.len() => {
3761 let ety = fs[i];
3762 self.check_expr_coercable_to_type(&e, ety);
3763 ety
3764 }
3765 _ => {
3766 self.check_expr_with_expectation(&e, NoExpectation);
3767 self.expr_ty(&e)
3768 }
3769 };
3770 err_field = err_field || t.references_error();
3771 t
3772 }).collect();
3773 if err_field {
3774 self.write_error(id);
3775 } else {
3776 let typ = tcx.mk_tup(elt_ts);
3777 self.write_ty(id, typ);
d9579d0f 3778 }
a7813a04
XL
3779 }
3780 hir::ExprStruct(ref path, ref fields, ref base_expr) => {
3781 self.check_expr_struct(expr, path, fields, base_expr);
54a0048b 3782
a7813a04
XL
3783 self.require_expr_have_sized_type(expr, traits::StructInitializerSized);
3784 }
3785 hir::ExprField(ref base, ref field) => {
3786 self.check_field(expr, lvalue_pref, &base, field);
3787 }
3788 hir::ExprTupField(ref base, idx) => {
3789 self.check_tup_field(expr, lvalue_pref, &base, idx);
3790 }
3791 hir::ExprIndex(ref base, ref idx) => {
3792 self.check_expr_with_lvalue_pref(&base, lvalue_pref);
3793 self.check_expr(&idx);
d9579d0f 3794
a7813a04
XL
3795 let base_t = self.expr_ty(&base);
3796 let idx_t = self.expr_ty(&idx);
1a4d82fc 3797
a7813a04
XL
3798 if base_t.references_error() {
3799 self.write_ty(id, base_t);
3800 } else if idx_t.references_error() {
3801 self.write_ty(id, idx_t);
3802 } else {
3803 let base_t = self.structurally_resolved_type(expr.span, base_t);
3804 match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
3805 Some((index_ty, element_ty)) => {
3806 let idx_expr_ty = self.expr_ty(idx);
3807 self.demand_eqtype(expr.span, index_ty, idx_expr_ty);
3808 self.write_ty(id, element_ty);
3809 }
3810 None => {
3811 self.check_expr_has_type(&idx, self.tcx.types.err);
3812 let mut err = self.type_error_struct(
3813 expr.span,
3814 |actual| {
3815 format!("cannot index a value of type `{}`",
3816 actual)
3817 },
3818 base_t,
3819 None);
3820 // Try to give some advice about indexing tuples.
3821 if let ty::TyTuple(_) = base_t.sty {
3822 let mut needs_note = true;
3823 // If the index is an integer, we can show the actual
3824 // fixed expression:
3825 if let hir::ExprLit(ref lit) = idx.node {
3826 if let ast::LitKind::Int(i,
3827 ast::LitIntType::Unsuffixed) = lit.node {
3828 let snip = tcx.sess.codemap().span_to_snippet(base.span);
3829 if let Ok(snip) = snip {
3830 err.span_suggestion(expr.span,
3831 "to access tuple elements, \
3832 use tuple indexing syntax \
3833 as shown",
3834 format!("{}.{}", snip, i));
3835 needs_note = false;
3836 }
3837 }
3838 }
3839 if needs_note {
3840 err.help("to access tuple elements, use tuple indexing \
3841 syntax (e.g. `tuple.0`)");
3842 }
3843 }
3844 err.emit();
3845 self.write_ty(id, self.tcx().types.err);
3846 }
3847 }
3848 }
3849 }
1a4d82fc 3850 }
1a4d82fc 3851
a7813a04
XL
3852 debug!("type of expr({}) {} is...", expr.id,
3853 pprust::expr_to_string(expr));
3854 debug!("... {:?}, expected is {:?}",
3855 self.expr_ty(expr),
3856 expected);
1a4d82fc
JJ
3857 }
3858
a7813a04
XL
3859 pub fn resolve_ty_and_def_ufcs<'b>(&self,
3860 path_res: def::PathResolution,
3861 opt_self_ty: Option<Ty<'tcx>>,
3862 path: &'b hir::Path,
3863 span: Span,
3864 node_id: ast::NodeId)
3865 -> Option<(Option<Ty<'tcx>>, &'b [hir::PathSegment], Def)>
3866 {
3867
3868 // If fully resolved already, we don't have to do anything.
3869 if path_res.depth == 0 {
3870 Some((opt_self_ty, &path.segments, path_res.base_def))
3871 } else {
3872 let def = path_res.base_def;
3873 let ty_segments = path.segments.split_last().unwrap().1;
3874 let base_ty_end = path.segments.len() - path_res.depth;
3875 let (ty, _def) = AstConv::finish_resolving_def_to_ty(self, self, span,
3876 PathParamMode::Optional,
3877 def,
3878 opt_self_ty,
3879 node_id,
3880 &ty_segments[..base_ty_end],
3881 &ty_segments[base_ty_end..]);
3882 let item_segment = path.segments.last().unwrap();
3883 let item_name = item_segment.name;
3884 let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
3885 Ok(def) => Some(def),
3886 Err(error) => {
3887 let def = match error {
3888 method::MethodError::PrivateMatch(def) => Some(def),
3889 _ => None,
3890 };
3891 if item_name != keywords::Invalid.name() {
3892 self.report_method_error(span, ty, item_name, None, error);
3893 }
3894 def
3895 }
3896 };
3897
3898 if let Some(def) = def {
3899 // Write back the new resolution.
3900 self.tcx().def_map.borrow_mut().insert(node_id, def::PathResolution {
3901 base_def: def,
3902 depth: 0,
3903 });
3904 Some((Some(ty), slice::ref_slice(item_segment), def))
3905 } else {
3906 self.write_error(node_id);
3907 None
3908 }
1a4d82fc
JJ
3909 }
3910 }
1a4d82fc 3911
a7813a04
XL
3912 pub fn check_decl_initializer(&self,
3913 local: &'gcx hir::Local,
3914 init: &'gcx hir::Expr)
3915 {
3916 let ref_bindings = self.tcx.pat_contains_ref_binding(&local.pat);
3917
3918 let local_ty = self.local_ty(init.span, local.id);
3919 if let Some(m) = ref_bindings {
3920 // Somewhat subtle: if we have a `ref` binding in the pattern,
3921 // we want to avoid introducing coercions for the RHS. This is
3922 // both because it helps preserve sanity and, in the case of
3923 // ref mut, for soundness (issue #23116). In particular, in
3924 // the latter case, we need to be clear that the type of the
3925 // referent for the reference that results is *equal to* the
3926 // type of the lvalue it is referencing, and not some
3927 // supertype thereof.
3928 self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
3929 let init_ty = self.expr_ty(init);
3930 self.demand_eqtype(init.span, init_ty, local_ty);
3931 } else {
3932 self.check_expr_coercable_to_type(init, local_ty)
3933 };
3934 }
1a4d82fc 3935
a7813a04
XL
3936 pub fn check_decl_local(&self, local: &'gcx hir::Local) {
3937 let tcx = self.tcx;
1a4d82fc 3938
a7813a04
XL
3939 let t = self.local_ty(local.span, local.id);
3940 self.write_ty(local.id, t);
1a4d82fc 3941
a7813a04
XL
3942 if let Some(ref init) = local.init {
3943 self.check_decl_initializer(local, &init);
3944 let init_ty = self.expr_ty(&init);
3945 if init_ty.references_error() {
3946 self.write_ty(local.id, init_ty);
3947 }
1a4d82fc 3948 }
1a4d82fc 3949
a7813a04
XL
3950 let pcx = PatCtxt {
3951 fcx: self,
3952 map: pat_id_map(&tcx.def_map, &local.pat),
3953 };
3954 pcx.check_pat(&local.pat, t);
3955 let pat_ty = self.node_ty(local.pat.id);
3956 if pat_ty.references_error() {
3957 self.write_ty(local.id, pat_ty);
3958 }
3959 }
3960
3961 pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
3962 let node_id;
3963 let mut saw_bot = false;
3964 let mut saw_err = false;
3965 match stmt.node {
3966 hir::StmtDecl(ref decl, id) => {
3967 node_id = id;
3968 match decl.node {
3969 hir::DeclLocal(ref l) => {
3970 self.check_decl_local(&l);
3971 let l_t = self.node_ty(l.id);
3972 saw_bot = saw_bot || self.type_var_diverges(l_t);
3973 saw_err = saw_err || l_t.references_error();
3974 }
3975 hir::DeclItem(_) => {/* ignore for now */ }
3976 }
3977 }
3978 hir::StmtExpr(ref expr, id) => {
3979 node_id = id;
3980 // Check with expected type of ()
3981 self.check_expr_has_type(&expr, self.tcx.mk_nil());
3982 let expr_ty = self.expr_ty(&expr);
3983 saw_bot = saw_bot || self.type_var_diverges(expr_ty);
3984 saw_err = saw_err || expr_ty.references_error();
3985 }
3986 hir::StmtSemi(ref expr, id) => {
3987 node_id = id;
3988 self.check_expr(&expr);
3989 let expr_ty = self.expr_ty(&expr);
3990 saw_bot |= self.type_var_diverges(expr_ty);
3991 saw_err |= expr_ty.references_error();
1a4d82fc 3992 }
1a4d82fc 3993 }
a7813a04
XL
3994 if saw_bot {
3995 self.write_ty(node_id, self.next_diverging_ty_var());
3996 }
3997 else if saw_err {
3998 self.write_error(node_id);
3999 }
4000 else {
4001 self.write_nil(node_id)
4002 }
1a4d82fc 4003 }
1a4d82fc 4004
a7813a04
XL
4005 pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
4006 self.check_block_with_expected(blk, ExpectHasType(self.tcx.mk_nil()));
4007 let blkty = self.node_ty(blk.id);
4008 if blkty.references_error() {
4009 self.write_error(blk.id);
4010 } else {
4011 let nilty = self.tcx.mk_nil();
4012 self.demand_suptype(blk.span, nilty, blkty);
4013 }
1a4d82fc 4014 }
1a4d82fc 4015
a7813a04
XL
4016 fn check_block_with_expected(&self,
4017 blk: &'gcx hir::Block,
4018 expected: Expectation<'tcx>) {
4019 let prev = {
4020 let mut fcx_ps = self.ps.borrow_mut();
4021 let unsafety_state = fcx_ps.recurse(blk);
4022 replace(&mut *fcx_ps, unsafety_state)
4023 };
1a4d82fc 4024
a7813a04
XL
4025 let mut warned = false;
4026 let mut any_diverges = false;
4027 let mut any_err = false;
4028 for s in &blk.stmts {
4029 self.check_stmt(s);
4030 let s_id = s.node.id();
4031 let s_ty = self.node_ty(s_id);
4032 if any_diverges && !warned && match s.node {
4033 hir::StmtDecl(ref decl, _) => {
4034 match decl.node {
4035 hir::DeclLocal(_) => true,
4036 _ => false,
4037 }
1a4d82fc 4038 }
a7813a04
XL
4039 hir::StmtExpr(_, _) | hir::StmtSemi(_, _) => true,
4040 } {
4041 self.tcx
1a4d82fc
JJ
4042 .sess
4043 .add_lint(lint::builtin::UNREACHABLE_CODE,
a7813a04
XL
4044 s_id,
4045 s.span,
4046 "unreachable statement".to_string());
4047 warned = true;
1a4d82fc 4048 }
a7813a04
XL
4049 any_diverges = any_diverges || self.type_var_diverges(s_ty);
4050 any_err = any_err || s_ty.references_error();
4051 }
4052 match blk.expr {
4053 None => if any_err {
4054 self.write_error(blk.id);
1a4d82fc 4055 } else if any_diverges {
a7813a04 4056 self.write_ty(blk.id, self.next_diverging_ty_var());
1a4d82fc 4057 } else {
a7813a04
XL
4058 self.write_nil(blk.id);
4059 },
4060 Some(ref e) => {
4061 if any_diverges && !warned {
4062 self.tcx
4063 .sess
4064 .add_lint(lint::builtin::UNREACHABLE_CODE,
4065 e.id,
4066 e.span,
4067 "unreachable expression".to_string());
4068 }
4069 let ety = match expected {
4070 ExpectHasType(ety) => {
4071 self.check_expr_coercable_to_type(&e, ety);
4072 ety
4073 }
4074 _ => {
4075 self.check_expr_with_expectation(&e, expected);
4076 self.expr_ty(&e)
4077 }
4078 };
1a4d82fc 4079
a7813a04
XL
4080 if any_err {
4081 self.write_error(blk.id);
4082 } else if any_diverges {
4083 self.write_ty(blk.id, self.next_diverging_ty_var());
4084 } else {
4085 self.write_ty(blk.id, ety);
4086 }
4087 }
4088 };
1a4d82fc 4089
a7813a04
XL
4090 *self.ps.borrow_mut() = prev;
4091 }
1a4d82fc 4092
1a4d82fc 4093
a7813a04
XL
4094 fn check_const_with_ty(&self,
4095 _: Span,
4096 e: &'gcx hir::Expr,
4097 declty: Ty<'tcx>) {
4098 // Gather locals in statics (because of block expressions).
4099 // This is technically unnecessary because locals in static items are forbidden,
4100 // but prevents type checking from blowing up before const checking can properly
4101 // emit an error.
4102 GatherLocalsVisitor { fcx: self }.visit_expr(e);
1a4d82fc 4103
a7813a04 4104 self.check_expr_coercable_to_type(e, declty);
1a4d82fc 4105
a7813a04
XL
4106 self.select_all_obligations_and_apply_defaults();
4107 self.closure_analyze_const(e);
4108 self.select_obligations_where_possible();
4109 self.check_casts();
4110 self.select_all_obligations_or_error();
4111
4112 self.regionck_expr(e);
4113 self.resolve_type_vars_in_expr(e);
4114 }
4115
4116 // Returns the type parameter count and the type for the given definition.
4117 fn type_scheme_and_predicates_for_def(&self,
4118 sp: Span,
4119 defn: Def)
4120 -> (TypeScheme<'tcx>, GenericPredicates<'tcx>) {
4121 match defn {
4122 Def::Local(_, nid) | Def::Upvar(_, nid, _, _) => {
4123 let typ = self.local_ty(sp, nid);
4124 (ty::TypeScheme { generics: ty::Generics::empty(), ty: typ },
4125 ty::GenericPredicates::empty())
1a4d82fc 4126 }
a7813a04
XL
4127 Def::Fn(id) | Def::Method(id) |
4128 Def::Static(id, _) | Def::Variant(_, id) |
4129 Def::Struct(id) | Def::Const(id) | Def::AssociatedConst(id) => {
4130 (self.tcx.lookup_item_type(id), self.tcx.lookup_predicates(id))
1a4d82fc 4131 }
a7813a04
XL
4132 Def::Trait(_) |
4133 Def::Enum(..) |
4134 Def::TyAlias(..) |
4135 Def::AssociatedTy(..) |
4136 Def::PrimTy(_) |
4137 Def::TyParam(..) |
4138 Def::Mod(..) |
4139 Def::ForeignMod(..) |
4140 Def::Label(..) |
4141 Def::SelfTy(..) |
4142 Def::Err => {
4143 span_bug!(sp, "expected value, found {:?}", defn);
1a4d82fc
JJ
4144 }
4145 }
1a4d82fc 4146 }
1a4d82fc 4147
a7813a04
XL
4148 // Instantiates the given path, which must refer to an item with the given
4149 // number of type parameters and type.
4150 pub fn instantiate_path(&self,
4151 segments: &[hir::PathSegment],
4152 type_scheme: TypeScheme<'tcx>,
4153 type_predicates: &ty::GenericPredicates<'tcx>,
4154 opt_self_ty: Option<Ty<'tcx>>,
4155 def: Def,
4156 span: Span,
4157 node_id: ast::NodeId) {
4158 debug!("instantiate_path(path={:?}, def={:?}, node_id={}, type_scheme={:?})",
4159 segments,
4160 def,
4161 node_id,
4162 type_scheme);
4163
4164 // We need to extract the type parameters supplied by the user in
4165 // the path `path`. Due to the current setup, this is a bit of a
4166 // tricky-process; the problem is that resolve only tells us the
4167 // end-point of the path resolution, and not the intermediate steps.
4168 // Luckily, we can (at least for now) deduce the intermediate steps
4169 // just from the end-point.
4170 //
4171 // There are basically four cases to consider:
4172 //
4173 // 1. Reference to a *type*, such as a struct or enum:
4174 //
4175 // mod a { struct Foo<T> { ... } }
4176 //
4177 // Because we don't allow types to be declared within one
4178 // another, a path that leads to a type will always look like
4179 // `a::b::Foo<T>` where `a` and `b` are modules. This implies
4180 // that only the final segment can have type parameters, and
4181 // they are located in the TypeSpace.
4182 //
4183 // *Note:* Generally speaking, references to types don't
4184 // actually pass through this function, but rather the
4185 // `ast_ty_to_ty` function in `astconv`. However, in the case
4186 // of struct patterns (and maybe literals) we do invoke
4187 // `instantiate_path` to get the general type of an instance of
4188 // a struct. (In these cases, there are actually no type
4189 // parameters permitted at present, but perhaps we will allow
4190 // them in the future.)
4191 //
4192 // 1b. Reference to an enum variant or tuple-like struct:
4193 //
4194 // struct foo<T>(...)
4195 // enum E<T> { foo(...) }
4196 //
4197 // In these cases, the parameters are declared in the type
4198 // space.
4199 //
4200 // 2. Reference to a *fn item*:
4201 //
4202 // fn foo<T>() { }
4203 //
4204 // In this case, the path will again always have the form
4205 // `a::b::foo::<T>` where only the final segment should have
4206 // type parameters. However, in this case, those parameters are
4207 // declared on a value, and hence are in the `FnSpace`.
4208 //
4209 // 3. Reference to a *method*:
4210 //
4211 // impl<A> SomeStruct<A> {
4212 // fn foo<B>(...)
4213 // }
4214 //
4215 // Here we can have a path like
4216 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
4217 // may appear in two places. The penultimate segment,
4218 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
4219 // final segment, `foo::<B>` contains parameters in fn space.
4220 //
4221 // 4. Reference to an *associated const*:
4222 //
4223 // impl<A> AnotherStruct<A> {
4224 // const FOO: B = BAR;
4225 // }
4226 //
4227 // The path in this case will look like
4228 // `a::b::AnotherStruct::<A>::FOO`, so the penultimate segment
4229 // only will have parameters in TypeSpace.
4230 //
4231 // The first step then is to categorize the segments appropriately.
4232
4233 assert!(!segments.is_empty());
4234
4235 let mut ufcs_associated = None;
4236 let mut segment_spaces: Vec<_>;
4237 match def {
4238 // Case 1 and 1b. Reference to a *type* or *enum variant*.
4239 Def::SelfTy(..) |
4240 Def::Struct(..) |
4241 Def::Variant(..) |
4242 Def::Enum(..) |
4243 Def::TyAlias(..) |
4244 Def::AssociatedTy(..) |
4245 Def::Trait(..) |
4246 Def::PrimTy(..) |
4247 Def::TyParam(..) => {
4248 // Everything but the final segment should have no
4249 // parameters at all.
4250 segment_spaces = vec![None; segments.len() - 1];
4251 segment_spaces.push(Some(subst::TypeSpace));
c34b1796 4252 }
1a4d82fc 4253
a7813a04
XL
4254 // Case 2. Reference to a top-level value.
4255 Def::Fn(..) |
4256 Def::Const(..) |
4257 Def::Static(..) => {
4258 segment_spaces = vec![None; segments.len() - 1];
4259 segment_spaces.push(Some(subst::FnSpace));
4260 }
1a4d82fc 4261
a7813a04
XL
4262 // Case 3. Reference to a method.
4263 Def::Method(def_id) => {
4264 let container = self.tcx.impl_or_trait_item(def_id).container();
4265 match container {
4266 ty::TraitContainer(trait_did) => {
4267 callee::check_legal_trait_for_method_call(self.ccx, span, trait_did)
4268 }
4269 ty::ImplContainer(_) => {}
4270 }
1a4d82fc 4271
a7813a04
XL
4272 if segments.len() >= 2 {
4273 segment_spaces = vec![None; segments.len() - 2];
4274 segment_spaces.push(Some(subst::TypeSpace));
4275 segment_spaces.push(Some(subst::FnSpace));
4276 } else {
4277 // `<T>::method` will end up here, and so can `T::method`.
4278 let self_ty = opt_self_ty.expect("UFCS sugared method missing Self");
4279 segment_spaces = vec![Some(subst::FnSpace)];
4280 ufcs_associated = Some((container, self_ty));
1a4d82fc 4281 }
1a4d82fc 4282 }
1a4d82fc 4283
a7813a04
XL
4284 Def::AssociatedConst(def_id) => {
4285 let container = self.tcx.impl_or_trait_item(def_id).container();
4286 match container {
4287 ty::TraitContainer(trait_did) => {
4288 callee::check_legal_trait_for_method_call(self.ccx, span, trait_did)
4289 }
4290 ty::ImplContainer(_) => {}
4291 }
1a4d82fc 4292
a7813a04
XL
4293 if segments.len() >= 2 {
4294 segment_spaces = vec![None; segments.len() - 2];
4295 segment_spaces.push(Some(subst::TypeSpace));
4296 segment_spaces.push(None);
4297 } else {
4298 // `<T>::CONST` will end up here, and so can `T::CONST`.
4299 let self_ty = opt_self_ty.expect("UFCS sugared const missing Self");
4300 segment_spaces = vec![None];
4301 ufcs_associated = Some((container, self_ty));
1a4d82fc 4302 }
1a4d82fc
JJ
4303 }
4304
a7813a04
XL
4305 // Other cases. Various nonsense that really shouldn't show up
4306 // here. If they do, an error will have been reported
4307 // elsewhere. (I hope)
4308 Def::Mod(..) |
4309 Def::ForeignMod(..) |
4310 Def::Local(..) |
4311 Def::Label(..) |
4312 Def::Upvar(..) => {
4313 segment_spaces = vec![None; segments.len()];
c34b1796 4314 }
1a4d82fc 4315
a7813a04
XL
4316 Def::Err => {
4317 self.set_tainted_by_errors();
4318 segment_spaces = vec![None; segments.len()];
d9579d0f 4319 }
a7813a04
XL
4320 }
4321 assert_eq!(segment_spaces.len(), segments.len());
4322
4323 // In `<T as Trait<A, B>>::method`, `A` and `B` are mandatory, but
4324 // `opt_self_ty` can also be Some for `Foo::method`, where Foo's
4325 // type parameters are not mandatory.
4326 let require_type_space = opt_self_ty.is_some() && ufcs_associated.is_none();
4327
4328 debug!("segment_spaces={:?}", segment_spaces);
4329
4330 // Next, examine the definition, and determine how many type
4331 // parameters we expect from each space.
4332 let type_defs = &type_scheme.generics.types;
4333 let region_defs = &type_scheme.generics.regions;
4334
4335 // Now that we have categorized what space the parameters for each
4336 // segment belong to, let's sort out the parameters that the user
4337 // provided (if any) into their appropriate spaces. We'll also report
4338 // errors if type parameters are provided in an inappropriate place.
4339 let mut substs = Substs::empty();
4340 for (&opt_space, segment) in segment_spaces.iter().zip(segments) {
4341 if let Some(space) = opt_space {
4342 self.push_explicit_parameters_from_segment_to_substs(space,
4343 span,
4344 type_defs,
4345 region_defs,
4346 segment,
4347 &mut substs);
d9579d0f 4348 } else {
a7813a04 4349 self.tcx.prohibit_type_params(slice::ref_slice(segment));
d9579d0f
AL
4350 }
4351 }
a7813a04
XL
4352 if let Some(self_ty) = opt_self_ty {
4353 if type_defs.len(subst::SelfSpace) == 1 {
4354 substs.types.push(subst::SelfSpace, self_ty);
4355 }
1a4d82fc 4356 }
c34b1796 4357
a7813a04
XL
4358 // Now we have to compare the types that the user *actually*
4359 // provided against the types that were *expected*. If the user
4360 // did not provide any types, then we want to substitute inference
4361 // variables. If the user provided some types, we may still need
4362 // to add defaults. If the user provided *too many* types, that's
4363 // a problem.
4364 for &space in &[subst::SelfSpace, subst::TypeSpace, subst::FnSpace] {
4365 self.adjust_type_parameters(span, space, type_defs,
4366 require_type_space, &mut substs);
4367 assert_eq!(substs.types.len(space), type_defs.len(space));
1a4d82fc 4368
a7813a04
XL
4369 self.adjust_region_parameters(span, space, region_defs, &mut substs);
4370 assert_eq!(substs.regions.len(space), region_defs.len(space));
4371 }
1a4d82fc 4372
a7813a04
XL
4373 // The things we are substituting into the type should not contain
4374 // escaping late-bound regions, and nor should the base type scheme.
4375 let substs = self.tcx.mk_substs(substs);
4376 assert!(!substs.has_regions_escaping_depth(0));
4377 assert!(!type_scheme.has_escaping_regions());
1a4d82fc 4378
a7813a04
XL
4379 // Add all the obligations that are required, substituting and
4380 // normalized appropriately.
4381 let bounds = self.instantiate_bounds(span, &substs, &type_predicates);
4382 self.add_obligations_for_parameters(
4383 traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
4384 &bounds);
1a4d82fc 4385
a7813a04
XL
4386 // Substitute the values for the type parameters into the type of
4387 // the referenced item.
4388 let ty_substituted = self.instantiate_type_scheme(span, &substs, &type_scheme.ty);
4389
4390
4391 if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
4392 // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
4393 // is inherent, there is no `Self` parameter, instead, the impl needs
4394 // type parameters, which we can infer by unifying the provided `Self`
4395 // with the substituted impl type.
4396 let impl_scheme = self.tcx.lookup_item_type(impl_def_id);
4397 assert_eq!(substs.types.len(subst::TypeSpace),
4398 impl_scheme.generics.types.len(subst::TypeSpace));
4399 assert_eq!(substs.regions.len(subst::TypeSpace),
4400 impl_scheme.generics.regions.len(subst::TypeSpace));
4401
4402 let impl_ty = self.instantiate_type_scheme(span, &substs, &impl_scheme.ty);
4403 match self.sub_types(false, TypeOrigin::Misc(span), self_ty, impl_ty) {
4404 Ok(InferOk { obligations, .. }) => {
4405 // FIXME(#32730) propagate obligations
4406 assert!(obligations.is_empty());
4407 }
4408 Err(_) => {
4409 span_bug!(span,
4410 "instantiate_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
4411 self_ty,
4412 impl_ty);
4413 }
1a4d82fc
JJ
4414 }
4415 }
1a4d82fc 4416
a7813a04
XL
4417 debug!("instantiate_path: type of {:?} is {:?}",
4418 node_id,
4419 ty_substituted);
4420 self.write_ty(node_id, ty_substituted);
4421 self.write_substs(node_id, ty::ItemSubsts {
4422 substs: substs
4423 });
1a4d82fc
JJ
4424 }
4425
4426 /// Finds the parameters that the user provided and adds them to `substs`. If too many
4427 /// parameters are provided, then reports an error and clears the output vector.
4428 ///
4429 /// We clear the output vector because that will cause the `adjust_XXX_parameters()` later to
4430 /// use inference variables. This seems less likely to lead to derived errors.
4431 ///
4432 /// Note that we *do not* check for *too few* parameters here. Due to the presence of defaults
4433 /// etc that is more complicated. I wanted however to do the reporting of *too many* parameters
4434 /// here because we can easily use the precise span of the N+1'th parameter.
a7813a04 4435 fn push_explicit_parameters_from_segment_to_substs(&self,
1a4d82fc
JJ
4436 space: subst::ParamSpace,
4437 span: Span,
4438 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4439 region_defs: &VecPerParamSpace<ty::RegionParameterDef>,
e9174d1e 4440 segment: &hir::PathSegment,
1a4d82fc
JJ
4441 substs: &mut Substs<'tcx>)
4442 {
4443 match segment.parameters {
e9174d1e 4444 hir::AngleBracketedParameters(ref data) => {
a7813a04
XL
4445 self.push_explicit_angle_bracketed_parameters_from_segment_to_substs(
4446 space, type_defs, region_defs, data, substs);
1a4d82fc
JJ
4447 }
4448
e9174d1e 4449 hir::ParenthesizedParameters(ref data) => {
a7813a04 4450 span_err!(self.tcx.sess, span, E0238,
1a4d82fc 4451 "parenthesized parameters may only be used with a trait");
a7813a04
XL
4452 self.push_explicit_parenthesized_parameters_from_segment_to_substs(
4453 space, span, type_defs, data, substs);
1a4d82fc
JJ
4454 }
4455 }
4456 }
4457
a7813a04 4458 fn push_explicit_angle_bracketed_parameters_from_segment_to_substs(&self,
1a4d82fc
JJ
4459 space: subst::ParamSpace,
4460 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
4461 region_defs: &VecPerParamSpace<ty::RegionParameterDef>,
e9174d1e 4462 data: &hir::AngleBracketedParameterData,
1a4d82fc
JJ
4463 substs: &mut Substs<'tcx>)
4464 {
4465 {
4466 let type_count = type_defs.len(space);
4467 assert_eq!(substs.types.len(space), 0);
4468 for (i, typ) in data.types.iter().enumerate() {
a7813a04 4469 let t = self.to_ty(&typ);
1a4d82fc
JJ
4470 if i < type_count {
4471 substs.types.push(space, t);
4472 } else if i == type_count {
a7813a04 4473 span_err!(self.tcx.sess, typ.span, E0087,
1a4d82fc 4474 "too many type parameters provided: \
62682a34
SL
4475 expected at most {} parameter{}, \
4476 found {} parameter{}",
4477 type_count,
4478 if type_count == 1 {""} else {"s"},
4479 data.types.len(),
4480 if data.types.len() == 1 {""} else {"s"});
1a4d82fc
JJ
4481 substs.types.truncate(space, 0);
4482 break;
4483 }
4484 }
4485 }
4486
9346a6ac 4487 if !data.bindings.is_empty() {
a7813a04 4488 span_err!(self.tcx.sess, data.bindings[0].span, E0182,
1a4d82fc
JJ
4489 "unexpected binding of associated item in expression path \
4490 (only allowed in type paths)");
4491 }
4492
4493 {
4494 let region_count = region_defs.len(space);
54a0048b 4495 assert_eq!(substs.regions.len(space), 0);
1a4d82fc 4496 for (i, lifetime) in data.lifetimes.iter().enumerate() {
a7813a04 4497 let r = ast_region_to_region(self.tcx, lifetime);
1a4d82fc 4498 if i < region_count {
54a0048b 4499 substs.regions.push(space, r);
1a4d82fc 4500 } else if i == region_count {
a7813a04 4501 span_err!(self.tcx.sess, lifetime.span, E0088,
1a4d82fc 4502 "too many lifetime parameters provided: \
62682a34 4503 expected {} parameter{}, found {} parameter{}",
1a4d82fc 4504 region_count,
62682a34
SL
4505 if region_count == 1 {""} else {"s"},
4506 data.lifetimes.len(),
4507 if data.lifetimes.len() == 1 {""} else {"s"});
54a0048b 4508 substs.regions.truncate(space, 0);
1a4d82fc
JJ
4509 break;
4510 }
4511 }
4512 }
4513 }
4514
4515 /// As with
4516 /// `push_explicit_angle_bracketed_parameters_from_segment_to_substs`,
4517 /// but intended for `Foo(A,B) -> C` form. This expands to
4518 /// roughly the same thing as `Foo<(A,B),C>`. One important
4519 /// difference has to do with the treatment of anonymous
4520 /// regions, which are translated into bound regions (NYI).
a7813a04 4521 fn push_explicit_parenthesized_parameters_from_segment_to_substs(&self,
1a4d82fc
JJ
4522 space: subst::ParamSpace,
4523 span: Span,
4524 type_defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
e9174d1e 4525 data: &hir::ParenthesizedParameterData,
1a4d82fc
JJ
4526 substs: &mut Substs<'tcx>)
4527 {
4528 let type_count = type_defs.len(space);
4529 if type_count < 2 {
a7813a04 4530 span_err!(self.tcx.sess, span, E0167,
1a4d82fc
JJ
4531 "parenthesized form always supplies 2 type parameters, \
4532 but only {} parameter(s) were expected",
4533 type_count);
4534 }
4535
4536 let input_tys: Vec<Ty> =
a7813a04 4537 data.inputs.iter().map(|ty| self.to_ty(&ty)).collect();
1a4d82fc 4538
a7813a04 4539 let tuple_ty = self.tcx.mk_tup(input_tys);
1a4d82fc
JJ
4540
4541 if type_count >= 1 {
4542 substs.types.push(space, tuple_ty);
4543 }
4544
4545 let output_ty: Option<Ty> =
a7813a04 4546 data.output.as_ref().map(|ty| self.to_ty(&ty));
1a4d82fc
JJ
4547
4548 let output_ty =
a7813a04 4549 output_ty.unwrap_or(self.tcx.mk_nil());
1a4d82fc
JJ
4550
4551 if type_count >= 2 {
4552 substs.types.push(space, output_ty);
4553 }
4554 }
4555
a7813a04 4556 fn adjust_type_parameters(&self,
1a4d82fc
JJ
4557 span: Span,
4558 space: ParamSpace,
4559 defs: &VecPerParamSpace<ty::TypeParameterDef<'tcx>>,
c34b1796 4560 require_type_space: bool,
1a4d82fc
JJ
4561 substs: &mut Substs<'tcx>)
4562 {
4563 let provided_len = substs.types.len(space);
4564 let desired = defs.get_slice(space);
4565 let required_len = desired.iter()
4566 .take_while(|d| d.default.is_none())
4567 .count();
4568
4569 debug!("adjust_type_parameters(space={:?}, \
4570 provided_len={}, \
4571 desired_len={}, \
4572 required_len={})",
4573 space,
4574 provided_len,
4575 desired.len(),
4576 required_len);
4577
4578 // Enforced by `push_explicit_parameters_from_segment_to_substs()`.
4579 assert!(provided_len <= desired.len());
4580
4581 // Nothing specified at all: supply inference variables for
4582 // everything.
c34b1796 4583 if provided_len == 0 && !(require_type_space && space == subst::TypeSpace) {
c1a9b12d 4584 substs.types.replace(space, Vec::new());
a7813a04 4585 self.type_vars_for_defs(span, space, substs, &desired[..]);
1a4d82fc
JJ
4586 return;
4587 }
4588
4589 // Too few parameters specified: report an error and use Err
4590 // for everything.
4591 if provided_len < required_len {
4592 let qualifier =
4593 if desired.len() != required_len { "at least " } else { "" };
a7813a04 4594 span_err!(self.tcx.sess, span, E0089,
62682a34
SL
4595 "too few type parameters provided: expected {}{} parameter{}, \
4596 found {} parameter{}",
4597 qualifier, required_len,
4598 if required_len == 1 {""} else {"s"},
4599 provided_len,
4600 if provided_len == 1 {""} else {"s"});
a7813a04 4601 substs.types.replace(space, vec![self.tcx.types.err; desired.len()]);
1a4d82fc
JJ
4602 return;
4603 }
4604
4605 // Otherwise, add in any optional parameters that the user
4606 // omitted. The case of *too many* parameters is handled
4607 // already by
4608 // push_explicit_parameters_from_segment_to_substs(). Note
4609 // that the *default* type are expressed in terms of all prior
4610 // parameters, so we have to substitute as we go with the
4611 // partial substitution that we have built up.
85aaf69f 4612 for i in provided_len..desired.len() {
1a4d82fc 4613 let default = desired[i].default.unwrap();
a7813a04 4614 let default = default.subst_spanned(self.tcx, substs, Some(span));
1a4d82fc
JJ
4615 substs.types.push(space, default);
4616 }
4617 assert_eq!(substs.types.len(space), desired.len());
4618
62682a34 4619 debug!("Final substs: {:?}", substs);
1a4d82fc
JJ
4620 }
4621
a7813a04 4622 fn adjust_region_parameters(&self,
1a4d82fc
JJ
4623 span: Span,
4624 space: ParamSpace,
4625 defs: &VecPerParamSpace<ty::RegionParameterDef>,
4626 substs: &mut Substs)
4627 {
54a0048b 4628 let provided_len = substs.regions.len(space);
1a4d82fc
JJ
4629 let desired = defs.get_slice(space);
4630
4631 // Enforced by `push_explicit_parameters_from_segment_to_substs()`.
4632 assert!(provided_len <= desired.len());
4633
4634 // If nothing was provided, just use inference variables.
4635 if provided_len == 0 {
54a0048b 4636 substs.regions.replace(
1a4d82fc 4637 space,
a7813a04 4638 self.region_vars_for_defs(span, desired));
1a4d82fc
JJ
4639 return;
4640 }
4641
4642 // If just the right number were provided, everybody is happy.
4643 if provided_len == desired.len() {
4644 return;
4645 }
4646
4647 // Otherwise, too few were provided. Report an error and then
4648 // use inference variables.
a7813a04 4649 span_err!(self.tcx.sess, span, E0090,
62682a34
SL
4650 "too few lifetime parameters provided: expected {} parameter{}, \
4651 found {} parameter{}",
4652 desired.len(),
4653 if desired.len() == 1 {""} else {"s"},
4654 provided_len,
4655 if provided_len == 1 {""} else {"s"});
1a4d82fc 4656
54a0048b 4657 substs.regions.replace(
1a4d82fc 4658 space,
a7813a04 4659 self.region_vars_for_defs(span, desired));
1a4d82fc 4660 }
1a4d82fc 4661
a7813a04
XL
4662 fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
4663 -> Ty<'tcx>
4664 where F: Fn() -> Ty<'tcx>
4665 {
4666 let mut ty = self.resolve_type_vars_with_obligations(ty);
4667
4668 if ty.is_ty_var() {
4669 let alternative = f();
4670
4671 // If not, error.
4672 if alternative.is_ty_var() || alternative.references_error() {
4673 if !self.is_tainted_by_errors() {
4674 self.type_error_message(sp, |_actual| {
4675 "the type of this value must be known in this context".to_string()
4676 }, ty, None);
4677 }
4678 self.demand_suptype(sp, self.tcx.types.err, ty);
4679 ty = self.tcx.types.err;
4680 } else {
4681 self.demand_suptype(sp, alternative, ty);
4682 ty = alternative;
4683 }
85aaf69f 4684 }
1a4d82fc 4685
a7813a04
XL
4686 ty
4687 }
1a4d82fc 4688
a7813a04
XL
4689 // Resolves `typ` by a single level if `typ` is a type variable. If no
4690 // resolution is possible, then an error is reported.
4691 pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
4692 self.structurally_resolve_type_or_else(sp, ty, || {
4693 self.tcx.types.err
4694 })
4695 }
85aaf69f
SL
4696}
4697
1a4d82fc 4698// Returns true if b contains a break that can exit from b
a7813a04 4699pub fn may_break(tcx: TyCtxt, id: ast::NodeId, b: &hir::Block) -> bool {
1a4d82fc
JJ
4700 // First: is there an unlabeled break immediately
4701 // inside the loop?
7453a54e 4702 (loop_query(&b, |e| {
1a4d82fc 4703 match *e {
e9174d1e 4704 hir::ExprBreak(None) => true,
1a4d82fc
JJ
4705 _ => false
4706 }
4707 })) ||
c34b1796
AL
4708 // Second: is there a labeled break with label
4709 // <id> nested anywhere inside the loop?
1a4d82fc 4710 (block_query(b, |e| {
e9174d1e 4711 if let hir::ExprBreak(Some(_)) = e.node {
a7813a04 4712 lookup_full_def(tcx, e.span, e.id) == Def::Label(id)
c34b1796
AL
4713 } else {
4714 false
4715 }
4716 }))
1a4d82fc
JJ
4717}
4718
4719pub fn check_bounds_are_used<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
9cc50fc6 4720 tps: &[hir::TyParam],
1a4d82fc 4721 ty: Ty<'tcx>) {
62682a34
SL
4722 debug!("check_bounds_are_used(n_tps={}, ty={:?})",
4723 tps.len(), ty);
1a4d82fc
JJ
4724
4725 // make a vector of booleans initially false, set to true when used
9346a6ac 4726 if tps.is_empty() { return; }
c1a9b12d 4727 let mut tps_used = vec![false; tps.len()];
1a4d82fc 4728
c1a9b12d
SL
4729 for leaf_ty in ty.walk() {
4730 if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
4731 debug!("Found use of ty param num {}", idx);
4732 tps_used[idx as usize] = true;
4733 }
4734 }
1a4d82fc
JJ
4735
4736 for (i, b) in tps_used.iter().enumerate() {
4737 if !*b {
92a42be0 4738 span_err!(ccx.tcx.sess, tps[i].span, E0091,
1a4d82fc 4739 "type parameter `{}` is unused",
b039eaaf 4740 tps[i].name);
1a4d82fc
JJ
4741 }
4742 }
4743}