PageRenderTime 87ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/src/librustc_typeck/check/mod.rs

http://github.com/eholk/rust
Rust | 4689 lines | 3488 code | 452 blank | 749 comment | 400 complexity | 9b4383ca6555cbae709d474ecb8fd3d0 MD5 | raw file
Possible License(s): AGPL-1.0, BSD-2-Clause, 0BSD, Apache-2.0, MIT, LGPL-2.0
  1. // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
  2. // file at the top-level directory of this distribution and at
  3. // http://rust-lang.org/COPYRIGHT.
  4. //
  5. // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
  6. // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
  7. // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
  8. // option. This file may not be copied, modified, or distributed
  9. // except according to those terms.
  10. /*
  11. # check.rs
  12. Within the check phase of type check, we check each item one at a time
  13. (bodies of function expressions are checked as part of the containing
  14. function). Inference is used to supply types wherever they are
  15. unknown.
  16. By far the most complex case is checking the body of a function. This
  17. can be broken down into several distinct phases:
  18. - gather: creates type variables to represent the type of each local
  19. variable and pattern binding.
  20. - main: the main pass does the lion's share of the work: it
  21. determines the types of all expressions, resolves
  22. methods, checks for most invalid conditions, and so forth. In
  23. some cases, where a type is unknown, it may create a type or region
  24. variable and use that as the type of an expression.
  25. In the process of checking, various constraints will be placed on
  26. these type variables through the subtyping relationships requested
  27. through the `demand` module. The `infer` module is in charge
  28. of resolving those constraints.
  29. - regionck: after main is complete, the regionck pass goes over all
  30. types looking for regions and making sure that they did not escape
  31. into places they are not in scope. This may also influence the
  32. final assignments of the various region variables if there is some
  33. flexibility.
  34. - vtable: find and records the impls to use for each trait bound that
  35. appears on a type parameter.
  36. - writeback: writes the final types within a function body, replacing
  37. type variables with their final inferred types. These final types
  38. are written into the `tcx.node_types` table, which should *never* contain
  39. any reference to a type variable.
  40. ## Intermediate types
  41. While type checking a function, the intermediate types for the
  42. expressions, blocks, and so forth contained within the function are
  43. stored in `fcx.node_types` and `fcx.item_substs`. These types
  44. may contain unresolved type variables. After type checking is
  45. complete, the functions in the writeback module are used to take the
  46. types from this table, resolve them, and then write them into their
  47. permanent home in the type context `tcx`.
  48. This means that during inferencing you should use `fcx.write_ty()`
  49. and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
  50. nodes within the function.
  51. The types of top-level items, which never contain unbound type
  52. variables, are stored directly into the `tcx` tables.
  53. n.b.: A type variable is not the same thing as a type parameter. A
  54. type variable is rather an "instance" of a type parameter: that is,
  55. given a generic function `fn foo<T>(t: T)`: while checking the
  56. function `foo`, the type `ty_param(0)` refers to the type `T`, which
  57. is treated in abstract. When `foo()` is called, however, `T` will be
  58. substituted for a fresh type variable `N`. This variable will
  59. eventually be resolved to some concrete type (which might itself be
  60. type parameter).
  61. */
  62. pub use self::Expectation::*;
  63. use self::coercion::{CoerceMany, DynamicCoerceMany};
  64. pub use self::compare_method::{compare_impl_method, compare_const_impl};
  65. use self::TupleArgumentsFlag::*;
  66. use astconv::AstConv;
  67. use fmt_macros::{Parser, Piece, Position};
  68. use hir::def::{Def, CtorKind};
  69. use hir::def_id::{CrateNum, DefId, LOCAL_CRATE};
  70. use rustc_back::slice::ref_slice;
  71. use rustc::infer::{self, InferCtxt, InferOk, RegionVariableOrigin};
  72. use rustc::infer::type_variable::{TypeVariableOrigin};
  73. use rustc::middle::region::CodeExtent;
  74. use rustc::ty::subst::{Kind, Subst, Substs};
  75. use rustc::traits::{self, FulfillmentContext, ObligationCause, ObligationCauseCode, Reveal};
  76. use rustc::ty::{ParamTy, LvaluePreference, NoPreference, PreferMutLvalue};
  77. use rustc::ty::{self, Ty, TyCtxt, Visibility};
  78. use rustc::ty::{MethodCall, MethodCallee};
  79. use rustc::ty::adjustment::{Adjust, Adjustment, AutoBorrow};
  80. use rustc::ty::fold::{BottomUpFolder, TypeFoldable};
  81. use rustc::ty::maps::Providers;
  82. use rustc::ty::util::{Representability, IntTypeExt};
  83. use errors::DiagnosticBuilder;
  84. use require_c_abi_if_variadic;
  85. use session::{Session, CompileResult};
  86. use TypeAndSubsts;
  87. use lint;
  88. use util::common::{ErrorReported, indenter};
  89. use util::nodemap::{DefIdMap, FxHashMap, NodeMap};
  90. use std::cell::{Cell, RefCell};
  91. use std::collections::hash_map::Entry;
  92. use std::cmp;
  93. use std::mem::replace;
  94. use std::ops::{self, Deref};
  95. use syntax::abi::Abi;
  96. use syntax::ast;
  97. use syntax::codemap::{self, original_sp, Spanned};
  98. use syntax::feature_gate::{GateIssue, emit_feature_err};
  99. use syntax::ptr::P;
  100. use syntax::symbol::{Symbol, InternedString, keywords};
  101. use syntax::util::lev_distance::find_best_match_for_name;
  102. use syntax_pos::{self, BytePos, Span, DUMMY_SP};
  103. use rustc::hir::intravisit::{self, Visitor, NestedVisitorMap};
  104. use rustc::hir::itemlikevisit::ItemLikeVisitor;
  105. use rustc::hir::{self, PatKind};
  106. use rustc::middle::lang_items;
  107. use rustc_back::slice;
  108. use rustc::middle::const_val::eval_length;
  109. use rustc_const_math::ConstInt;
  110. mod autoderef;
  111. pub mod dropck;
  112. pub mod _match;
  113. pub mod writeback;
  114. pub mod regionck;
  115. pub mod coercion;
  116. pub mod demand;
  117. pub mod method;
  118. mod upvar;
  119. mod wfcheck;
  120. mod cast;
  121. mod closure;
  122. mod callee;
  123. mod compare_method;
  124. mod intrinsic;
  125. mod op;
  126. /// closures defined within the function. For example:
  127. ///
  128. /// fn foo() {
  129. /// bar(move|| { ... })
  130. /// }
  131. ///
  132. /// Here, the function `foo()` and the closure passed to
  133. /// `bar()` will each have their own `FnCtxt`, but they will
  134. /// share the inherited fields.
  135. pub struct Inherited<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
  136. infcx: InferCtxt<'a, 'gcx, 'tcx>,
  137. locals: RefCell<NodeMap<Ty<'tcx>>>,
  138. fulfillment_cx: RefCell<traits::FulfillmentContext<'tcx>>,
  139. // When we process a call like `c()` where `c` is a closure type,
  140. // we may not have decided yet whether `c` is a `Fn`, `FnMut`, or
  141. // `FnOnce` closure. In that case, we defer full resolution of the
  142. // call until upvar inference can kick in and make the
  143. // decision. We keep these deferred resolutions grouped by the
  144. // def-id of the closure, so that once we decide, we can easily go
  145. // back and process them.
  146. deferred_call_resolutions: RefCell<DefIdMap<Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>>>,
  147. deferred_cast_checks: RefCell<Vec<cast::CastCheck<'tcx>>>,
  148. // Anonymized types found in explicit return types and their
  149. // associated fresh inference variable. Writeback resolves these
  150. // variables to get the concrete type, which can be used to
  151. // deanonymize TyAnon, after typeck is done with all functions.
  152. anon_types: RefCell<NodeMap<Ty<'tcx>>>,
  153. /// Each type parameter has an implicit region bound that
  154. /// indicates it must outlive at least the function body (the user
  155. /// may specify stronger requirements). This field indicates the
  156. /// region of the callee. If it is `None`, then the parameter
  157. /// environment is for an item or something where the "callee" is
  158. /// not clear.
  159. implicit_region_bound: Option<ty::Region<'tcx>>,
  160. }
  161. impl<'a, 'gcx, 'tcx> Deref for Inherited<'a, 'gcx, 'tcx> {
  162. type Target = InferCtxt<'a, 'gcx, 'tcx>;
  163. fn deref(&self) -> &Self::Target {
  164. &self.infcx
  165. }
  166. }
  167. trait DeferredCallResolution<'gcx, 'tcx> {
  168. fn resolve<'a>(&mut self, fcx: &FnCtxt<'a, 'gcx, 'tcx>);
  169. }
  170. type DeferredCallResolutionHandler<'gcx, 'tcx> = Box<DeferredCallResolution<'gcx, 'tcx>+'tcx>;
  171. /// When type-checking an expression, we propagate downward
  172. /// whatever type hint we are able in the form of an `Expectation`.
  173. #[derive(Copy, Clone, Debug)]
  174. pub enum Expectation<'tcx> {
  175. /// We know nothing about what type this expression should have.
  176. NoExpectation,
  177. /// This expression should have the type given (or some subtype)
  178. ExpectHasType(Ty<'tcx>),
  179. /// This expression will be cast to the `Ty`
  180. ExpectCastableToType(Ty<'tcx>),
  181. /// This rvalue expression will be wrapped in `&` or `Box` and coerced
  182. /// to `&Ty` or `Box<Ty>`, respectively. `Ty` is `[A]` or `Trait`.
  183. ExpectRvalueLikeUnsized(Ty<'tcx>),
  184. }
  185. impl<'a, 'gcx, 'tcx> Expectation<'tcx> {
  186. // Disregard "castable to" expectations because they
  187. // can lead us astray. Consider for example `if cond
  188. // {22} else {c} as u8` -- if we propagate the
  189. // "castable to u8" constraint to 22, it will pick the
  190. // type 22u8, which is overly constrained (c might not
  191. // be a u8). In effect, the problem is that the
  192. // "castable to" expectation is not the tightest thing
  193. // we can say, so we want to drop it in this case.
  194. // The tightest thing we can say is "must unify with
  195. // else branch". Note that in the case of a "has type"
  196. // constraint, this limitation does not hold.
  197. // If the expected type is just a type variable, then don't use
  198. // an expected type. Otherwise, we might write parts of the type
  199. // when checking the 'then' block which are incompatible with the
  200. // 'else' branch.
  201. fn adjust_for_branches(&self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
  202. match *self {
  203. ExpectHasType(ety) => {
  204. let ety = fcx.shallow_resolve(ety);
  205. if !ety.is_ty_var() {
  206. ExpectHasType(ety)
  207. } else {
  208. NoExpectation
  209. }
  210. }
  211. ExpectRvalueLikeUnsized(ety) => {
  212. ExpectRvalueLikeUnsized(ety)
  213. }
  214. _ => NoExpectation
  215. }
  216. }
  217. /// Provide an expectation for an rvalue expression given an *optional*
  218. /// hint, which is not required for type safety (the resulting type might
  219. /// be checked higher up, as is the case with `&expr` and `box expr`), but
  220. /// is useful in determining the concrete type.
  221. ///
  222. /// The primary use case is where the expected type is a fat pointer,
  223. /// like `&[isize]`. For example, consider the following statement:
  224. ///
  225. /// let x: &[isize] = &[1, 2, 3];
  226. ///
  227. /// In this case, the expected type for the `&[1, 2, 3]` expression is
  228. /// `&[isize]`. If however we were to say that `[1, 2, 3]` has the
  229. /// expectation `ExpectHasType([isize])`, that would be too strong --
  230. /// `[1, 2, 3]` does not have the type `[isize]` but rather `[isize; 3]`.
  231. /// It is only the `&[1, 2, 3]` expression as a whole that can be coerced
  232. /// to the type `&[isize]`. Therefore, we propagate this more limited hint,
  233. /// which still is useful, because it informs integer literals and the like.
  234. /// See the test case `test/run-pass/coerce-expect-unsized.rs` and #20169
  235. /// for examples of where this comes up,.
  236. fn rvalue_hint(fcx: &FnCtxt<'a, 'gcx, 'tcx>, ty: Ty<'tcx>) -> Expectation<'tcx> {
  237. match fcx.tcx.struct_tail(ty).sty {
  238. ty::TySlice(_) | ty::TyStr | ty::TyDynamic(..) => {
  239. ExpectRvalueLikeUnsized(ty)
  240. }
  241. _ => ExpectHasType(ty)
  242. }
  243. }
  244. // Resolves `expected` by a single level if it is a variable. If
  245. // there is no expected type or resolution is not possible (e.g.,
  246. // no constraints yet present), just returns `None`.
  247. fn resolve(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Expectation<'tcx> {
  248. match self {
  249. NoExpectation => {
  250. NoExpectation
  251. }
  252. ExpectCastableToType(t) => {
  253. ExpectCastableToType(fcx.resolve_type_vars_if_possible(&t))
  254. }
  255. ExpectHasType(t) => {
  256. ExpectHasType(fcx.resolve_type_vars_if_possible(&t))
  257. }
  258. ExpectRvalueLikeUnsized(t) => {
  259. ExpectRvalueLikeUnsized(fcx.resolve_type_vars_if_possible(&t))
  260. }
  261. }
  262. }
  263. fn to_option(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
  264. match self.resolve(fcx) {
  265. NoExpectation => None,
  266. ExpectCastableToType(ty) |
  267. ExpectHasType(ty) |
  268. ExpectRvalueLikeUnsized(ty) => Some(ty),
  269. }
  270. }
  271. /// It sometimes happens that we want to turn an expectation into
  272. /// a **hard constraint** (i.e., something that must be satisfied
  273. /// for the program to type-check). `only_has_type` will return
  274. /// such a constraint, if it exists.
  275. fn only_has_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>) -> Option<Ty<'tcx>> {
  276. match self.resolve(fcx) {
  277. ExpectHasType(ty) => Some(ty),
  278. _ => None
  279. }
  280. }
  281. /// Like `only_has_type`, but instead of returning `None` if no
  282. /// hard constraint exists, creates a fresh type variable.
  283. fn coercion_target_type(self, fcx: &FnCtxt<'a, 'gcx, 'tcx>, span: Span) -> Ty<'tcx> {
  284. self.only_has_type(fcx)
  285. .unwrap_or_else(|| fcx.next_ty_var(TypeVariableOrigin::MiscVariable(span)))
  286. }
  287. }
  288. #[derive(Copy, Clone)]
  289. pub struct UnsafetyState {
  290. pub def: ast::NodeId,
  291. pub unsafety: hir::Unsafety,
  292. pub unsafe_push_count: u32,
  293. from_fn: bool
  294. }
  295. impl UnsafetyState {
  296. pub fn function(unsafety: hir::Unsafety, def: ast::NodeId) -> UnsafetyState {
  297. UnsafetyState { def: def, unsafety: unsafety, unsafe_push_count: 0, from_fn: true }
  298. }
  299. pub fn recurse(&mut self, blk: &hir::Block) -> UnsafetyState {
  300. match self.unsafety {
  301. // If this unsafe, then if the outer function was already marked as
  302. // unsafe we shouldn't attribute the unsafe'ness to the block. This
  303. // way the block can be warned about instead of ignoring this
  304. // extraneous block (functions are never warned about).
  305. hir::Unsafety::Unsafe if self.from_fn => *self,
  306. unsafety => {
  307. let (unsafety, def, count) = match blk.rules {
  308. hir::PushUnsafeBlock(..) =>
  309. (unsafety, blk.id, self.unsafe_push_count.checked_add(1).unwrap()),
  310. hir::PopUnsafeBlock(..) =>
  311. (unsafety, blk.id, self.unsafe_push_count.checked_sub(1).unwrap()),
  312. hir::UnsafeBlock(..) =>
  313. (hir::Unsafety::Unsafe, blk.id, self.unsafe_push_count),
  314. hir::DefaultBlock =>
  315. (unsafety, self.def, self.unsafe_push_count),
  316. };
  317. UnsafetyState{ def: def,
  318. unsafety: unsafety,
  319. unsafe_push_count: count,
  320. from_fn: false }
  321. }
  322. }
  323. }
  324. }
  325. #[derive(Debug, Copy, Clone)]
  326. pub enum LvalueOp {
  327. Deref,
  328. Index
  329. }
  330. #[derive(Copy, Clone, Debug)]
  331. pub struct AdjustedRcvr<'a> {
  332. pub rcvr_expr: &'a hir::Expr,
  333. pub autoderefs: usize,
  334. pub unsize: bool
  335. }
  336. /// Tracks whether executing a node may exit normally (versus
  337. /// return/break/panic, which "diverge", leaving dead code in their
  338. /// wake). Tracked semi-automatically (through type variables marked
  339. /// as diverging), with some manual adjustments for control-flow
  340. /// primitives (approximating a CFG).
  341. #[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
  342. pub enum Diverges {
  343. /// Potentially unknown, some cases converge,
  344. /// others require a CFG to determine them.
  345. Maybe,
  346. /// Definitely known to diverge and therefore
  347. /// not reach the next sibling or its parent.
  348. Always,
  349. /// Same as `Always` but with a reachability
  350. /// warning already emitted
  351. WarnedAlways
  352. }
  353. // Convenience impls for combinig `Diverges`.
  354. impl ops::BitAnd for Diverges {
  355. type Output = Self;
  356. fn bitand(self, other: Self) -> Self {
  357. cmp::min(self, other)
  358. }
  359. }
  360. impl ops::BitOr for Diverges {
  361. type Output = Self;
  362. fn bitor(self, other: Self) -> Self {
  363. cmp::max(self, other)
  364. }
  365. }
  366. impl ops::BitAndAssign for Diverges {
  367. fn bitand_assign(&mut self, other: Self) {
  368. *self = *self & other;
  369. }
  370. }
  371. impl ops::BitOrAssign for Diverges {
  372. fn bitor_assign(&mut self, other: Self) {
  373. *self = *self | other;
  374. }
  375. }
  376. impl Diverges {
  377. fn always(self) -> bool {
  378. self >= Diverges::Always
  379. }
  380. }
  381. pub struct BreakableCtxt<'gcx: 'tcx, 'tcx> {
  382. may_break: bool,
  383. // this is `null` for loops where break with a value is illegal,
  384. // such as `while`, `for`, and `while let`
  385. coerce: Option<DynamicCoerceMany<'gcx, 'tcx>>,
  386. }
  387. pub struct EnclosingBreakables<'gcx: 'tcx, 'tcx> {
  388. stack: Vec<BreakableCtxt<'gcx, 'tcx>>,
  389. by_id: NodeMap<usize>,
  390. }
  391. impl<'gcx, 'tcx> EnclosingBreakables<'gcx, 'tcx> {
  392. fn find_breakable(&mut self, target_id: ast::NodeId) -> &mut BreakableCtxt<'gcx, 'tcx> {
  393. let ix = *self.by_id.get(&target_id).unwrap_or_else(|| {
  394. bug!("could not find enclosing breakable with id {}", target_id);
  395. });
  396. &mut self.stack[ix]
  397. }
  398. }
  399. pub struct FnCtxt<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
  400. body_id: ast::NodeId,
  401. // Number of errors that had been reported when we started
  402. // checking this function. On exit, if we find that *more* errors
  403. // have been reported, we will skip regionck and other work that
  404. // expects the types within the function to be consistent.
  405. err_count_on_creation: usize,
  406. ret_coercion: Option<RefCell<DynamicCoerceMany<'gcx, 'tcx>>>,
  407. ps: RefCell<UnsafetyState>,
  408. /// Whether the last checked node generates a divergence (e.g.,
  409. /// `return` will set this to Always). In general, when entering
  410. /// an expression or other node in the tree, the initial value
  411. /// indicates whether prior parts of the containing expression may
  412. /// have diverged. It is then typically set to `Maybe` (and the
  413. /// old value remembered) for processing the subparts of the
  414. /// current expression. As each subpart is processed, they may set
  415. /// the flag to `Always` etc. Finally, at the end, we take the
  416. /// result and "union" it with the original value, so that when we
  417. /// return the flag indicates if any subpart of the the parent
  418. /// expression (up to and including this part) has diverged. So,
  419. /// if you read it after evaluating a subexpression `X`, the value
  420. /// you get indicates whether any subexpression that was
  421. /// evaluating up to and including `X` diverged.
  422. ///
  423. /// We use this flag for two purposes:
  424. ///
  425. /// - To warn about unreachable code: if, after processing a
  426. /// sub-expression but before we have applied the effects of the
  427. /// current node, we see that the flag is set to `Always`, we
  428. /// can issue a warning. This corresponds to something like
  429. /// `foo(return)`; we warn on the `foo()` expression. (We then
  430. /// update the flag to `WarnedAlways` to suppress duplicate
  431. /// reports.) Similarly, if we traverse to a fresh statement (or
  432. /// tail expression) from a `Always` setting, we will isssue a
  433. /// warning. This corresponds to something like `{return;
  434. /// foo();}` or `{return; 22}`, where we would warn on the
  435. /// `foo()` or `22`.
  436. ///
  437. /// - To permit assignment into a local variable or other lvalue
  438. /// (including the "return slot") of type `!`. This is allowed
  439. /// if **either** the type of value being assigned is `!`, which
  440. /// means the current code is dead, **or** the expression's
  441. /// divering flag is true, which means that a divering value was
  442. /// wrapped (e.g., `let x: ! = foo(return)`).
  443. ///
  444. /// To repeat the last point: an expression represents dead-code
  445. /// if, after checking it, **either** its type is `!` OR the
  446. /// diverges flag is set to something other than `Maybe`.
  447. diverges: Cell<Diverges>,
  448. /// Whether any child nodes have any type errors.
  449. has_errors: Cell<bool>,
  450. enclosing_breakables: RefCell<EnclosingBreakables<'gcx, 'tcx>>,
  451. inh: &'a Inherited<'a, 'gcx, 'tcx>,
  452. }
  453. impl<'a, 'gcx, 'tcx> Deref for FnCtxt<'a, 'gcx, 'tcx> {
  454. type Target = Inherited<'a, 'gcx, 'tcx>;
  455. fn deref(&self) -> &Self::Target {
  456. &self.inh
  457. }
  458. }
  459. /// Helper type of a temporary returned by Inherited::build(...).
  460. /// Necessary because we can't write the following bound:
  461. /// F: for<'b, 'tcx> where 'gcx: 'tcx FnOnce(Inherited<'b, 'gcx, 'tcx>).
  462. pub struct InheritedBuilder<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
  463. infcx: infer::InferCtxtBuilder<'a, 'gcx, 'tcx>,
  464. def_id: DefId,
  465. }
  466. impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
  467. pub fn build(tcx: TyCtxt<'a, 'gcx, 'gcx>, def_id: DefId)
  468. -> InheritedBuilder<'a, 'gcx, 'tcx> {
  469. let tables = ty::TypeckTables::empty();
  470. let param_env = tcx.parameter_environment(def_id);
  471. InheritedBuilder {
  472. infcx: tcx.infer_ctxt((tables, param_env), Reveal::UserFacing),
  473. def_id,
  474. }
  475. }
  476. }
  477. impl<'a, 'gcx, 'tcx> InheritedBuilder<'a, 'gcx, 'tcx> {
  478. fn enter<F, R>(&'tcx mut self, f: F) -> R
  479. where F: for<'b> FnOnce(Inherited<'b, 'gcx, 'tcx>) -> R
  480. {
  481. let def_id = self.def_id;
  482. self.infcx.enter(|infcx| f(Inherited::new(infcx, def_id)))
  483. }
  484. }
  485. impl<'a, 'gcx, 'tcx> Inherited<'a, 'gcx, 'tcx> {
  486. fn new(infcx: InferCtxt<'a, 'gcx, 'tcx>, def_id: DefId) -> Self {
  487. let tcx = infcx.tcx;
  488. let item_id = tcx.hir.as_local_node_id(def_id);
  489. let body_id = item_id.and_then(|id| tcx.hir.maybe_body_owned_by(id));
  490. let implicit_region_bound = body_id.map(|body| {
  491. tcx.mk_region(ty::ReScope(CodeExtent::CallSiteScope(body)))
  492. });
  493. Inherited {
  494. infcx: infcx,
  495. fulfillment_cx: RefCell::new(traits::FulfillmentContext::new()),
  496. locals: RefCell::new(NodeMap()),
  497. deferred_call_resolutions: RefCell::new(DefIdMap()),
  498. deferred_cast_checks: RefCell::new(Vec::new()),
  499. anon_types: RefCell::new(NodeMap()),
  500. implicit_region_bound,
  501. }
  502. }
  503. fn register_predicate(&self, obligation: traits::PredicateObligation<'tcx>) {
  504. debug!("register_predicate({:?})", obligation);
  505. if obligation.has_escaping_regions() {
  506. span_bug!(obligation.cause.span, "escaping regions in predicate {:?}",
  507. obligation);
  508. }
  509. self.fulfillment_cx
  510. .borrow_mut()
  511. .register_predicate_obligation(self, obligation);
  512. }
  513. fn register_predicates(&self, obligations: Vec<traits::PredicateObligation<'tcx>>) {
  514. for obligation in obligations {
  515. self.register_predicate(obligation);
  516. }
  517. }
  518. fn register_infer_ok_obligations<T>(&self, infer_ok: InferOk<'tcx, T>) -> T {
  519. self.register_predicates(infer_ok.obligations);
  520. infer_ok.value
  521. }
  522. fn normalize_associated_types_in<T>(&self,
  523. span: Span,
  524. body_id: ast::NodeId,
  525. value: &T) -> T
  526. where T : TypeFoldable<'tcx>
  527. {
  528. let ok = self.normalize_associated_types_in_as_infer_ok(span, body_id, value);
  529. self.register_infer_ok_obligations(ok)
  530. }
  531. fn normalize_associated_types_in_as_infer_ok<T>(&self,
  532. span: Span,
  533. body_id: ast::NodeId,
  534. value: &T)
  535. -> InferOk<'tcx, T>
  536. where T : TypeFoldable<'tcx>
  537. {
  538. debug!("normalize_associated_types_in(value={:?})", value);
  539. let mut selcx = traits::SelectionContext::new(self);
  540. let cause = ObligationCause::misc(span, body_id);
  541. let traits::Normalized { value, obligations } =
  542. traits::normalize(&mut selcx, cause, value);
  543. debug!("normalize_associated_types_in: result={:?} predicates={:?}",
  544. value,
  545. obligations);
  546. InferOk { value, obligations }
  547. }
  548. /// Replace any late-bound regions bound in `value` with
  549. /// free variants attached to `all_outlive_scope`.
  550. fn liberate_late_bound_regions<T>(&self,
  551. all_outlive_scope: DefId,
  552. value: &ty::Binder<T>)
  553. -> T
  554. where T: TypeFoldable<'tcx>
  555. {
  556. self.tcx.replace_late_bound_regions(value, |br| {
  557. self.tcx.mk_region(ty::ReFree(ty::FreeRegion {
  558. scope: all_outlive_scope,
  559. bound_region: br
  560. }))
  561. }).0
  562. }
  563. }
  564. struct CheckItemTypesVisitor<'a, 'tcx: 'a> { tcx: TyCtxt<'a, 'tcx, 'tcx> }
  565. impl<'a, 'tcx> ItemLikeVisitor<'tcx> for CheckItemTypesVisitor<'a, 'tcx> {
  566. fn visit_item(&mut self, i: &'tcx hir::Item) {
  567. check_item_type(self.tcx, i);
  568. }
  569. fn visit_trait_item(&mut self, _: &'tcx hir::TraitItem) { }
  570. fn visit_impl_item(&mut self, _: &'tcx hir::ImplItem) { }
  571. }
  572. pub fn check_wf_new<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
  573. tcx.sess.track_errors(|| {
  574. let mut visit = wfcheck::CheckTypeWellFormedVisitor::new(tcx);
  575. tcx.hir.krate().visit_all_item_likes(&mut visit.as_deep_visitor());
  576. })
  577. }
  578. pub fn check_item_types<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
  579. tcx.sess.track_errors(|| {
  580. tcx.hir.krate().visit_all_item_likes(&mut CheckItemTypesVisitor { tcx });
  581. })
  582. }
  583. pub fn check_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> CompileResult {
  584. tcx.typeck_item_bodies(LOCAL_CRATE)
  585. }
  586. fn typeck_item_bodies<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, crate_num: CrateNum) -> CompileResult {
  587. debug_assert!(crate_num == LOCAL_CRATE);
  588. tcx.sess.track_errors(|| {
  589. for body_owner_def_id in tcx.body_owners() {
  590. tcx.typeck_tables_of(body_owner_def_id);
  591. }
  592. })
  593. }
  594. pub fn provide(providers: &mut Providers) {
  595. *providers = Providers {
  596. typeck_item_bodies,
  597. typeck_tables_of,
  598. has_typeck_tables,
  599. closure_type,
  600. closure_kind,
  601. adt_destructor,
  602. ..*providers
  603. };
  604. }
  605. fn closure_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  606. def_id: DefId)
  607. -> ty::PolyFnSig<'tcx> {
  608. let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
  609. tcx.typeck_tables_of(def_id).closure_tys[&node_id]
  610. }
  611. fn closure_kind<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  612. def_id: DefId)
  613. -> ty::ClosureKind {
  614. let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
  615. tcx.typeck_tables_of(def_id).closure_kinds[&node_id]
  616. }
  617. fn adt_destructor<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  618. def_id: DefId)
  619. -> Option<ty::Destructor> {
  620. tcx.calculate_dtor(def_id, &mut dropck::check_drop_impl)
  621. }
  622. /// If this def-id is a "primary tables entry", returns `Some((body_id, decl))`
  623. /// with information about it's body-id and fn-decl (if any). Otherwise,
  624. /// returns `None`.
  625. ///
  626. /// If this function returns "some", then `typeck_tables(def_id)` will
  627. /// succeed; if it returns `None`, then `typeck_tables(def_id)` may or
  628. /// may not succeed. In some cases where this function returns `None`
  629. /// (notably closures), `typeck_tables(def_id)` would wind up
  630. /// redirecting to the owning function.
  631. fn primary_body_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  632. id: ast::NodeId)
  633. -> Option<(hir::BodyId, Option<&'tcx hir::FnDecl>)>
  634. {
  635. match tcx.hir.get(id) {
  636. hir::map::NodeItem(item) => {
  637. match item.node {
  638. hir::ItemConst(_, body) |
  639. hir::ItemStatic(_, _, body) =>
  640. Some((body, None)),
  641. hir::ItemFn(ref decl, .., body) =>
  642. Some((body, Some(decl))),
  643. _ =>
  644. None,
  645. }
  646. }
  647. hir::map::NodeTraitItem(item) => {
  648. match item.node {
  649. hir::TraitItemKind::Const(_, Some(body)) =>
  650. Some((body, None)),
  651. hir::TraitItemKind::Method(ref sig, hir::TraitMethod::Provided(body)) =>
  652. Some((body, Some(&sig.decl))),
  653. _ =>
  654. None,
  655. }
  656. }
  657. hir::map::NodeImplItem(item) => {
  658. match item.node {
  659. hir::ImplItemKind::Const(_, body) =>
  660. Some((body, None)),
  661. hir::ImplItemKind::Method(ref sig, body) =>
  662. Some((body, Some(&sig.decl))),
  663. _ =>
  664. None,
  665. }
  666. }
  667. hir::map::NodeExpr(expr) => {
  668. // FIXME(eddyb) Closures should have separate
  669. // function definition IDs and expression IDs.
  670. // Type-checking should not let closures get
  671. // this far in a constant position.
  672. // Assume that everything other than closures
  673. // is a constant "initializer" expression.
  674. match expr.node {
  675. hir::ExprClosure(..) =>
  676. None,
  677. _ =>
  678. Some((hir::BodyId { node_id: expr.id }, None)),
  679. }
  680. }
  681. _ => None,
  682. }
  683. }
  684. fn has_typeck_tables<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  685. def_id: DefId)
  686. -> bool {
  687. // Closures' tables come from their outermost function,
  688. // as they are part of the same "inference environment".
  689. let outer_def_id = tcx.closure_base_def_id(def_id);
  690. if outer_def_id != def_id {
  691. return tcx.has_typeck_tables(outer_def_id);
  692. }
  693. let id = tcx.hir.as_local_node_id(def_id).unwrap();
  694. primary_body_of(tcx, id).is_some()
  695. }
  696. fn typeck_tables_of<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  697. def_id: DefId)
  698. -> &'tcx ty::TypeckTables<'tcx> {
  699. // Closures' tables come from their outermost function,
  700. // as they are part of the same "inference environment".
  701. let outer_def_id = tcx.closure_base_def_id(def_id);
  702. if outer_def_id != def_id {
  703. return tcx.typeck_tables_of(outer_def_id);
  704. }
  705. let id = tcx.hir.as_local_node_id(def_id).unwrap();
  706. let span = tcx.hir.span(id);
  707. // Figure out what primary body this item has.
  708. let (body_id, fn_decl) = primary_body_of(tcx, id).unwrap_or_else(|| {
  709. span_bug!(span, "can't type-check body of {:?}", def_id);
  710. });
  711. let body = tcx.hir.body(body_id);
  712. Inherited::build(tcx, def_id).enter(|inh| {
  713. let fcx = if let Some(decl) = fn_decl {
  714. let fn_sig = tcx.type_of(def_id).fn_sig();
  715. check_abi(tcx, span, fn_sig.abi());
  716. // Compute the fty from point of view of inside fn.
  717. let fn_sig =
  718. inh.liberate_late_bound_regions(def_id, &fn_sig);
  719. let fn_sig =
  720. inh.normalize_associated_types_in(body.value.span, body_id.node_id, &fn_sig);
  721. check_fn(&inh, fn_sig, decl, id, body)
  722. } else {
  723. let fcx = FnCtxt::new(&inh, body.value.id);
  724. let expected_type = tcx.type_of(def_id);
  725. let expected_type = fcx.normalize_associated_types_in(body.value.span, &expected_type);
  726. fcx.require_type_is_sized(expected_type, body.value.span, traits::ConstSized);
  727. // Gather locals in statics (because of block expressions).
  728. // This is technically unnecessary because locals in static items are forbidden,
  729. // but prevents type checking from blowing up before const checking can properly
  730. // emit an error.
  731. GatherLocalsVisitor { fcx: &fcx }.visit_body(body);
  732. fcx.check_expr_coercable_to_type(&body.value, expected_type);
  733. fcx
  734. };
  735. fcx.select_all_obligations_and_apply_defaults();
  736. fcx.closure_analyze(body);
  737. fcx.select_obligations_where_possible();
  738. fcx.check_casts();
  739. fcx.select_all_obligations_or_error();
  740. if fn_decl.is_some() {
  741. fcx.regionck_fn(id, body);
  742. } else {
  743. fcx.regionck_expr(body);
  744. }
  745. fcx.resolve_type_vars_in_body(body)
  746. })
  747. }
  748. fn check_abi<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, span: Span, abi: Abi) {
  749. if !tcx.sess.target.target.is_abi_supported(abi) {
  750. struct_span_err!(tcx.sess, span, E0570,
  751. "The ABI `{}` is not supported for the current target", abi).emit()
  752. }
  753. }
  754. struct GatherLocalsVisitor<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
  755. fcx: &'a FnCtxt<'a, 'gcx, 'tcx>
  756. }
  757. impl<'a, 'gcx, 'tcx> GatherLocalsVisitor<'a, 'gcx, 'tcx> {
  758. fn assign(&mut self, span: Span, nid: ast::NodeId, ty_opt: Option<Ty<'tcx>>) -> Ty<'tcx> {
  759. match ty_opt {
  760. None => {
  761. // infer the variable's type
  762. let var_ty = self.fcx.next_ty_var(TypeVariableOrigin::TypeInference(span));
  763. self.fcx.locals.borrow_mut().insert(nid, var_ty);
  764. var_ty
  765. }
  766. Some(typ) => {
  767. // take type that the user specified
  768. self.fcx.locals.borrow_mut().insert(nid, typ);
  769. typ
  770. }
  771. }
  772. }
  773. }
  774. impl<'a, 'gcx, 'tcx> Visitor<'gcx> for GatherLocalsVisitor<'a, 'gcx, 'tcx> {
  775. fn nested_visit_map<'this>(&'this mut self) -> NestedVisitorMap<'this, 'gcx> {
  776. NestedVisitorMap::None
  777. }
  778. // Add explicitly-declared locals.
  779. fn visit_local(&mut self, local: &'gcx hir::Local) {
  780. let o_ty = match local.ty {
  781. Some(ref ty) => Some(self.fcx.to_ty(&ty)),
  782. None => None
  783. };
  784. self.assign(local.span, local.id, o_ty);
  785. debug!("Local variable {:?} is assigned type {}",
  786. local.pat,
  787. self.fcx.ty_to_string(
  788. self.fcx.locals.borrow().get(&local.id).unwrap().clone()));
  789. intravisit::walk_local(self, local);
  790. }
  791. // Add pattern bindings.
  792. fn visit_pat(&mut self, p: &'gcx hir::Pat) {
  793. if let PatKind::Binding(_, _, ref path1, _) = p.node {
  794. let var_ty = self.assign(p.span, p.id, None);
  795. self.fcx.require_type_is_sized(var_ty, p.span,
  796. traits::VariableType(p.id));
  797. debug!("Pattern binding {} is assigned to {} with type {:?}",
  798. path1.node,
  799. self.fcx.ty_to_string(
  800. self.fcx.locals.borrow().get(&p.id).unwrap().clone()),
  801. var_ty);
  802. }
  803. intravisit::walk_pat(self, p);
  804. }
  805. // Don't descend into the bodies of nested closures
  806. fn visit_fn(&mut self, _: intravisit::FnKind<'gcx>, _: &'gcx hir::FnDecl,
  807. _: hir::BodyId, _: Span, _: ast::NodeId) { }
  808. }
  809. /// Helper used for fns and closures. Does the grungy work of checking a function
  810. /// body and returns the function context used for that purpose, since in the case of a fn item
  811. /// there is still a bit more to do.
  812. ///
  813. /// * ...
  814. /// * inherited: other fields inherited from the enclosing fn (if any)
  815. fn check_fn<'a, 'gcx, 'tcx>(inherited: &'a Inherited<'a, 'gcx, 'tcx>,
  816. fn_sig: ty::FnSig<'tcx>,
  817. decl: &'gcx hir::FnDecl,
  818. fn_id: ast::NodeId,
  819. body: &'gcx hir::Body)
  820. -> FnCtxt<'a, 'gcx, 'tcx>
  821. {
  822. let mut fn_sig = fn_sig.clone();
  823. debug!("check_fn(sig={:?}, fn_id={})", fn_sig, fn_id);
  824. // Create the function context. This is either derived from scratch or,
  825. // in the case of function expressions, based on the outer context.
  826. let mut fcx = FnCtxt::new(inherited, body.value.id);
  827. *fcx.ps.borrow_mut() = UnsafetyState::function(fn_sig.unsafety, fn_id);
  828. let ret_ty = fn_sig.output();
  829. fcx.require_type_is_sized(ret_ty, decl.output.span(), traits::ReturnType);
  830. let ret_ty = fcx.instantiate_anon_types(&ret_ty);
  831. fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
  832. fn_sig = fcx.tcx.mk_fn_sig(
  833. fn_sig.inputs().iter().cloned(),
  834. ret_ty,
  835. fn_sig.variadic,
  836. fn_sig.unsafety,
  837. fn_sig.abi
  838. );
  839. GatherLocalsVisitor { fcx: &fcx, }.visit_body(body);
  840. // Add formal parameters.
  841. for (arg_ty, arg) in fn_sig.inputs().iter().zip(&body.arguments) {
  842. // The type of the argument must be well-formed.
  843. //
  844. // NB -- this is now checked in wfcheck, but that
  845. // currently only results in warnings, so we issue an
  846. // old-style WF obligation here so that we still get the
  847. // errors that we used to get.
  848. fcx.register_old_wf_obligation(arg_ty, arg.pat.span, traits::MiscObligation);
  849. // Check the pattern.
  850. fcx.check_pat_arg(&arg.pat, arg_ty, true);
  851. fcx.write_ty(arg.id, arg_ty);
  852. }
  853. inherited.tables.borrow_mut().liberated_fn_sigs.insert(fn_id, fn_sig);
  854. fcx.check_return_expr(&body.value);
  855. // Finalize the return check by taking the LUB of the return types
  856. // we saw and assigning it to the expected return type. This isn't
  857. // really expected to fail, since the coercions would have failed
  858. // earlier when trying to find a LUB.
  859. //
  860. // However, the behavior around `!` is sort of complex. In the
  861. // event that the `actual_return_ty` comes back as `!`, that
  862. // indicates that the fn either does not return or "returns" only
  863. // values of type `!`. In this case, if there is an expected
  864. // return type that is *not* `!`, that should be ok. But if the
  865. // return type is being inferred, we want to "fallback" to `!`:
  866. //
  867. // let x = move || panic!();
  868. //
  869. // To allow for that, I am creating a type variable with diverging
  870. // fallback. This was deemed ever so slightly better than unifying
  871. // the return value with `!` because it allows for the caller to
  872. // make more assumptions about the return type (e.g., they could do
  873. //
  874. // let y: Option<u32> = Some(x());
  875. //
  876. // which would then cause this return type to become `u32`, not
  877. // `!`).
  878. let coercion = fcx.ret_coercion.take().unwrap().into_inner();
  879. let mut actual_return_ty = coercion.complete(&fcx);
  880. if actual_return_ty.is_never() {
  881. actual_return_ty = fcx.next_diverging_ty_var(
  882. TypeVariableOrigin::DivergingFn(body.value.span));
  883. }
  884. fcx.demand_suptype(body.value.span, ret_ty, actual_return_ty);
  885. fcx
  886. }
  887. fn check_struct<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  888. id: ast::NodeId,
  889. span: Span) {
  890. let def_id = tcx.hir.local_def_id(id);
  891. let def = tcx.adt_def(def_id);
  892. def.destructor(tcx); // force the destructor to be evaluated
  893. check_representable(tcx, span, def_id);
  894. if def.repr.simd() {
  895. check_simd(tcx, span, def_id);
  896. }
  897. // if struct is packed and not aligned, check fields for alignment.
  898. // Checks for combining packed and align attrs on single struct are done elsewhere.
  899. if tcx.adt_def(def_id).repr.packed() && tcx.adt_def(def_id).repr.align == 0 {
  900. check_packed(tcx, span, def_id);
  901. }
  902. }
  903. fn check_union<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  904. id: ast::NodeId,
  905. span: Span) {
  906. let def_id = tcx.hir.local_def_id(id);
  907. let def = tcx.adt_def(def_id);
  908. def.destructor(tcx); // force the destructor to be evaluated
  909. check_representable(tcx, span, def_id);
  910. }
  911. pub fn check_item_type<'a,'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, it: &'tcx hir::Item) {
  912. debug!("check_item_type(it.id={}, it.name={})",
  913. it.id,
  914. tcx.item_path_str(tcx.hir.local_def_id(it.id)));
  915. let _indenter = indenter();
  916. match it.node {
  917. // Consts can play a role in type-checking, so they are included here.
  918. hir::ItemStatic(..) |
  919. hir::ItemConst(..) => {
  920. tcx.typeck_tables_of(tcx.hir.local_def_id(it.id));
  921. }
  922. hir::ItemEnum(ref enum_definition, _) => {
  923. check_enum(tcx,
  924. it.span,
  925. &enum_definition.variants,
  926. it.id);
  927. }
  928. hir::ItemFn(..) => {} // entirely within check_item_body
  929. hir::ItemImpl(.., ref impl_item_refs) => {
  930. debug!("ItemImpl {} with id {}", it.name, it.id);
  931. let impl_def_id = tcx.hir.local_def_id(it.id);
  932. if let Some(impl_trait_ref) = tcx.impl_trait_ref(impl_def_id) {
  933. check_impl_items_against_trait(tcx,
  934. it.span,
  935. impl_def_id,
  936. impl_trait_ref,
  937. impl_item_refs);
  938. let trait_def_id = impl_trait_ref.def_id;
  939. check_on_unimplemented(tcx, trait_def_id, it);
  940. }
  941. }
  942. hir::ItemTrait(..) => {
  943. let def_id = tcx.hir.local_def_id(it.id);
  944. check_on_unimplemented(tcx, def_id, it);
  945. }
  946. hir::ItemStruct(..) => {
  947. check_struct(tcx, it.id, it.span);
  948. }
  949. hir::ItemUnion(..) => {
  950. check_union(tcx, it.id, it.span);
  951. }
  952. hir::ItemTy(_, ref generics) => {
  953. let def_id = tcx.hir.local_def_id(it.id);
  954. let pty_ty = tcx.type_of(def_id);
  955. check_bounds_are_used(tcx, generics, pty_ty);
  956. }
  957. hir::ItemForeignMod(ref m) => {
  958. check_abi(tcx, it.span, m.abi);
  959. if m.abi == Abi::RustIntrinsic {
  960. for item in &m.items {
  961. intrinsic::check_intrinsic_type(tcx, item);
  962. }
  963. } else if m.abi == Abi::PlatformIntrinsic {
  964. for item in &m.items {
  965. intrinsic::check_platform_intrinsic_type(tcx, item);
  966. }
  967. } else {
  968. for item in &m.items {
  969. let generics = tcx.generics_of(tcx.hir.local_def_id(item.id));
  970. if !generics.types.is_empty() {
  971. let mut err = struct_span_err!(tcx.sess, item.span, E0044,
  972. "foreign items may not have type parameters");
  973. span_help!(&mut err, item.span,
  974. "consider using specialization instead of \
  975. type parameters");
  976. err.emit();
  977. }
  978. if let hir::ForeignItemFn(ref fn_decl, _, _) = item.node {
  979. require_c_abi_if_variadic(tcx, fn_decl, m.abi, item.span);
  980. }
  981. }
  982. }
  983. }
  984. _ => {/* nothing to do */ }
  985. }
  986. }
  987. fn check_on_unimplemented<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  988. def_id: DefId,
  989. item: &hir::Item) {
  990. let generics = tcx.generics_of(def_id);
  991. if let Some(ref attr) = item.attrs.iter().find(|a| {
  992. a.check_name("rustc_on_unimplemented")
  993. }) {
  994. if let Some(istring) = attr.value_str() {
  995. let istring = istring.as_str();
  996. let parser = Parser::new(&istring);
  997. let types = &generics.types;
  998. for token in parser {
  999. match token {
  1000. Piece::String(_) => (), // Normal string, no need to check it
  1001. Piece::NextArgument(a) => match a.position {
  1002. // `{Self}` is allowed
  1003. Position::ArgumentNamed(s) if s == "Self" => (),
  1004. // So is `{A}` if A is a type parameter
  1005. Position::ArgumentNamed(s) => match types.iter().find(|t| {
  1006. t.name == s
  1007. }) {
  1008. Some(_) => (),
  1009. None => {
  1010. let name = tcx.item_name(def_id);
  1011. span_err!(tcx.sess, attr.span, E0230,
  1012. "there is no type parameter \
  1013. {} on trait {}",
  1014. s, name);
  1015. }
  1016. },
  1017. // `{:1}` and `{}` are not to be used
  1018. Position::ArgumentIs(_) => {
  1019. span_err!(tcx.sess, attr.span, E0231,
  1020. "only named substitution \
  1021. parameters are allowed");
  1022. }
  1023. }
  1024. }
  1025. }
  1026. } else {
  1027. struct_span_err!(
  1028. tcx.sess, attr.span, E0232,
  1029. "this attribute must have a value")
  1030. .span_label(attr.span, "attribute requires a value")
  1031. .note(&format!("eg `#[rustc_on_unimplemented = \"foo\"]`"))
  1032. .emit();
  1033. }
  1034. }
  1035. }
  1036. fn report_forbidden_specialization<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1037. impl_item: &hir::ImplItem,
  1038. parent_impl: DefId)
  1039. {
  1040. let mut err = struct_span_err!(
  1041. tcx.sess, impl_item.span, E0520,
  1042. "`{}` specializes an item from a parent `impl`, but \
  1043. that item is not marked `default`",
  1044. impl_item.name);
  1045. err.span_label(impl_item.span, format!("cannot specialize default item `{}`",
  1046. impl_item.name));
  1047. match tcx.span_of_impl(parent_impl) {
  1048. Ok(span) => {
  1049. err.span_label(span, "parent `impl` is here");
  1050. err.note(&format!("to specialize, `{}` in the parent `impl` must be marked `default`",
  1051. impl_item.name));
  1052. }
  1053. Err(cname) => {
  1054. err.note(&format!("parent implementation is in crate `{}`", cname));
  1055. }
  1056. }
  1057. err.emit();
  1058. }
  1059. fn check_specialization_validity<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1060. trait_def: &ty::TraitDef,
  1061. impl_id: DefId,
  1062. impl_item: &hir::ImplItem)
  1063. {
  1064. let ancestors = trait_def.ancestors(tcx, impl_id);
  1065. let kind = match impl_item.node {
  1066. hir::ImplItemKind::Const(..) => ty::AssociatedKind::Const,
  1067. hir::ImplItemKind::Method(..) => ty::AssociatedKind::Method,
  1068. hir::ImplItemKind::Type(_) => ty::AssociatedKind::Type
  1069. };
  1070. let parent = ancestors.defs(tcx, impl_item.name, kind).skip(1).next()
  1071. .map(|node_item| node_item.map(|parent| parent.defaultness));
  1072. if let Some(parent) = parent {
  1073. if tcx.impl_item_is_final(&parent) {
  1074. report_forbidden_specialization(tcx, impl_item, parent.node.def_id());
  1075. }
  1076. }
  1077. }
  1078. fn check_impl_items_against_trait<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1079. impl_span: Span,
  1080. impl_id: DefId,
  1081. impl_trait_ref: ty::TraitRef<'tcx>,
  1082. impl_item_refs: &[hir::ImplItemRef]) {
  1083. // If the trait reference itself is erroneous (so the compilation is going
  1084. // to fail), skip checking the items here -- the `impl_item` table in `tcx`
  1085. // isn't populated for such impls.
  1086. if impl_trait_ref.references_error() { return; }
  1087. // Locate trait definition and items
  1088. let trait_def = tcx.trait_def(impl_trait_ref.def_id);
  1089. let mut overridden_associated_type = None;
  1090. let impl_items = || impl_item_refs.iter().map(|iiref| tcx.hir.impl_item(iiref.id));
  1091. // Check existing impl methods to see if they are both present in trait
  1092. // and compatible with trait signature
  1093. for impl_item in impl_items() {
  1094. let ty_impl_item = tcx.associated_item(tcx.hir.local_def_id(impl_item.id));
  1095. let ty_trait_item = tcx.associated_items(impl_trait_ref.def_id)
  1096. .find(|ac| ac.name == ty_impl_item.name);
  1097. // Check that impl definition matches trait definition
  1098. if let Some(ty_trait_item) = ty_trait_item {
  1099. match impl_item.node {
  1100. hir::ImplItemKind::Const(..) => {
  1101. // Find associated const definition.
  1102. if ty_trait_item.kind == ty::AssociatedKind::Const {
  1103. compare_const_impl(tcx,
  1104. &ty_impl_item,
  1105. impl_item.span,
  1106. &ty_trait_item,
  1107. impl_trait_ref);
  1108. } else {
  1109. let mut err = struct_span_err!(tcx.sess, impl_item.span, E0323,
  1110. "item `{}` is an associated const, \
  1111. which doesn't match its trait `{}`",
  1112. ty_impl_item.name,
  1113. impl_trait_ref);
  1114. err.span_label(impl_item.span, "does not match trait");
  1115. // We can only get the spans from local trait definition
  1116. // Same for E0324 and E0325
  1117. if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
  1118. err.span_label(trait_span, "item in trait");
  1119. }
  1120. err.emit()
  1121. }
  1122. }
  1123. hir::ImplItemKind::Method(..) => {
  1124. let trait_span = tcx.hir.span_if_local(ty_trait_item.def_id);
  1125. if ty_trait_item.kind == ty::AssociatedKind::Method {
  1126. let err_count = tcx.sess.err_count();
  1127. compare_impl_method(tcx,
  1128. &ty_impl_item,
  1129. impl_item.span,
  1130. &ty_trait_item,
  1131. impl_trait_ref,
  1132. trait_span,
  1133. true); // start with old-broken-mode
  1134. if err_count == tcx.sess.err_count() {
  1135. // old broken mode did not report an error. Try with the new mode.
  1136. compare_impl_method(tcx,
  1137. &ty_impl_item,
  1138. impl_item.span,
  1139. &ty_trait_item,
  1140. impl_trait_ref,
  1141. trait_span,
  1142. false); // use the new mode
  1143. }
  1144. } else {
  1145. let mut err = struct_span_err!(tcx.sess, impl_item.span, E0324,
  1146. "item `{}` is an associated method, \
  1147. which doesn't match its trait `{}`",
  1148. ty_impl_item.name,
  1149. impl_trait_ref);
  1150. err.span_label(impl_item.span, "does not match trait");
  1151. if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
  1152. err.span_label(trait_span, "item in trait");
  1153. }
  1154. err.emit()
  1155. }
  1156. }
  1157. hir::ImplItemKind::Type(_) => {
  1158. if ty_trait_item.kind == ty::AssociatedKind::Type {
  1159. if ty_trait_item.defaultness.has_value() {
  1160. overridden_associated_type = Some(impl_item);
  1161. }
  1162. } else {
  1163. let mut err = struct_span_err!(tcx.sess, impl_item.span, E0325,
  1164. "item `{}` is an associated type, \
  1165. which doesn't match its trait `{}`",
  1166. ty_impl_item.name,
  1167. impl_trait_ref);
  1168. err.span_label(impl_item.span, "does not match trait");
  1169. if let Some(trait_span) = tcx.hir.span_if_local(ty_trait_item.def_id) {
  1170. err.span_label(trait_span, "item in trait");
  1171. }
  1172. err.emit()
  1173. }
  1174. }
  1175. }
  1176. }
  1177. check_specialization_validity(tcx, trait_def, impl_id, impl_item);
  1178. }
  1179. // Check for missing items from trait
  1180. let mut missing_items = Vec::new();
  1181. let mut invalidated_items = Vec::new();
  1182. let associated_type_overridden = overridden_associated_type.is_some();
  1183. for trait_item in tcx.associated_items(impl_trait_ref.def_id) {
  1184. let is_implemented = trait_def.ancestors(tcx, impl_id)
  1185. .defs(tcx, trait_item.name, trait_item.kind)
  1186. .next()
  1187. .map(|node_item| !node_item.node.is_from_trait())
  1188. .unwrap_or(false);
  1189. if !is_implemented {
  1190. if !trait_item.defaultness.has_value() {
  1191. missing_items.push(trait_item);
  1192. } else if associated_type_overridden {
  1193. invalidated_items.push(trait_item.name);
  1194. }
  1195. }
  1196. }
  1197. let signature = |item: &ty::AssociatedItem| {
  1198. match item.kind {
  1199. ty::AssociatedKind::Method => {
  1200. format!("{}", tcx.type_of(item.def_id).fn_sig().0)
  1201. }
  1202. ty::AssociatedKind::Type => format!("type {};", item.name.to_string()),
  1203. ty::AssociatedKind::Const => {
  1204. format!("const {}: {:?};", item.name.to_string(), tcx.type_of(item.def_id))
  1205. }
  1206. }
  1207. };
  1208. if !missing_items.is_empty() {
  1209. let mut err = struct_span_err!(tcx.sess, impl_span, E0046,
  1210. "not all trait items implemented, missing: `{}`",
  1211. missing_items.iter()
  1212. .map(|trait_item| trait_item.name.to_string())
  1213. .collect::<Vec<_>>().join("`, `"));
  1214. err.span_label(impl_span, format!("missing `{}` in implementation",
  1215. missing_items.iter()
  1216. .map(|trait_item| trait_item.name.to_string())
  1217. .collect::<Vec<_>>().join("`, `")));
  1218. for trait_item in missing_items {
  1219. if let Some(span) = tcx.hir.span_if_local(trait_item.def_id) {
  1220. err.span_label(span, format!("`{}` from trait", trait_item.name));
  1221. } else {
  1222. err.note(&format!("`{}` from trait: `{}`",
  1223. trait_item.name,
  1224. signature(&trait_item)));
  1225. }
  1226. }
  1227. err.emit();
  1228. }
  1229. if !invalidated_items.is_empty() {
  1230. let invalidator = overridden_associated_type.unwrap();
  1231. span_err!(tcx.sess, invalidator.span, E0399,
  1232. "the following trait items need to be reimplemented \
  1233. as `{}` was overridden: `{}`",
  1234. invalidator.name,
  1235. invalidated_items.iter()
  1236. .map(|name| name.to_string())
  1237. .collect::<Vec<_>>().join("`, `"))
  1238. }
  1239. }
  1240. /// Checks whether a type can be represented in memory. In particular, it
  1241. /// identifies types that contain themselves without indirection through a
  1242. /// pointer, which would mean their size is unbounded.
  1243. fn check_representable<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1244. sp: Span,
  1245. item_def_id: DefId)
  1246. -> bool {
  1247. let rty = tcx.type_of(item_def_id);
  1248. // Check that it is possible to represent this type. This call identifies
  1249. // (1) types that contain themselves and (2) types that contain a different
  1250. // recursive type. It is only necessary to throw an error on those that
  1251. // contain themselves. For case 2, there must be an inner type that will be
  1252. // caught by case 1.
  1253. match rty.is_representable(tcx, sp) {
  1254. Representability::SelfRecursive(spans) => {
  1255. let mut err = tcx.recursive_type_with_infinite_size_error(item_def_id);
  1256. for span in spans {
  1257. err.span_label(span, "recursive without indirection");
  1258. }
  1259. err.emit();
  1260. return false
  1261. }
  1262. Representability::Representable | Representability::ContainsRecursive => (),
  1263. }
  1264. return true
  1265. }
  1266. pub fn check_simd<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
  1267. let t = tcx.type_of(def_id);
  1268. match t.sty {
  1269. ty::TyAdt(def, substs) if def.is_struct() => {
  1270. let fields = &def.struct_variant().fields;
  1271. if fields.is_empty() {
  1272. span_err!(tcx.sess, sp, E0075, "SIMD vector cannot be empty");
  1273. return;
  1274. }
  1275. let e = fields[0].ty(tcx, substs);
  1276. if !fields.iter().all(|f| f.ty(tcx, substs) == e) {
  1277. struct_span_err!(tcx.sess, sp, E0076, "SIMD vector should be homogeneous")
  1278. .span_label(sp, "SIMD elements must have the same type")
  1279. .emit();
  1280. return;
  1281. }
  1282. match e.sty {
  1283. ty::TyParam(_) => { /* struct<T>(T, T, T, T) is ok */ }
  1284. _ if e.is_machine() => { /* struct(u8, u8, u8, u8) is ok */ }
  1285. _ => {
  1286. span_err!(tcx.sess, sp, E0077,
  1287. "SIMD vector element type should be machine type");
  1288. return;
  1289. }
  1290. }
  1291. }
  1292. _ => ()
  1293. }
  1294. }
  1295. fn check_packed<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, sp: Span, def_id: DefId) {
  1296. if check_packed_inner(tcx, def_id, &mut Vec::new()) {
  1297. struct_span_err!(tcx.sess, sp, E0588,
  1298. "packed struct cannot transitively contain a `[repr(align)]` struct").emit();
  1299. }
  1300. }
  1301. fn check_packed_inner<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1302. def_id: DefId,
  1303. stack: &mut Vec<DefId>) -> bool {
  1304. let t = tcx.type_of(def_id);
  1305. if stack.contains(&def_id) {
  1306. debug!("check_packed_inner: {:?} is recursive", t);
  1307. return false;
  1308. }
  1309. match t.sty {
  1310. ty::TyAdt(def, substs) if def.is_struct() => {
  1311. if tcx.adt_def(def.did).repr.align > 0 {
  1312. return true;
  1313. }
  1314. // push struct def_id before checking fields
  1315. stack.push(def_id);
  1316. for field in &def.struct_variant().fields {
  1317. let f = field.ty(tcx, substs);
  1318. match f.sty {
  1319. ty::TyAdt(def, _) => {
  1320. if check_packed_inner(tcx, def.did, stack) {
  1321. return true;
  1322. }
  1323. }
  1324. _ => ()
  1325. }
  1326. }
  1327. // only need to pop if not early out
  1328. stack.pop();
  1329. }
  1330. _ => ()
  1331. }
  1332. false
  1333. }
  1334. #[allow(trivial_numeric_casts)]
  1335. pub fn check_enum<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  1336. sp: Span,
  1337. vs: &'tcx [hir::Variant],
  1338. id: ast::NodeId) {
  1339. let def_id = tcx.hir.local_def_id(id);
  1340. let def = tcx.adt_def(def_id);
  1341. def.destructor(tcx); // force the destructor to be evaluated
  1342. if vs.is_empty() && tcx.has_attr(def_id, "repr") {
  1343. struct_span_err!(
  1344. tcx.sess, sp, E0084,
  1345. "unsupported representation for zero-variant enum")
  1346. .span_label(sp, "unsupported enum representation")
  1347. .emit();
  1348. }
  1349. let repr_type_ty = def.repr.discr_type().to_ty(tcx);
  1350. if repr_type_ty == tcx.types.i128 || repr_type_ty == tcx.types.u128 {
  1351. if !tcx.sess.features.borrow().i128_type {
  1352. emit_feature_err(&tcx.sess.parse_sess,
  1353. "i128_type", sp, GateIssue::Language, "128-bit type is unstable");
  1354. }
  1355. }
  1356. for v in vs {
  1357. if let Some(e) = v.node.disr_expr {
  1358. tcx.typeck_tables_of(tcx.hir.local_def_id(e.node_id));
  1359. }
  1360. }
  1361. let mut disr_vals: Vec<ConstInt> = Vec::new();
  1362. for (discr, v) in def.discriminants(tcx).zip(vs) {
  1363. // Check for duplicate discriminant values
  1364. if let Some(i) = disr_vals.iter().position(|&x| x == discr) {
  1365. let variant_i_node_id = tcx.hir.as_local_node_id(def.variants[i].did).unwrap();
  1366. let variant_i = tcx.hir.expect_variant(variant_i_node_id);
  1367. let i_span = match variant_i.node.disr_expr {
  1368. Some(expr) => tcx.hir.span(expr.node_id),
  1369. None => tcx.hir.span(variant_i_node_id)
  1370. };
  1371. let span = match v.node.disr_expr {
  1372. Some(expr) => tcx.hir.span(expr.node_id),
  1373. None => v.span
  1374. };
  1375. struct_span_err!(tcx.sess, span, E0081,
  1376. "discriminant value `{}` already exists", disr_vals[i])
  1377. .span_label(i_span, format!("first use of `{}`", disr_vals[i]))
  1378. .span_label(span , format!("enum already has `{}`", disr_vals[i]))
  1379. .emit();
  1380. }
  1381. disr_vals.push(discr);
  1382. }
  1383. check_representable(tcx, sp, def_id);
  1384. }
  1385. impl<'a, 'gcx, 'tcx> AstConv<'gcx, 'tcx> for FnCtxt<'a, 'gcx, 'tcx> {
  1386. fn tcx<'b>(&'b self) -> TyCtxt<'b, 'gcx, 'tcx> { self.tcx }
  1387. fn get_type_parameter_bounds(&self, _: Span, def_id: DefId)
  1388. -> ty::GenericPredicates<'tcx>
  1389. {
  1390. let tcx = self.tcx;
  1391. let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
  1392. let item_id = tcx.hir.ty_param_owner(node_id);
  1393. let item_def_id = tcx.hir.local_def_id(item_id);
  1394. let generics = tcx.generics_of(item_def_id);
  1395. let index = generics.type_param_to_index[&def_id.index];
  1396. ty::GenericPredicates {
  1397. parent: None,
  1398. predicates: self.parameter_environment.caller_bounds.iter().filter(|predicate| {
  1399. match **predicate {
  1400. ty::Predicate::Trait(ref data) => {
  1401. data.0.self_ty().is_param(index)
  1402. }
  1403. _ => false
  1404. }
  1405. }).cloned().collect()
  1406. }
  1407. }
  1408. fn re_infer(&self, span: Span, def: Option<&ty::RegionParameterDef>)
  1409. -> Option<ty::Region<'tcx>> {
  1410. let v = match def {
  1411. Some(def) => infer::EarlyBoundRegion(span, def.name, def.issue_32330),
  1412. None => infer::MiscVariable(span)
  1413. };
  1414. Some(self.next_region_var(v))
  1415. }
  1416. fn ty_infer(&self, span: Span) -> Ty<'tcx> {
  1417. self.next_ty_var(TypeVariableOrigin::TypeInference(span))
  1418. }
  1419. fn ty_infer_for_def(&self,
  1420. ty_param_def: &ty::TypeParameterDef,
  1421. substs: &[Kind<'tcx>],
  1422. span: Span) -> Ty<'tcx> {
  1423. self.type_var_for_def(span, ty_param_def, substs)
  1424. }
  1425. fn projected_ty_from_poly_trait_ref(&self,
  1426. span: Span,
  1427. poly_trait_ref: ty::PolyTraitRef<'tcx>,
  1428. item_name: ast::Name)
  1429. -> Ty<'tcx>
  1430. {
  1431. let (trait_ref, _) =
  1432. self.replace_late_bound_regions_with_fresh_var(
  1433. span,
  1434. infer::LateBoundRegionConversionTime::AssocTypeProjection(item_name),
  1435. &poly_trait_ref);
  1436. self.tcx().mk_projection(trait_ref, item_name)
  1437. }
  1438. fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
  1439. if ty.has_escaping_regions() {
  1440. ty // FIXME: normalization and escaping regions
  1441. } else {
  1442. self.normalize_associated_types_in(span, &ty)
  1443. }
  1444. }
  1445. fn set_tainted_by_errors(&self) {
  1446. self.infcx.set_tainted_by_errors()
  1447. }
  1448. }
  1449. /// Controls whether the arguments are tupled. This is used for the call
  1450. /// operator.
  1451. ///
  1452. /// Tupling means that all call-side arguments are packed into a tuple and
  1453. /// passed as a single parameter. For example, if tupling is enabled, this
  1454. /// function:
  1455. ///
  1456. /// fn f(x: (isize, isize))
  1457. ///
  1458. /// Can be called as:
  1459. ///
  1460. /// f(1, 2);
  1461. ///
  1462. /// Instead of:
  1463. ///
  1464. /// f((1, 2));
  1465. #[derive(Clone, Eq, PartialEq)]
  1466. enum TupleArgumentsFlag {
  1467. DontTupleArguments,
  1468. TupleArguments,
  1469. }
  1470. impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
  1471. pub fn new(inh: &'a Inherited<'a, 'gcx, 'tcx>,
  1472. body_id: ast::NodeId)
  1473. -> FnCtxt<'a, 'gcx, 'tcx> {
  1474. FnCtxt {
  1475. body_id: body_id,
  1476. err_count_on_creation: inh.tcx.sess.err_count(),
  1477. ret_coercion: None,
  1478. ps: RefCell::new(UnsafetyState::function(hir::Unsafety::Normal,
  1479. ast::CRATE_NODE_ID)),
  1480. diverges: Cell::new(Diverges::Maybe),
  1481. has_errors: Cell::new(false),
  1482. enclosing_breakables: RefCell::new(EnclosingBreakables {
  1483. stack: Vec::new(),
  1484. by_id: NodeMap(),
  1485. }),
  1486. inh: inh,
  1487. }
  1488. }
  1489. pub fn sess(&self) -> &Session {
  1490. &self.tcx.sess
  1491. }
  1492. pub fn err_count_since_creation(&self) -> usize {
  1493. self.tcx.sess.err_count() - self.err_count_on_creation
  1494. }
  1495. /// Produce warning on the given node, if the current point in the
  1496. /// function is unreachable, and there hasn't been another warning.
  1497. fn warn_if_unreachable(&self, id: ast::NodeId, span: Span, kind: &str) {
  1498. if self.diverges.get() == Diverges::Always {
  1499. self.diverges.set(Diverges::WarnedAlways);
  1500. debug!("warn_if_unreachable: id={:?} span={:?} kind={}", id, span, kind);
  1501. self.tables.borrow_mut().lints.add_lint(
  1502. lint::builtin::UNREACHABLE_CODE,
  1503. id, span,
  1504. format!("unreachable {}", kind));
  1505. }
  1506. }
  1507. pub fn cause(&self,
  1508. span: Span,
  1509. code: ObligationCauseCode<'tcx>)
  1510. -> ObligationCause<'tcx> {
  1511. ObligationCause::new(span, self.body_id, code)
  1512. }
  1513. pub fn misc(&self, span: Span) -> ObligationCause<'tcx> {
  1514. self.cause(span, ObligationCauseCode::MiscObligation)
  1515. }
  1516. /// Resolves type variables in `ty` if possible. Unlike the infcx
  1517. /// version (resolve_type_vars_if_possible), this version will
  1518. /// also select obligations if it seems useful, in an effort
  1519. /// to get more type information.
  1520. fn resolve_type_vars_with_obligations(&self, mut ty: Ty<'tcx>) -> Ty<'tcx> {
  1521. debug!("resolve_type_vars_with_obligations(ty={:?})", ty);
  1522. // No TyInfer()? Nothing needs doing.
  1523. if !ty.has_infer_types() {
  1524. debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
  1525. return ty;
  1526. }
  1527. // If `ty` is a type variable, see whether we already know what it is.
  1528. ty = self.resolve_type_vars_if_possible(&ty);
  1529. if !ty.has_infer_types() {
  1530. debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
  1531. return ty;
  1532. }
  1533. // If not, try resolving pending obligations as much as
  1534. // possible. This can help substantially when there are
  1535. // indirect dependencies that don't seem worth tracking
  1536. // precisely.
  1537. self.select_obligations_where_possible();
  1538. ty = self.resolve_type_vars_if_possible(&ty);
  1539. debug!("resolve_type_vars_with_obligations: ty={:?}", ty);
  1540. ty
  1541. }
  1542. fn record_deferred_call_resolution(&self,
  1543. closure_def_id: DefId,
  1544. r: DeferredCallResolutionHandler<'gcx, 'tcx>) {
  1545. let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
  1546. deferred_call_resolutions.entry(closure_def_id).or_insert(vec![]).push(r);
  1547. }
  1548. fn remove_deferred_call_resolutions(&self,
  1549. closure_def_id: DefId)
  1550. -> Vec<DeferredCallResolutionHandler<'gcx, 'tcx>>
  1551. {
  1552. let mut deferred_call_resolutions = self.deferred_call_resolutions.borrow_mut();
  1553. deferred_call_resolutions.remove(&closure_def_id).unwrap_or(Vec::new())
  1554. }
  1555. pub fn tag(&self) -> String {
  1556. let self_ptr: *const FnCtxt = self;
  1557. format!("{:?}", self_ptr)
  1558. }
  1559. pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> Ty<'tcx> {
  1560. match self.locals.borrow().get(&nid) {
  1561. Some(&t) => t,
  1562. None => {
  1563. span_bug!(span, "no type for local variable {}",
  1564. self.tcx.hir.node_to_string(nid));
  1565. }
  1566. }
  1567. }
  1568. #[inline]
  1569. pub fn write_ty(&self, node_id: ast::NodeId, ty: Ty<'tcx>) {
  1570. debug!("write_ty({}, {:?}) in fcx {}",
  1571. node_id, self.resolve_type_vars_if_possible(&ty), self.tag());
  1572. self.tables.borrow_mut().node_types.insert(node_id, ty);
  1573. if ty.references_error() {
  1574. self.has_errors.set(true);
  1575. self.set_tainted_by_errors();
  1576. }
  1577. }
  1578. pub fn write_substs(&self, node_id: ast::NodeId, substs: ty::ItemSubsts<'tcx>) {
  1579. if !substs.substs.is_noop() {
  1580. debug!("write_substs({}, {:?}) in fcx {}",
  1581. node_id,
  1582. substs,
  1583. self.tag());
  1584. self.tables.borrow_mut().item_substs.insert(node_id, substs);
  1585. }
  1586. }
  1587. pub fn apply_autoderef_adjustment(&self,
  1588. node_id: ast::NodeId,
  1589. derefs: usize,
  1590. adjusted_ty: Ty<'tcx>) {
  1591. self.apply_adjustment(node_id, Adjustment {
  1592. kind: Adjust::DerefRef {
  1593. autoderefs: derefs,
  1594. autoref: None,
  1595. unsize: false
  1596. },
  1597. target: adjusted_ty
  1598. });
  1599. }
  1600. pub fn apply_adjustment(&self, node_id: ast::NodeId, adj: Adjustment<'tcx>) {
  1601. debug!("apply_adjustment(node_id={}, adj={:?})", node_id, adj);
  1602. if adj.is_identity() {
  1603. return;
  1604. }
  1605. match self.tables.borrow_mut().adjustments.entry(node_id) {
  1606. Entry::Vacant(entry) => { entry.insert(adj); },
  1607. Entry::Occupied(mut entry) => {
  1608. debug!(" - composing on top of {:?}", entry.get());
  1609. let composed_kind = match (entry.get().kind, adj.kind) {
  1610. // Applying any adjustment on top of a NeverToAny
  1611. // is a valid NeverToAny adjustment, because it can't
  1612. // be reached.
  1613. (Adjust::NeverToAny, _) => Adjust::NeverToAny,
  1614. (Adjust::DerefRef {
  1615. autoderefs: 1,
  1616. autoref: Some(AutoBorrow::Ref(..)),
  1617. unsize: false
  1618. }, Adjust::DerefRef { autoderefs, .. }) if autoderefs > 0 => {
  1619. // A reborrow has no effect before a dereference.
  1620. adj.kind
  1621. }
  1622. // FIXME: currently we never try to compose autoderefs
  1623. // and ReifyFnPointer/UnsafeFnPointer, but we could.
  1624. _ =>
  1625. bug!("while adjusting {}, can't compose {:?} and {:?}",
  1626. node_id, entry.get(), adj)
  1627. };
  1628. *entry.get_mut() = Adjustment {
  1629. kind: composed_kind,
  1630. target: adj.target
  1631. };
  1632. }
  1633. }
  1634. }
  1635. /// Basically whenever we are converting from a type scheme into
  1636. /// the fn body space, we always want to normalize associated
  1637. /// types as well. This function combines the two.
  1638. fn instantiate_type_scheme<T>(&self,
  1639. span: Span,
  1640. substs: &Substs<'tcx>,
  1641. value: &T)
  1642. -> T
  1643. where T : TypeFoldable<'tcx>
  1644. {
  1645. let value = value.subst(self.tcx, substs);
  1646. let result = self.normalize_associated_types_in(span, &value);
  1647. debug!("instantiate_type_scheme(value={:?}, substs={:?}) = {:?}",
  1648. value,
  1649. substs,
  1650. result);
  1651. result
  1652. }
  1653. /// As `instantiate_type_scheme`, but for the bounds found in a
  1654. /// generic type scheme.
  1655. fn instantiate_bounds(&self, span: Span, def_id: DefId, substs: &Substs<'tcx>)
  1656. -> ty::InstantiatedPredicates<'tcx> {
  1657. let bounds = self.tcx.predicates_of(def_id);
  1658. let result = bounds.instantiate(self.tcx, substs);
  1659. let result = self.normalize_associated_types_in(span, &result);
  1660. debug!("instantiate_bounds(bounds={:?}, substs={:?}) = {:?}",
  1661. bounds,
  1662. substs,
  1663. result);
  1664. result
  1665. }
  1666. /// Replace all anonymized types with fresh inference variables
  1667. /// and record them for writeback.
  1668. fn instantiate_anon_types<T: TypeFoldable<'tcx>>(&self, value: &T) -> T {
  1669. value.fold_with(&mut BottomUpFolder { tcx: self.tcx, fldop: |ty| {
  1670. if let ty::TyAnon(def_id, substs) = ty.sty {
  1671. // Use the same type variable if the exact same TyAnon appears more
  1672. // than once in the return type (e.g. if it's pased to a type alias).
  1673. let id = self.tcx.hir.as_local_node_id(def_id).unwrap();
  1674. if let Some(ty_var) = self.anon_types.borrow().get(&id) {
  1675. return ty_var;
  1676. }
  1677. let span = self.tcx.def_span(def_id);
  1678. let ty_var = self.next_ty_var(TypeVariableOrigin::TypeInference(span));
  1679. self.anon_types.borrow_mut().insert(id, ty_var);
  1680. let predicates_of = self.tcx.predicates_of(def_id);
  1681. let bounds = predicates_of.instantiate(self.tcx, substs);
  1682. for predicate in bounds.predicates {
  1683. // Change the predicate to refer to the type variable,
  1684. // which will be the concrete type, instead of the TyAnon.
  1685. // This also instantiates nested `impl Trait`.
  1686. let predicate = self.instantiate_anon_types(&predicate);
  1687. // Require that the predicate holds for the concrete type.
  1688. let cause = traits::ObligationCause::new(span, self.body_id,
  1689. traits::ReturnType);
  1690. self.register_predicate(traits::Obligation::new(cause, predicate));
  1691. }
  1692. ty_var
  1693. } else {
  1694. ty
  1695. }
  1696. }})
  1697. }
  1698. fn normalize_associated_types_in<T>(&self, span: Span, value: &T) -> T
  1699. where T : TypeFoldable<'tcx>
  1700. {
  1701. let ok = self.normalize_associated_types_in_as_infer_ok(span, value);
  1702. self.register_infer_ok_obligations(ok)
  1703. }
  1704. fn normalize_associated_types_in_as_infer_ok<T>(&self, span: Span, value: &T)
  1705. -> InferOk<'tcx, T>
  1706. where T : TypeFoldable<'tcx>
  1707. {
  1708. self.inh.normalize_associated_types_in_as_infer_ok(span, self.body_id, value)
  1709. }
  1710. pub fn write_nil(&self, node_id: ast::NodeId) {
  1711. self.write_ty(node_id, self.tcx.mk_nil());
  1712. }
  1713. pub fn write_error(&self, node_id: ast::NodeId) {
  1714. self.write_ty(node_id, self.tcx.types.err);
  1715. }
  1716. pub fn require_type_meets(&self,
  1717. ty: Ty<'tcx>,
  1718. span: Span,
  1719. code: traits::ObligationCauseCode<'tcx>,
  1720. def_id: DefId)
  1721. {
  1722. self.register_bound(
  1723. ty,
  1724. def_id,
  1725. traits::ObligationCause::new(span, self.body_id, code));
  1726. }
  1727. pub fn require_type_is_sized(&self,
  1728. ty: Ty<'tcx>,
  1729. span: Span,
  1730. code: traits::ObligationCauseCode<'tcx>)
  1731. {
  1732. let lang_item = self.tcx.require_lang_item(lang_items::SizedTraitLangItem);
  1733. self.require_type_meets(ty, span, code, lang_item);
  1734. }
  1735. pub fn register_bound(&self,
  1736. ty: Ty<'tcx>,
  1737. def_id: DefId,
  1738. cause: traits::ObligationCause<'tcx>)
  1739. {
  1740. self.fulfillment_cx.borrow_mut()
  1741. .register_bound(self, ty, def_id, cause);
  1742. }
  1743. pub fn to_ty(&self, ast_t: &hir::Ty) -> Ty<'tcx> {
  1744. let t = AstConv::ast_ty_to_ty(self, ast_t);
  1745. self.register_wf_obligation(t, ast_t.span, traits::MiscObligation);
  1746. t
  1747. }
  1748. pub fn node_ty(&self, id: ast::NodeId) -> Ty<'tcx> {
  1749. match self.tables.borrow().node_types.get(&id) {
  1750. Some(&t) => t,
  1751. None if self.err_count_since_creation() != 0 => self.tcx.types.err,
  1752. None => {
  1753. bug!("no type for node {}: {} in fcx {}",
  1754. id, self.tcx.hir.node_to_string(id),
  1755. self.tag());
  1756. }
  1757. }
  1758. }
  1759. pub fn opt_node_ty_substs<F>(&self,
  1760. id: ast::NodeId,
  1761. f: F) where
  1762. F: FnOnce(&ty::ItemSubsts<'tcx>),
  1763. {
  1764. if let Some(s) = self.tables.borrow().item_substs.get(&id) {
  1765. f(s);
  1766. }
  1767. }
  1768. /// Registers an obligation for checking later, during regionck, that the type `ty` must
  1769. /// outlive the region `r`.
  1770. pub fn register_region_obligation(&self,
  1771. ty: Ty<'tcx>,
  1772. region: ty::Region<'tcx>,
  1773. cause: traits::ObligationCause<'tcx>)
  1774. {
  1775. let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
  1776. fulfillment_cx.register_region_obligation(ty, region, cause);
  1777. }
  1778. /// Registers an obligation for checking later, during regionck, that the type `ty` must
  1779. /// outlive the region `r`.
  1780. pub fn register_wf_obligation(&self,
  1781. ty: Ty<'tcx>,
  1782. span: Span,
  1783. code: traits::ObligationCauseCode<'tcx>)
  1784. {
  1785. // WF obligations never themselves fail, so no real need to give a detailed cause:
  1786. let cause = traits::ObligationCause::new(span, self.body_id, code);
  1787. self.register_predicate(traits::Obligation::new(cause, ty::Predicate::WellFormed(ty)));
  1788. }
  1789. pub fn register_old_wf_obligation(&self,
  1790. ty: Ty<'tcx>,
  1791. span: Span,
  1792. code: traits::ObligationCauseCode<'tcx>)
  1793. {
  1794. // Registers an "old-style" WF obligation that uses the
  1795. // implicator code. This is basically a buggy version of
  1796. // `register_wf_obligation` that is being kept around
  1797. // temporarily just to help with phasing in the newer rules.
  1798. //
  1799. // FIXME(#27579) all uses of this should be migrated to register_wf_obligation eventually
  1800. let cause = traits::ObligationCause::new(span, self.body_id, code);
  1801. self.register_region_obligation(ty, self.tcx.types.re_empty, cause);
  1802. }
  1803. /// Registers obligations that all types appearing in `substs` are well-formed.
  1804. pub fn add_wf_bounds(&self, substs: &Substs<'tcx>, expr: &hir::Expr)
  1805. {
  1806. for ty in substs.types() {
  1807. self.register_wf_obligation(ty, expr.span, traits::MiscObligation);
  1808. }
  1809. }
  1810. /// Given a fully substituted set of bounds (`generic_bounds`), and the values with which each
  1811. /// type/region parameter was instantiated (`substs`), creates and registers suitable
  1812. /// trait/region obligations.
  1813. ///
  1814. /// For example, if there is a function:
  1815. ///
  1816. /// ```
  1817. /// fn foo<'a,T:'a>(...)
  1818. /// ```
  1819. ///
  1820. /// and a reference:
  1821. ///
  1822. /// ```
  1823. /// let f = foo;
  1824. /// ```
  1825. ///
  1826. /// Then we will create a fresh region variable `'$0` and a fresh type variable `$1` for `'a`
  1827. /// and `T`. This routine will add a region obligation `$1:'$0` and register it locally.
  1828. pub fn add_obligations_for_parameters(&self,
  1829. cause: traits::ObligationCause<'tcx>,
  1830. predicates: &ty::InstantiatedPredicates<'tcx>)
  1831. {
  1832. assert!(!predicates.has_escaping_regions());
  1833. debug!("add_obligations_for_parameters(predicates={:?})",
  1834. predicates);
  1835. for obligation in traits::predicates_for_generics(cause, predicates) {
  1836. self.register_predicate(obligation);
  1837. }
  1838. }
  1839. // FIXME(arielb1): use this instead of field.ty everywhere
  1840. // Only for fields! Returns <none> for methods>
  1841. // Indifferent to privacy flags
  1842. pub fn field_ty(&self,
  1843. span: Span,
  1844. field: &'tcx ty::FieldDef,
  1845. substs: &Substs<'tcx>)
  1846. -> Ty<'tcx>
  1847. {
  1848. self.normalize_associated_types_in(span,
  1849. &field.ty(self.tcx, substs))
  1850. }
  1851. fn check_casts(&self) {
  1852. let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
  1853. for cast in deferred_cast_checks.drain(..) {
  1854. cast.check(self);
  1855. }
  1856. }
  1857. /// Apply "fallbacks" to some types
  1858. /// unconstrained types get replaced with ! or () (depending on whether
  1859. /// feature(never_type) is enabled), unconstrained ints with i32, and
  1860. /// unconstrained floats with f64.
  1861. fn default_type_parameters(&self) {
  1862. use rustc::ty::error::UnconstrainedNumeric::Neither;
  1863. use rustc::ty::error::UnconstrainedNumeric::{UnconstrainedInt, UnconstrainedFloat};
  1864. // Defaulting inference variables becomes very dubious if we have
  1865. // encountered type-checking errors. Therefore, if we think we saw
  1866. // some errors in this function, just resolve all uninstanted type
  1867. // varibles to TyError.
  1868. if self.is_tainted_by_errors() {
  1869. for ty in &self.unsolved_variables() {
  1870. if let ty::TyInfer(_) = self.shallow_resolve(ty).sty {
  1871. debug!("default_type_parameters: defaulting `{:?}` to error", ty);
  1872. self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx().types.err);
  1873. }
  1874. }
  1875. return;
  1876. }
  1877. for ty in &self.unsolved_variables() {
  1878. let resolved = self.resolve_type_vars_if_possible(ty);
  1879. if self.type_var_diverges(resolved) {
  1880. debug!("default_type_parameters: defaulting `{:?}` to `!` because it diverges",
  1881. resolved);
  1882. self.demand_eqtype(syntax_pos::DUMMY_SP, *ty,
  1883. self.tcx.mk_diverging_default());
  1884. } else {
  1885. match self.type_is_unconstrained_numeric(resolved) {
  1886. UnconstrainedInt => {
  1887. debug!("default_type_parameters: defaulting `{:?}` to `i32`",
  1888. resolved);
  1889. self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.i32)
  1890. },
  1891. UnconstrainedFloat => {
  1892. debug!("default_type_parameters: defaulting `{:?}` to `f32`",
  1893. resolved);
  1894. self.demand_eqtype(syntax_pos::DUMMY_SP, *ty, self.tcx.types.f64)
  1895. }
  1896. Neither => { }
  1897. }
  1898. }
  1899. }
  1900. }
  1901. // Implements type inference fallback algorithm
  1902. fn select_all_obligations_and_apply_defaults(&self) {
  1903. self.select_obligations_where_possible();
  1904. self.default_type_parameters();
  1905. self.select_obligations_where_possible();
  1906. }
  1907. fn select_all_obligations_or_error(&self) {
  1908. debug!("select_all_obligations_or_error");
  1909. // upvar inference should have ensured that all deferred call
  1910. // resolutions are handled by now.
  1911. assert!(self.deferred_call_resolutions.borrow().is_empty());
  1912. self.select_all_obligations_and_apply_defaults();
  1913. let mut fulfillment_cx = self.fulfillment_cx.borrow_mut();
  1914. match fulfillment_cx.select_all_or_error(self) {
  1915. Ok(()) => { }
  1916. Err(errors) => { self.report_fulfillment_errors(&errors); }
  1917. }
  1918. }
  1919. /// Select as many obligations as we can at present.
  1920. fn select_obligations_where_possible(&self) {
  1921. match self.fulfillment_cx.borrow_mut().select_where_possible(self) {
  1922. Ok(()) => { }
  1923. Err(errors) => { self.report_fulfillment_errors(&errors); }
  1924. }
  1925. }
  1926. /// For the overloaded lvalue expressions (`*x`, `x[3]`), the trait
  1927. /// returns a type of `&T`, but the actual type we assign to the
  1928. /// *expression* is `T`. So this function just peels off the return
  1929. /// type by one layer to yield `T`.
  1930. fn make_overloaded_lvalue_return_type(&self,
  1931. method: MethodCallee<'tcx>)
  1932. -> ty::TypeAndMut<'tcx>
  1933. {
  1934. // extract method return type, which will be &T;
  1935. // all LB regions should have been instantiated during method lookup
  1936. let ret_ty = method.ty.fn_ret();
  1937. let ret_ty = self.tcx.no_late_bound_regions(&ret_ty).unwrap();
  1938. // method returns &T, but the type as visible to user is T, so deref
  1939. ret_ty.builtin_deref(true, NoPreference).unwrap()
  1940. }
  1941. fn lookup_indexing(&self,
  1942. expr: &hir::Expr,
  1943. base_expr: &'gcx hir::Expr,
  1944. base_ty: Ty<'tcx>,
  1945. idx_ty: Ty<'tcx>,
  1946. lvalue_pref: LvaluePreference)
  1947. -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
  1948. {
  1949. // FIXME(#18741) -- this is almost but not quite the same as the
  1950. // autoderef that normal method probing does. They could likely be
  1951. // consolidated.
  1952. let mut autoderef = self.autoderef(base_expr.span, base_ty);
  1953. while let Some((adj_ty, autoderefs)) = autoderef.next() {
  1954. if let Some(final_mt) = self.try_index_step(
  1955. MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
  1956. rcvr_expr: base_expr,
  1957. autoderefs,
  1958. unsize: false
  1959. }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
  1960. {
  1961. autoderef.finalize(lvalue_pref, base_expr);
  1962. return Some(final_mt);
  1963. }
  1964. if let ty::TyArray(element_ty, _) = adj_ty.sty {
  1965. autoderef.finalize(lvalue_pref, base_expr);
  1966. let adj_ty = self.tcx.mk_slice(element_ty);
  1967. return self.try_index_step(
  1968. MethodCall::expr(expr.id), expr, Some(AdjustedRcvr {
  1969. rcvr_expr: base_expr,
  1970. autoderefs,
  1971. unsize: true
  1972. }), base_expr.span, adj_ty, lvalue_pref, idx_ty)
  1973. }
  1974. }
  1975. autoderef.unambiguous_final_ty();
  1976. None
  1977. }
  1978. /// To type-check `base_expr[index_expr]`, we progressively autoderef
  1979. /// (and otherwise adjust) `base_expr`, looking for a type which either
  1980. /// supports builtin indexing or overloaded indexing.
  1981. /// This loop implements one step in that search; the autoderef loop
  1982. /// is implemented by `lookup_indexing`.
  1983. fn try_index_step(&self,
  1984. method_call: MethodCall,
  1985. expr: &hir::Expr,
  1986. base_expr: Option<AdjustedRcvr>,
  1987. base_span: Span,
  1988. adjusted_ty: Ty<'tcx>,
  1989. lvalue_pref: LvaluePreference,
  1990. index_ty: Ty<'tcx>)
  1991. -> Option<(/*index type*/ Ty<'tcx>, /*element type*/ Ty<'tcx>)>
  1992. {
  1993. let tcx = self.tcx;
  1994. debug!("try_index_step(expr={:?}, base_expr={:?}, adjusted_ty={:?}, \
  1995. index_ty={:?})",
  1996. expr,
  1997. base_expr,
  1998. adjusted_ty,
  1999. index_ty);
  2000. let input_ty = self.next_ty_var(TypeVariableOrigin::AutoDeref(base_span));
  2001. // First, try built-in indexing.
  2002. match (adjusted_ty.builtin_index(), &index_ty.sty) {
  2003. (Some(ty), &ty::TyUint(ast::UintTy::Us)) | (Some(ty), &ty::TyInfer(ty::IntVar(_))) => {
  2004. debug!("try_index_step: success, using built-in indexing");
  2005. // If we had `[T; N]`, we should've caught it before unsizing to `[T]`.
  2006. if let Some(base_expr) = base_expr {
  2007. assert!(!base_expr.unsize);
  2008. self.apply_autoderef_adjustment(
  2009. base_expr.rcvr_expr.id, base_expr.autoderefs, adjusted_ty);
  2010. }
  2011. return Some((tcx.types.usize, ty));
  2012. }
  2013. _ => {}
  2014. }
  2015. // If some lookup succeeds, write callee into table and extract index/element
  2016. // type from the method signature.
  2017. // If some lookup succeeded, install method in table
  2018. let method = self.try_overloaded_lvalue_op(
  2019. expr.span, base_expr, adjusted_ty, &[input_ty], lvalue_pref, LvalueOp::Index);
  2020. method.map(|ok| {
  2021. debug!("try_index_step: success, using overloaded indexing");
  2022. let method = self.register_infer_ok_obligations(ok);
  2023. self.tables.borrow_mut().method_map.insert(method_call, method);
  2024. (input_ty, self.make_overloaded_lvalue_return_type(method).ty)
  2025. })
  2026. }
  2027. fn resolve_lvalue_op(&self, op: LvalueOp, is_mut: bool) -> (Option<DefId>, Symbol) {
  2028. let (tr, name) = match (op, is_mut) {
  2029. (LvalueOp::Deref, false) =>
  2030. (self.tcx.lang_items.deref_trait(), "deref"),
  2031. (LvalueOp::Deref, true) =>
  2032. (self.tcx.lang_items.deref_mut_trait(), "deref_mut"),
  2033. (LvalueOp::Index, false) =>
  2034. (self.tcx.lang_items.index_trait(), "index"),
  2035. (LvalueOp::Index, true) =>
  2036. (self.tcx.lang_items.index_mut_trait(), "index_mut"),
  2037. };
  2038. (tr, Symbol::intern(name))
  2039. }
  2040. fn try_overloaded_lvalue_op(&self,
  2041. span: Span,
  2042. base_expr: Option<AdjustedRcvr>,
  2043. base_ty: Ty<'tcx>,
  2044. arg_tys: &[Ty<'tcx>],
  2045. lvalue_pref: LvaluePreference,
  2046. op: LvalueOp)
  2047. -> Option<InferOk<'tcx, MethodCallee<'tcx>>>
  2048. {
  2049. debug!("try_overloaded_lvalue_op({:?},{:?},{:?},{:?},{:?})",
  2050. span,
  2051. base_expr,
  2052. base_ty,
  2053. lvalue_pref,
  2054. op);
  2055. // Try Mut first, if preferred.
  2056. let (mut_tr, mut_op) = self.resolve_lvalue_op(op, true);
  2057. let method = match (lvalue_pref, mut_tr) {
  2058. (PreferMutLvalue, Some(trait_did)) => {
  2059. self.lookup_method_in_trait_adjusted(span,
  2060. base_expr,
  2061. mut_op,
  2062. trait_did,
  2063. base_ty,
  2064. Some(arg_tys.to_owned()))
  2065. }
  2066. _ => None,
  2067. };
  2068. // Otherwise, fall back to the immutable version.
  2069. let (imm_tr, imm_op) = self.resolve_lvalue_op(op, false);
  2070. let method = match (method, imm_tr) {
  2071. (None, Some(trait_did)) => {
  2072. self.lookup_method_in_trait_adjusted(span,
  2073. base_expr,
  2074. imm_op,
  2075. trait_did,
  2076. base_ty,
  2077. Some(arg_tys.to_owned()))
  2078. }
  2079. (method, _) => method,
  2080. };
  2081. method
  2082. }
  2083. fn check_method_argument_types(&self,
  2084. sp: Span,
  2085. method_fn_ty: Ty<'tcx>,
  2086. callee_expr: &'gcx hir::Expr,
  2087. args_no_rcvr: &'gcx [hir::Expr],
  2088. tuple_arguments: TupleArgumentsFlag,
  2089. expected: Expectation<'tcx>)
  2090. -> Ty<'tcx> {
  2091. if method_fn_ty.references_error() {
  2092. let err_inputs = self.err_args(args_no_rcvr.len());
  2093. let err_inputs = match tuple_arguments {
  2094. DontTupleArguments => err_inputs,
  2095. TupleArguments => vec![self.tcx.intern_tup(&err_inputs[..], false)],
  2096. };
  2097. self.check_argument_types(sp, &err_inputs[..], &[], args_no_rcvr,
  2098. false, tuple_arguments, None);
  2099. self.tcx.types.err
  2100. } else {
  2101. match method_fn_ty.sty {
  2102. ty::TyFnDef(def_id, .., ref fty) => {
  2103. // HACK(eddyb) ignore self in the definition (see above).
  2104. let expected_arg_tys = self.expected_inputs_for_expected_output(
  2105. sp,
  2106. expected,
  2107. fty.0.output(),
  2108. &fty.0.inputs()[1..]
  2109. );
  2110. self.check_argument_types(sp, &fty.0.inputs()[1..], &expected_arg_tys[..],
  2111. args_no_rcvr, fty.0.variadic, tuple_arguments,
  2112. self.tcx.hir.span_if_local(def_id));
  2113. fty.0.output()
  2114. }
  2115. _ => {
  2116. span_bug!(callee_expr.span, "method without bare fn type");
  2117. }
  2118. }
  2119. }
  2120. }
  2121. /// Generic function that factors out common logic from function calls,
  2122. /// method calls and overloaded operators.
  2123. fn check_argument_types(&self,
  2124. sp: Span,
  2125. fn_inputs: &[Ty<'tcx>],
  2126. expected_arg_tys: &[Ty<'tcx>],
  2127. args: &'gcx [hir::Expr],
  2128. variadic: bool,
  2129. tuple_arguments: TupleArgumentsFlag,
  2130. def_span: Option<Span>) {
  2131. let tcx = self.tcx;
  2132. // Grab the argument types, supplying fresh type variables
  2133. // if the wrong number of arguments were supplied
  2134. let supplied_arg_count = if tuple_arguments == DontTupleArguments {
  2135. args.len()
  2136. } else {
  2137. 1
  2138. };
  2139. // All the input types from the fn signature must outlive the call
  2140. // so as to validate implied bounds.
  2141. for &fn_input_ty in fn_inputs {
  2142. self.register_wf_obligation(fn_input_ty, sp, traits::MiscObligation);
  2143. }
  2144. let mut expected_arg_tys = expected_arg_tys;
  2145. let expected_arg_count = fn_inputs.len();
  2146. let sp_args = if args.len() > 0 {
  2147. let (first, args) = args.split_at(1);
  2148. let mut sp_tmp = first[0].span;
  2149. for arg in args {
  2150. let sp_opt = self.sess().codemap().merge_spans(sp_tmp, arg.span);
  2151. if ! sp_opt.is_some() {
  2152. break;
  2153. }
  2154. sp_tmp = sp_opt.unwrap();
  2155. };
  2156. sp_tmp
  2157. } else {
  2158. sp
  2159. };
  2160. fn parameter_count_error<'tcx>(sess: &Session, sp: Span, expected_count: usize,
  2161. arg_count: usize, error_code: &str, variadic: bool,
  2162. def_span: Option<Span>) {
  2163. let mut err = sess.struct_span_err_with_code(sp,
  2164. &format!("this function takes {}{} parameter{} but {} parameter{} supplied",
  2165. if variadic {"at least "} else {""},
  2166. expected_count,
  2167. if expected_count == 1 {""} else {"s"},
  2168. arg_count,
  2169. if arg_count == 1 {" was"} else {"s were"}),
  2170. error_code);
  2171. err.span_label(sp, format!("expected {}{} parameter{}",
  2172. if variadic {"at least "} else {""},
  2173. expected_count,
  2174. if expected_count == 1 {""} else {"s"}));
  2175. if let Some(def_s) = def_span {
  2176. err.span_label(def_s, "defined here");
  2177. }
  2178. err.emit();
  2179. }
  2180. let formal_tys = if tuple_arguments == TupleArguments {
  2181. let tuple_type = self.structurally_resolved_type(sp, fn_inputs[0]);
  2182. match tuple_type.sty {
  2183. ty::TyTuple(arg_types, _) if arg_types.len() != args.len() => {
  2184. parameter_count_error(tcx.sess, sp_args, arg_types.len(), args.len(),
  2185. "E0057", false, def_span);
  2186. expected_arg_tys = &[];
  2187. self.err_args(args.len())
  2188. }
  2189. ty::TyTuple(arg_types, _) => {
  2190. expected_arg_tys = match expected_arg_tys.get(0) {
  2191. Some(&ty) => match ty.sty {
  2192. ty::TyTuple(ref tys, _) => &tys,
  2193. _ => &[]
  2194. },
  2195. None => &[]
  2196. };
  2197. arg_types.to_vec()
  2198. }
  2199. _ => {
  2200. span_err!(tcx.sess, sp, E0059,
  2201. "cannot use call notation; the first type parameter \
  2202. for the function trait is neither a tuple nor unit");
  2203. expected_arg_tys = &[];
  2204. self.err_args(args.len())
  2205. }
  2206. }
  2207. } else if expected_arg_count == supplied_arg_count {
  2208. fn_inputs.to_vec()
  2209. } else if variadic {
  2210. if supplied_arg_count >= expected_arg_count {
  2211. fn_inputs.to_vec()
  2212. } else {
  2213. parameter_count_error(tcx.sess, sp_args, expected_arg_count,
  2214. supplied_arg_count, "E0060", true, def_span);
  2215. expected_arg_tys = &[];
  2216. self.err_args(supplied_arg_count)
  2217. }
  2218. } else {
  2219. parameter_count_error(tcx.sess, sp_args, expected_arg_count,
  2220. supplied_arg_count, "E0061", false, def_span);
  2221. expected_arg_tys = &[];
  2222. self.err_args(supplied_arg_count)
  2223. };
  2224. debug!("check_argument_types: formal_tys={:?}",
  2225. formal_tys.iter().map(|t| self.ty_to_string(*t)).collect::<Vec<String>>());
  2226. // Check the arguments.
  2227. // We do this in a pretty awful way: first we typecheck any arguments
  2228. // that are not closures, then we typecheck the closures. This is so
  2229. // that we have more information about the types of arguments when we
  2230. // typecheck the functions. This isn't really the right way to do this.
  2231. for &check_closures in &[false, true] {
  2232. debug!("check_closures={}", check_closures);
  2233. // More awful hacks: before we check argument types, try to do
  2234. // an "opportunistic" vtable resolution of any trait bounds on
  2235. // the call. This helps coercions.
  2236. if check_closures {
  2237. self.select_obligations_where_possible();
  2238. }
  2239. // For variadic functions, we don't have a declared type for all of
  2240. // the arguments hence we only do our usual type checking with
  2241. // the arguments who's types we do know.
  2242. let t = if variadic {
  2243. expected_arg_count
  2244. } else if tuple_arguments == TupleArguments {
  2245. args.len()
  2246. } else {
  2247. supplied_arg_count
  2248. };
  2249. for (i, arg) in args.iter().take(t).enumerate() {
  2250. // Warn only for the first loop (the "no closures" one).
  2251. // Closure arguments themselves can't be diverging, but
  2252. // a previous argument can, e.g. `foo(panic!(), || {})`.
  2253. if !check_closures {
  2254. self.warn_if_unreachable(arg.id, arg.span, "expression");
  2255. }
  2256. let is_closure = match arg.node {
  2257. hir::ExprClosure(..) => true,
  2258. _ => false
  2259. };
  2260. if is_closure != check_closures {
  2261. continue;
  2262. }
  2263. debug!("checking the argument");
  2264. let formal_ty = formal_tys[i];
  2265. // The special-cased logic below has three functions:
  2266. // 1. Provide as good of an expected type as possible.
  2267. let expected = expected_arg_tys.get(i).map(|&ty| {
  2268. Expectation::rvalue_hint(self, ty)
  2269. });
  2270. let checked_ty = self.check_expr_with_expectation(
  2271. &arg,
  2272. expected.unwrap_or(ExpectHasType(formal_ty)));
  2273. // 2. Coerce to the most detailed type that could be coerced
  2274. // to, which is `expected_ty` if `rvalue_hint` returns an
  2275. // `ExpectHasType(expected_ty)`, or the `formal_ty` otherwise.
  2276. let coerce_ty = expected.and_then(|e| e.only_has_type(self));
  2277. self.demand_coerce(&arg, checked_ty, coerce_ty.unwrap_or(formal_ty));
  2278. // 3. Relate the expected type and the formal one,
  2279. // if the expected type was used for the coercion.
  2280. coerce_ty.map(|ty| self.demand_suptype(arg.span, formal_ty, ty));
  2281. }
  2282. }
  2283. // We also need to make sure we at least write the ty of the other
  2284. // arguments which we skipped above.
  2285. if variadic {
  2286. for arg in args.iter().skip(expected_arg_count) {
  2287. let arg_ty = self.check_expr(&arg);
  2288. // There are a few types which get autopromoted when passed via varargs
  2289. // in C but we just error out instead and require explicit casts.
  2290. let arg_ty = self.structurally_resolved_type(arg.span,
  2291. arg_ty);
  2292. match arg_ty.sty {
  2293. ty::TyFloat(ast::FloatTy::F32) => {
  2294. self.type_error_message(arg.span, |t| {
  2295. format!("can't pass an `{}` to variadic \
  2296. function, cast to `c_double`", t)
  2297. }, arg_ty);
  2298. }
  2299. ty::TyInt(ast::IntTy::I8) | ty::TyInt(ast::IntTy::I16) | ty::TyBool => {
  2300. self.type_error_message(arg.span, |t| {
  2301. format!("can't pass `{}` to variadic \
  2302. function, cast to `c_int`",
  2303. t)
  2304. }, arg_ty);
  2305. }
  2306. ty::TyUint(ast::UintTy::U8) | ty::TyUint(ast::UintTy::U16) => {
  2307. self.type_error_message(arg.span, |t| {
  2308. format!("can't pass `{}` to variadic \
  2309. function, cast to `c_uint`",
  2310. t)
  2311. }, arg_ty);
  2312. }
  2313. ty::TyFnDef(.., f) => {
  2314. let ptr_ty = self.tcx.mk_fn_ptr(f);
  2315. let ptr_ty = self.resolve_type_vars_if_possible(&ptr_ty);
  2316. self.type_error_message(arg.span,
  2317. |t| {
  2318. format!("can't pass `{}` to variadic \
  2319. function, cast to `{}`", t, ptr_ty)
  2320. }, arg_ty);
  2321. }
  2322. _ => {}
  2323. }
  2324. }
  2325. }
  2326. }
  2327. fn err_args(&self, len: usize) -> Vec<Ty<'tcx>> {
  2328. (0..len).map(|_| self.tcx.types.err).collect()
  2329. }
  2330. // AST fragment checking
  2331. fn check_lit(&self,
  2332. lit: &ast::Lit,
  2333. expected: Expectation<'tcx>)
  2334. -> Ty<'tcx>
  2335. {
  2336. let tcx = self.tcx;
  2337. match lit.node {
  2338. ast::LitKind::Str(..) => tcx.mk_static_str(),
  2339. ast::LitKind::ByteStr(ref v) => {
  2340. tcx.mk_imm_ref(tcx.types.re_static,
  2341. tcx.mk_array(tcx.types.u8, v.len()))
  2342. }
  2343. ast::LitKind::Byte(_) => tcx.types.u8,
  2344. ast::LitKind::Char(_) => tcx.types.char,
  2345. ast::LitKind::Int(_, ast::LitIntType::Signed(t)) => tcx.mk_mach_int(t),
  2346. ast::LitKind::Int(_, ast::LitIntType::Unsigned(t)) => tcx.mk_mach_uint(t),
  2347. ast::LitKind::Int(_, ast::LitIntType::Unsuffixed) => {
  2348. let opt_ty = expected.to_option(self).and_then(|ty| {
  2349. match ty.sty {
  2350. ty::TyInt(_) | ty::TyUint(_) => Some(ty),
  2351. ty::TyChar => Some(tcx.types.u8),
  2352. ty::TyRawPtr(..) => Some(tcx.types.usize),
  2353. ty::TyFnDef(..) | ty::TyFnPtr(_) => Some(tcx.types.usize),
  2354. _ => None
  2355. }
  2356. });
  2357. opt_ty.unwrap_or_else(
  2358. || tcx.mk_int_var(self.next_int_var_id()))
  2359. }
  2360. ast::LitKind::Float(_, t) => tcx.mk_mach_float(t),
  2361. ast::LitKind::FloatUnsuffixed(_) => {
  2362. let opt_ty = expected.to_option(self).and_then(|ty| {
  2363. match ty.sty {
  2364. ty::TyFloat(_) => Some(ty),
  2365. _ => None
  2366. }
  2367. });
  2368. opt_ty.unwrap_or_else(
  2369. || tcx.mk_float_var(self.next_float_var_id()))
  2370. }
  2371. ast::LitKind::Bool(_) => tcx.types.bool
  2372. }
  2373. }
  2374. fn check_expr_eq_type(&self,
  2375. expr: &'gcx hir::Expr,
  2376. expected: Ty<'tcx>) {
  2377. let ty = self.check_expr_with_hint(expr, expected);
  2378. self.demand_eqtype(expr.span, expected, ty);
  2379. }
  2380. pub fn check_expr_has_type(&self,
  2381. expr: &'gcx hir::Expr,
  2382. expected: Ty<'tcx>) -> Ty<'tcx> {
  2383. let mut ty = self.check_expr_with_hint(expr, expected);
  2384. // While we don't allow *arbitrary* coercions here, we *do* allow
  2385. // coercions from ! to `expected`.
  2386. if ty.is_never() {
  2387. assert!(!self.tables.borrow().adjustments.contains_key(&expr.id),
  2388. "expression with never type wound up being adjusted");
  2389. let adj_ty = self.next_diverging_ty_var(
  2390. TypeVariableOrigin::AdjustmentType(expr.span));
  2391. self.apply_adjustment(expr.id, Adjustment {
  2392. kind: Adjust::NeverToAny,
  2393. target: adj_ty
  2394. });
  2395. ty = adj_ty;
  2396. }
  2397. self.demand_suptype(expr.span, expected, ty);
  2398. ty
  2399. }
  2400. fn check_expr_coercable_to_type(&self,
  2401. expr: &'gcx hir::Expr,
  2402. expected: Ty<'tcx>) -> Ty<'tcx> {
  2403. let ty = self.check_expr_with_hint(expr, expected);
  2404. self.demand_coerce(expr, ty, expected);
  2405. ty
  2406. }
  2407. fn check_expr_with_hint(&self, expr: &'gcx hir::Expr,
  2408. expected: Ty<'tcx>) -> Ty<'tcx> {
  2409. self.check_expr_with_expectation(expr, ExpectHasType(expected))
  2410. }
  2411. fn check_expr_with_expectation(&self,
  2412. expr: &'gcx hir::Expr,
  2413. expected: Expectation<'tcx>) -> Ty<'tcx> {
  2414. self.check_expr_with_expectation_and_lvalue_pref(expr, expected, NoPreference)
  2415. }
  2416. fn check_expr(&self, expr: &'gcx hir::Expr) -> Ty<'tcx> {
  2417. self.check_expr_with_expectation(expr, NoExpectation)
  2418. }
  2419. fn check_expr_with_lvalue_pref(&self, expr: &'gcx hir::Expr,
  2420. lvalue_pref: LvaluePreference) -> Ty<'tcx> {
  2421. self.check_expr_with_expectation_and_lvalue_pref(expr, NoExpectation, lvalue_pref)
  2422. }
  2423. // determine the `self` type, using fresh variables for all variables
  2424. // declared on the impl declaration e.g., `impl<A,B> for Vec<(A,B)>`
  2425. // would return ($0, $1) where $0 and $1 are freshly instantiated type
  2426. // variables.
  2427. pub fn impl_self_ty(&self,
  2428. span: Span, // (potential) receiver for this impl
  2429. did: DefId)
  2430. -> TypeAndSubsts<'tcx> {
  2431. let ity = self.tcx.type_of(did);
  2432. debug!("impl_self_ty: ity={:?}", ity);
  2433. let substs = self.fresh_substs_for_item(span, did);
  2434. let substd_ty = self.instantiate_type_scheme(span, &substs, &ity);
  2435. TypeAndSubsts { substs: substs, ty: substd_ty }
  2436. }
  2437. /// Unifies the output type with the expected type early, for more coercions
  2438. /// and forward type information on the input expressions.
  2439. fn expected_inputs_for_expected_output(&self,
  2440. call_span: Span,
  2441. expected_ret: Expectation<'tcx>,
  2442. formal_ret: Ty<'tcx>,
  2443. formal_args: &[Ty<'tcx>])
  2444. -> Vec<Ty<'tcx>> {
  2445. let expected_args = expected_ret.only_has_type(self).and_then(|ret_ty| {
  2446. self.fudge_regions_if_ok(&RegionVariableOrigin::Coercion(call_span), || {
  2447. // Attempt to apply a subtyping relationship between the formal
  2448. // return type (likely containing type variables if the function
  2449. // is polymorphic) and the expected return type.
  2450. // No argument expectations are produced if unification fails.
  2451. let origin = self.misc(call_span);
  2452. let ures = self.sub_types(false, &origin, formal_ret, ret_ty);
  2453. // FIXME(#15760) can't use try! here, FromError doesn't default
  2454. // to identity so the resulting type is not constrained.
  2455. match ures {
  2456. Ok(ok) => {
  2457. // Process any obligations locally as much as
  2458. // we can. We don't care if some things turn
  2459. // out unconstrained or ambiguous, as we're
  2460. // just trying to get hints here.
  2461. let result = self.save_and_restore_in_snapshot_flag(|_| {
  2462. let mut fulfill = FulfillmentContext::new();
  2463. let ok = ok; // FIXME(#30046)
  2464. for obligation in ok.obligations {
  2465. fulfill.register_predicate_obligation(self, obligation);
  2466. }
  2467. fulfill.select_where_possible(self)
  2468. });
  2469. match result {
  2470. Ok(()) => { }
  2471. Err(_) => return Err(()),
  2472. }
  2473. }
  2474. Err(_) => return Err(()),
  2475. }
  2476. // Record all the argument types, with the substitutions
  2477. // produced from the above subtyping unification.
  2478. Ok(formal_args.iter().map(|ty| {
  2479. self.resolve_type_vars_if_possible(ty)
  2480. }).collect())
  2481. }).ok()
  2482. }).unwrap_or(vec![]);
  2483. debug!("expected_inputs_for_expected_output(formal={:?} -> {:?}, expected={:?} -> {:?})",
  2484. formal_args, formal_ret,
  2485. expected_args, expected_ret);
  2486. expected_args
  2487. }
  2488. // Checks a method call.
  2489. fn check_method_call(&self,
  2490. expr: &'gcx hir::Expr,
  2491. method_name: Spanned<ast::Name>,
  2492. args: &'gcx [hir::Expr],
  2493. tps: &[P<hir::Ty>],
  2494. expected: Expectation<'tcx>,
  2495. lvalue_pref: LvaluePreference) -> Ty<'tcx> {
  2496. let rcvr = &args[0];
  2497. let rcvr_t = self.check_expr_with_lvalue_pref(&rcvr, lvalue_pref);
  2498. // no need to check for bot/err -- callee does that
  2499. let expr_t = self.structurally_resolved_type(expr.span, rcvr_t);
  2500. let tps = tps.iter().map(|ast_ty| self.to_ty(&ast_ty)).collect::<Vec<_>>();
  2501. let fn_ty = match self.lookup_method(method_name.span,
  2502. method_name.node,
  2503. expr_t,
  2504. tps,
  2505. expr,
  2506. rcvr) {
  2507. Ok(method) => {
  2508. let method_ty = method.ty;
  2509. let method_call = MethodCall::expr(expr.id);
  2510. self.tables.borrow_mut().method_map.insert(method_call, method);
  2511. method_ty
  2512. }
  2513. Err(error) => {
  2514. if method_name.node != keywords::Invalid.name() {
  2515. self.report_method_error(method_name.span,
  2516. expr_t,
  2517. method_name.node,
  2518. Some(rcvr),
  2519. error,
  2520. Some(args));
  2521. }
  2522. self.write_error(expr.id);
  2523. self.tcx.types.err
  2524. }
  2525. };
  2526. // Call the generic checker.
  2527. let ret_ty = self.check_method_argument_types(method_name.span, fn_ty,
  2528. expr, &args[1..],
  2529. DontTupleArguments,
  2530. expected);
  2531. ret_ty
  2532. }
  2533. fn check_return_expr(&self, return_expr: &'gcx hir::Expr) {
  2534. let ret_coercion =
  2535. self.ret_coercion
  2536. .as_ref()
  2537. .unwrap_or_else(|| span_bug!(return_expr.span,
  2538. "check_return_expr called outside fn body"));
  2539. let ret_ty = ret_coercion.borrow().expected_ty();
  2540. let return_expr_ty = self.check_expr_with_hint(return_expr, ret_ty);
  2541. ret_coercion.borrow_mut()
  2542. .coerce(self,
  2543. &self.misc(return_expr.span),
  2544. return_expr,
  2545. return_expr_ty,
  2546. self.diverges.get());
  2547. }
  2548. // A generic function for checking the then and else in an if
  2549. // or if-else.
  2550. fn check_then_else(&self,
  2551. cond_expr: &'gcx hir::Expr,
  2552. then_expr: &'gcx hir::Expr,
  2553. opt_else_expr: Option<&'gcx hir::Expr>,
  2554. sp: Span,
  2555. expected: Expectation<'tcx>) -> Ty<'tcx> {
  2556. let cond_ty = self.check_expr_has_type(cond_expr, self.tcx.types.bool);
  2557. let cond_diverges = self.diverges.get();
  2558. self.diverges.set(Diverges::Maybe);
  2559. let expected = expected.adjust_for_branches(self);
  2560. let then_ty = self.check_expr_with_expectation(then_expr, expected);
  2561. let then_diverges = self.diverges.get();
  2562. self.diverges.set(Diverges::Maybe);
  2563. // We've already taken the expected type's preferences
  2564. // into account when typing the `then` branch. To figure
  2565. // out the initial shot at a LUB, we thus only consider
  2566. // `expected` if it represents a *hard* constraint
  2567. // (`only_has_type`); otherwise, we just go with a
  2568. // fresh type variable.
  2569. let coerce_to_ty = expected.coercion_target_type(self, sp);
  2570. let mut coerce: DynamicCoerceMany = CoerceMany::new(coerce_to_ty);
  2571. let if_cause = self.cause(sp, ObligationCauseCode::IfExpression);
  2572. coerce.coerce(self, &if_cause, then_expr, then_ty, then_diverges);
  2573. if let Some(else_expr) = opt_else_expr {
  2574. let else_ty = self.check_expr_with_expectation(else_expr, expected);
  2575. let else_diverges = self.diverges.get();
  2576. coerce.coerce(self, &if_cause, else_expr, else_ty, else_diverges);
  2577. // We won't diverge unless both branches do (or the condition does).
  2578. self.diverges.set(cond_diverges | then_diverges & else_diverges);
  2579. } else {
  2580. let else_cause = self.cause(sp, ObligationCauseCode::IfExpressionWithNoElse);
  2581. coerce.coerce_forced_unit(self, &else_cause, &mut |_| (), true);
  2582. // If the condition is false we can't diverge.
  2583. self.diverges.set(cond_diverges);
  2584. }
  2585. let result_ty = coerce.complete(self);
  2586. if cond_ty.references_error() {
  2587. self.tcx.types.err
  2588. } else {
  2589. result_ty
  2590. }
  2591. }
  2592. // Check field access expressions
  2593. fn check_field(&self,
  2594. expr: &'gcx hir::Expr,
  2595. lvalue_pref: LvaluePreference,
  2596. base: &'gcx hir::Expr,
  2597. field: &Spanned<ast::Name>) -> Ty<'tcx> {
  2598. let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
  2599. let expr_t = self.structurally_resolved_type(expr.span,
  2600. expr_t);
  2601. let mut private_candidate = None;
  2602. let mut autoderef = self.autoderef(expr.span, expr_t);
  2603. while let Some((base_t, autoderefs)) = autoderef.next() {
  2604. match base_t.sty {
  2605. ty::TyAdt(base_def, substs) if !base_def.is_enum() => {
  2606. debug!("struct named {:?}", base_t);
  2607. if let Some(field) = base_def.struct_variant().find_field_named(field.node) {
  2608. let field_ty = self.field_ty(expr.span, field, substs);
  2609. if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
  2610. autoderef.finalize(lvalue_pref, base);
  2611. self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
  2612. self.tcx.check_stability(field.did, expr.id, expr.span);
  2613. return field_ty;
  2614. }
  2615. private_candidate = Some((base_def.did, field_ty));
  2616. }
  2617. }
  2618. _ => {}
  2619. }
  2620. }
  2621. autoderef.unambiguous_final_ty();
  2622. if let Some((did, field_ty)) = private_candidate {
  2623. let struct_path = self.tcx().item_path_str(did);
  2624. let msg = format!("field `{}` of struct `{}` is private", field.node, struct_path);
  2625. let mut err = self.tcx().sess.struct_span_err(expr.span, &msg);
  2626. // Also check if an accessible method exists, which is often what is meant.
  2627. if self.method_exists(field.span, field.node, expr_t, expr.id, false) {
  2628. err.note(&format!("a method `{}` also exists, perhaps you wish to call it",
  2629. field.node));
  2630. }
  2631. err.emit();
  2632. field_ty
  2633. } else if field.node == keywords::Invalid.name() {
  2634. self.tcx().types.err
  2635. } else if self.method_exists(field.span, field.node, expr_t, expr.id, true) {
  2636. self.type_error_struct(field.span, |actual| {
  2637. format!("attempted to take value of method `{}` on type \
  2638. `{}`", field.node, actual)
  2639. }, expr_t)
  2640. .help("maybe a `()` to call it is missing? \
  2641. If not, try an anonymous function")
  2642. .emit();
  2643. self.tcx().types.err
  2644. } else {
  2645. let mut err = self.type_error_struct(field.span, |actual| {
  2646. format!("no field `{}` on type `{}`",
  2647. field.node, actual)
  2648. }, expr_t);
  2649. match expr_t.sty {
  2650. ty::TyAdt(def, _) if !def.is_enum() => {
  2651. if let Some(suggested_field_name) =
  2652. Self::suggest_field_name(def.struct_variant(), field, vec![]) {
  2653. err.span_label(field.span,
  2654. format!("did you mean `{}`?", suggested_field_name));
  2655. } else {
  2656. err.span_label(field.span,
  2657. "unknown field");
  2658. };
  2659. }
  2660. ty::TyRawPtr(..) => {
  2661. err.note(&format!("`{0}` is a native pointer; perhaps you need to deref with \
  2662. `(*{0}).{1}`",
  2663. self.tcx.hir.node_to_pretty_string(base.id),
  2664. field.node));
  2665. }
  2666. _ => {}
  2667. }
  2668. err.emit();
  2669. self.tcx().types.err
  2670. }
  2671. }
  2672. // Return an hint about the closest match in field names
  2673. fn suggest_field_name(variant: &'tcx ty::VariantDef,
  2674. field: &Spanned<ast::Name>,
  2675. skip : Vec<InternedString>)
  2676. -> Option<Symbol> {
  2677. let name = field.node.as_str();
  2678. let names = variant.fields.iter().filter_map(|field| {
  2679. // ignore already set fields and private fields from non-local crates
  2680. if skip.iter().any(|x| *x == field.name.as_str()) ||
  2681. (variant.did.krate != LOCAL_CRATE && field.vis != Visibility::Public) {
  2682. None
  2683. } else {
  2684. Some(&field.name)
  2685. }
  2686. });
  2687. // only find fits with at least one matching letter
  2688. find_best_match_for_name(names, &name, Some(name.len()))
  2689. }
  2690. // Check tuple index expressions
  2691. fn check_tup_field(&self,
  2692. expr: &'gcx hir::Expr,
  2693. lvalue_pref: LvaluePreference,
  2694. base: &'gcx hir::Expr,
  2695. idx: codemap::Spanned<usize>) -> Ty<'tcx> {
  2696. let expr_t = self.check_expr_with_lvalue_pref(base, lvalue_pref);
  2697. let expr_t = self.structurally_resolved_type(expr.span,
  2698. expr_t);
  2699. let mut private_candidate = None;
  2700. let mut tuple_like = false;
  2701. let mut autoderef = self.autoderef(expr.span, expr_t);
  2702. while let Some((base_t, autoderefs)) = autoderef.next() {
  2703. let field = match base_t.sty {
  2704. ty::TyAdt(base_def, substs) if base_def.is_struct() => {
  2705. tuple_like = base_def.struct_variant().ctor_kind == CtorKind::Fn;
  2706. if !tuple_like { continue }
  2707. debug!("tuple struct named {:?}", base_t);
  2708. base_def.struct_variant().fields.get(idx.node).and_then(|field| {
  2709. let field_ty = self.field_ty(expr.span, field, substs);
  2710. private_candidate = Some((base_def.did, field_ty));
  2711. if self.tcx.vis_is_accessible_from(field.vis, self.body_id) {
  2712. self.tcx.check_stability(field.did, expr.id, expr.span);
  2713. Some(field_ty)
  2714. } else {
  2715. None
  2716. }
  2717. })
  2718. }
  2719. ty::TyTuple(ref v, _) => {
  2720. tuple_like = true;
  2721. v.get(idx.node).cloned()
  2722. }
  2723. _ => continue
  2724. };
  2725. if let Some(field_ty) = field {
  2726. autoderef.finalize(lvalue_pref, base);
  2727. self.apply_autoderef_adjustment(base.id, autoderefs, base_t);
  2728. return field_ty;
  2729. }
  2730. }
  2731. autoderef.unambiguous_final_ty();
  2732. if let Some((did, field_ty)) = private_candidate {
  2733. let struct_path = self.tcx().item_path_str(did);
  2734. let msg = format!("field `{}` of struct `{}` is private", idx.node, struct_path);
  2735. self.tcx().sess.span_err(expr.span, &msg);
  2736. return field_ty;
  2737. }
  2738. self.type_error_message(
  2739. expr.span,
  2740. |actual| {
  2741. if tuple_like {
  2742. format!("attempted out-of-bounds tuple index `{}` on \
  2743. type `{}`",
  2744. idx.node,
  2745. actual)
  2746. } else {
  2747. format!("attempted tuple index `{}` on type `{}`, but the \
  2748. type was not a tuple or tuple struct",
  2749. idx.node,
  2750. actual)
  2751. }
  2752. },
  2753. expr_t);
  2754. self.tcx().types.err
  2755. }
  2756. fn report_unknown_field(&self,
  2757. ty: Ty<'tcx>,
  2758. variant: &'tcx ty::VariantDef,
  2759. field: &hir::Field,
  2760. skip_fields: &[hir::Field],
  2761. kind_name: &str) {
  2762. let mut err = self.type_error_struct_with_diag(
  2763. field.name.span,
  2764. |actual| match ty.sty {
  2765. ty::TyAdt(adt, ..) if adt.is_enum() => {
  2766. struct_span_err!(self.tcx.sess, field.name.span, E0559,
  2767. "{} `{}::{}` has no field named `{}`",
  2768. kind_name, actual, variant.name, field.name.node)
  2769. }
  2770. _ => {
  2771. struct_span_err!(self.tcx.sess, field.name.span, E0560,
  2772. "{} `{}` has no field named `{}`",
  2773. kind_name, actual, field.name.node)
  2774. }
  2775. },
  2776. ty);
  2777. // prevent all specified fields from being suggested
  2778. let skip_fields = skip_fields.iter().map(|ref x| x.name.node.as_str());
  2779. if let Some(field_name) = Self::suggest_field_name(variant,
  2780. &field.name,
  2781. skip_fields.collect()) {
  2782. err.span_label(field.name.span,
  2783. format!("field does not exist - did you mean `{}`?", field_name));
  2784. } else {
  2785. match ty.sty {
  2786. ty::TyAdt(adt, ..) if adt.is_enum() => {
  2787. err.span_label(field.name.span, format!("`{}::{}` does not have this field",
  2788. ty, variant.name));
  2789. }
  2790. _ => {
  2791. err.span_label(field.name.span, format!("`{}` does not have this field", ty));
  2792. }
  2793. }
  2794. };
  2795. err.emit();
  2796. }
  2797. fn check_expr_struct_fields(&self,
  2798. adt_ty: Ty<'tcx>,
  2799. expected: Expectation<'tcx>,
  2800. expr_id: ast::NodeId,
  2801. span: Span,
  2802. variant: &'tcx ty::VariantDef,
  2803. ast_fields: &'gcx [hir::Field],
  2804. check_completeness: bool) {
  2805. let tcx = self.tcx;
  2806. let adt_ty_hint =
  2807. self.expected_inputs_for_expected_output(span, expected, adt_ty, &[adt_ty])
  2808. .get(0).cloned().unwrap_or(adt_ty);
  2809. let (substs, hint_substs, adt_kind, kind_name) = match (&adt_ty.sty, &adt_ty_hint.sty) {
  2810. (&ty::TyAdt(adt, substs), &ty::TyAdt(_, hint_substs)) => {
  2811. (substs, hint_substs, adt.adt_kind(), adt.variant_descr())
  2812. }
  2813. _ => span_bug!(span, "non-ADT passed to check_expr_struct_fields")
  2814. };
  2815. let mut remaining_fields = FxHashMap();
  2816. for field in &variant.fields {
  2817. remaining_fields.insert(field.name, field);
  2818. }
  2819. let mut seen_fields = FxHashMap();
  2820. let mut error_happened = false;
  2821. // Typecheck each field.
  2822. for field in ast_fields {
  2823. let final_field_type;
  2824. let field_type_hint;
  2825. if let Some(v_field) = remaining_fields.remove(&field.name.node) {
  2826. final_field_type = self.field_ty(field.span, v_field, substs);
  2827. field_type_hint = self.field_ty(field.span, v_field, hint_substs);
  2828. seen_fields.insert(field.name.node, field.span);
  2829. // we don't look at stability attributes on
  2830. // struct-like enums (yet...), but it's definitely not
  2831. // a bug to have construct one.
  2832. if adt_kind != ty::AdtKind::Enum {
  2833. tcx.check_stability(v_field.did, expr_id, field.span);
  2834. }
  2835. } else {
  2836. error_happened = true;
  2837. final_field_type = tcx.types.err;
  2838. field_type_hint = tcx.types.err;
  2839. if let Some(_) = variant.find_field_named(field.name.node) {
  2840. let mut err = struct_span_err!(self.tcx.sess,
  2841. field.name.span,
  2842. E0062,
  2843. "field `{}` specified more than once",
  2844. field.name.node);
  2845. err.span_label(field.name.span, "used more than once");
  2846. if let Some(prev_span) = seen_fields.get(&field.name.node) {
  2847. err.span_label(*prev_span, format!("first use of `{}`", field.name.node));
  2848. }
  2849. err.emit();
  2850. } else {
  2851. self.report_unknown_field(adt_ty, variant, field, ast_fields, kind_name);
  2852. }
  2853. }
  2854. // Make sure to give a type to the field even if there's
  2855. // an error, so we can continue typechecking
  2856. let ty = self.check_expr_with_hint(&field.expr, field_type_hint);
  2857. self.demand_coerce(&field.expr, ty, final_field_type);
  2858. }
  2859. // Make sure the programmer specified correct number of fields.
  2860. if kind_name == "union" {
  2861. if ast_fields.len() != 1 {
  2862. tcx.sess.span_err(span, "union expressions should have exactly one field");
  2863. }
  2864. } else if check_completeness && !error_happened && !remaining_fields.is_empty() {
  2865. let len = remaining_fields.len();
  2866. let mut displayable_field_names = remaining_fields
  2867. .keys()
  2868. .map(|x| x.as_str())
  2869. .collect::<Vec<_>>();
  2870. displayable_field_names.sort();
  2871. let truncated_fields_error = if len <= 3 {
  2872. "".to_string()
  2873. } else {
  2874. format!(" and {} other field{}", (len - 3), if len - 3 == 1 {""} else {"s"})
  2875. };
  2876. let remaining_fields_names = displayable_field_names.iter().take(3)
  2877. .map(|n| format!("`{}`", n))
  2878. .collect::<Vec<_>>()
  2879. .join(", ");
  2880. struct_span_err!(tcx.sess, span, E0063,
  2881. "missing field{} {}{} in initializer of `{}`",
  2882. if remaining_fields.len() == 1 {""} else {"s"},
  2883. remaining_fields_names,
  2884. truncated_fields_error,
  2885. adt_ty)
  2886. .span_label(span, format!("missing {}{}",
  2887. remaining_fields_names,
  2888. truncated_fields_error))
  2889. .emit();
  2890. }
  2891. }
  2892. fn check_struct_fields_on_error(&self,
  2893. fields: &'gcx [hir::Field],
  2894. base_expr: &'gcx Option<P<hir::Expr>>) {
  2895. for field in fields {
  2896. self.check_expr(&field.expr);
  2897. }
  2898. match *base_expr {
  2899. Some(ref base) => {
  2900. self.check_expr(&base);
  2901. },
  2902. None => {}
  2903. }
  2904. }
  2905. pub fn check_struct_path(&self,
  2906. qpath: &hir::QPath,
  2907. node_id: ast::NodeId)
  2908. -> Option<(&'tcx ty::VariantDef, Ty<'tcx>)> {
  2909. let path_span = match *qpath {
  2910. hir::QPath::Resolved(_, ref path) => path.span,
  2911. hir::QPath::TypeRelative(ref qself, _) => qself.span
  2912. };
  2913. let (def, ty) = self.finish_resolving_struct_path(qpath, path_span, node_id);
  2914. let variant = match def {
  2915. Def::Err => {
  2916. self.set_tainted_by_errors();
  2917. return None;
  2918. }
  2919. Def::Variant(..) => {
  2920. match ty.sty {
  2921. ty::TyAdt(adt, substs) => {
  2922. Some((adt.variant_of_def(def), adt.did, substs))
  2923. }
  2924. _ => bug!("unexpected type: {:?}", ty.sty)
  2925. }
  2926. }
  2927. Def::Struct(..) | Def::Union(..) | Def::TyAlias(..) |
  2928. Def::AssociatedTy(..) | Def::SelfTy(..) => {
  2929. match ty.sty {
  2930. ty::TyAdt(adt, substs) if !adt.is_enum() => {
  2931. Some((adt.struct_variant(), adt.did, substs))
  2932. }
  2933. _ => None,
  2934. }
  2935. }
  2936. _ => bug!("unexpected definition: {:?}", def)
  2937. };
  2938. if let Some((variant, did, substs)) = variant {
  2939. // Check bounds on type arguments used in the path.
  2940. let bounds = self.instantiate_bounds(path_span, did, substs);
  2941. let cause = traits::ObligationCause::new(path_span, self.body_id,
  2942. traits::ItemObligation(did));
  2943. self.add_obligations_for_parameters(cause, &bounds);
  2944. Some((variant, ty))
  2945. } else {
  2946. struct_span_err!(self.tcx.sess, path_span, E0071,
  2947. "expected struct, variant or union type, found {}",
  2948. ty.sort_string(self.tcx))
  2949. .span_label(path_span, "not a struct")
  2950. .emit();
  2951. None
  2952. }
  2953. }
  2954. fn check_expr_struct(&self,
  2955. expr: &hir::Expr,
  2956. expected: Expectation<'tcx>,
  2957. qpath: &hir::QPath,
  2958. fields: &'gcx [hir::Field],
  2959. base_expr: &'gcx Option<P<hir::Expr>>) -> Ty<'tcx>
  2960. {
  2961. // Find the relevant variant
  2962. let (variant, struct_ty) =
  2963. if let Some(variant_ty) = self.check_struct_path(qpath, expr.id) {
  2964. variant_ty
  2965. } else {
  2966. self.check_struct_fields_on_error(fields, base_expr);
  2967. return self.tcx.types.err;
  2968. };
  2969. let path_span = match *qpath {
  2970. hir::QPath::Resolved(_, ref path) => path.span,
  2971. hir::QPath::TypeRelative(ref qself, _) => qself.span
  2972. };
  2973. self.check_expr_struct_fields(struct_ty, expected, expr.id, path_span, variant, fields,
  2974. base_expr.is_none());
  2975. if let &Some(ref base_expr) = base_expr {
  2976. self.check_expr_has_type(base_expr, struct_ty);
  2977. match struct_ty.sty {
  2978. ty::TyAdt(adt, substs) if adt.is_struct() => {
  2979. self.tables.borrow_mut().fru_field_types.insert(
  2980. expr.id,
  2981. adt.struct_variant().fields.iter().map(|f| {
  2982. self.normalize_associated_types_in(
  2983. expr.span, &f.ty(self.tcx, substs)
  2984. )
  2985. }).collect()
  2986. );
  2987. }
  2988. _ => {
  2989. span_err!(self.tcx.sess, base_expr.span, E0436,
  2990. "functional record update syntax requires a struct");
  2991. }
  2992. }
  2993. }
  2994. self.require_type_is_sized(struct_ty, expr.span, traits::StructInitializerSized);
  2995. struct_ty
  2996. }
  2997. /// Invariant:
  2998. /// If an expression has any sub-expressions that result in a type error,
  2999. /// inspecting that expression's type with `ty.references_error()` will return
  3000. /// true. Likewise, if an expression is known to diverge, inspecting its
  3001. /// type with `ty::type_is_bot` will return true (n.b.: since Rust is
  3002. /// strict, _|_ can appear in the type of an expression that does not,
  3003. /// itself, diverge: for example, fn() -> _|_.)
  3004. /// Note that inspecting a type's structure *directly* may expose the fact
  3005. /// that there are actually multiple representations for `TyError`, so avoid
  3006. /// that when err needs to be handled differently.
  3007. fn check_expr_with_expectation_and_lvalue_pref(&self,
  3008. expr: &'gcx hir::Expr,
  3009. expected: Expectation<'tcx>,
  3010. lvalue_pref: LvaluePreference) -> Ty<'tcx> {
  3011. debug!(">> typechecking: expr={:?} expected={:?}",
  3012. expr, expected);
  3013. // Warn for expressions after diverging siblings.
  3014. self.warn_if_unreachable(expr.id, expr.span, "expression");
  3015. // Hide the outer diverging and has_errors flags.
  3016. let old_diverges = self.diverges.get();
  3017. let old_has_errors = self.has_errors.get();
  3018. self.diverges.set(Diverges::Maybe);
  3019. self.has_errors.set(false);
  3020. let ty = self.check_expr_kind(expr, expected, lvalue_pref);
  3021. // Warn for non-block expressions with diverging children.
  3022. match expr.node {
  3023. hir::ExprBlock(_) |
  3024. hir::ExprLoop(..) | hir::ExprWhile(..) |
  3025. hir::ExprIf(..) | hir::ExprMatch(..) => {}
  3026. _ => self.warn_if_unreachable(expr.id, expr.span, "expression")
  3027. }
  3028. // Any expression that produces a value of type `!` must have diverged
  3029. if ty.is_never() {
  3030. self.diverges.set(self.diverges.get() | Diverges::Always);
  3031. }
  3032. // Record the type, which applies it effects.
  3033. // We need to do this after the warning above, so that
  3034. // we don't warn for the diverging expression itself.
  3035. self.write_ty(expr.id, ty);
  3036. // Combine the diverging and has_error flags.
  3037. self.diverges.set(self.diverges.get() | old_diverges);
  3038. self.has_errors.set(self.has_errors.get() | old_has_errors);
  3039. debug!("type of {} is...", self.tcx.hir.node_to_string(expr.id));
  3040. debug!("... {:?}, expected is {:?}", ty, expected);
  3041. ty
  3042. }
  3043. fn check_expr_kind(&self,
  3044. expr: &'gcx hir::Expr,
  3045. expected: Expectation<'tcx>,
  3046. lvalue_pref: LvaluePreference) -> Ty<'tcx> {
  3047. let tcx = self.tcx;
  3048. let id = expr.id;
  3049. match expr.node {
  3050. hir::ExprBox(ref subexpr) => {
  3051. let expected_inner = expected.to_option(self).map_or(NoExpectation, |ty| {
  3052. match ty.sty {
  3053. ty::TyAdt(def, _) if def.is_box()
  3054. => Expectation::rvalue_hint(self, ty.boxed_ty()),
  3055. _ => NoExpectation
  3056. }
  3057. });
  3058. let referent_ty = self.check_expr_with_expectation(subexpr, expected_inner);
  3059. tcx.mk_box(referent_ty)
  3060. }
  3061. hir::ExprLit(ref lit) => {
  3062. self.check_lit(&lit, expected)
  3063. }
  3064. hir::ExprBinary(op, ref lhs, ref rhs) => {
  3065. self.check_binop(expr, op, lhs, rhs)
  3066. }
  3067. hir::ExprAssignOp(op, ref lhs, ref rhs) => {
  3068. self.check_binop_assign(expr, op, lhs, rhs)
  3069. }
  3070. hir::ExprUnary(unop, ref oprnd) => {
  3071. let expected_inner = match unop {
  3072. hir::UnNot | hir::UnNeg => {
  3073. expected
  3074. }
  3075. hir::UnDeref => {
  3076. NoExpectation
  3077. }
  3078. };
  3079. let lvalue_pref = match unop {
  3080. hir::UnDeref => lvalue_pref,
  3081. _ => NoPreference
  3082. };
  3083. let mut oprnd_t = self.check_expr_with_expectation_and_lvalue_pref(&oprnd,
  3084. expected_inner,
  3085. lvalue_pref);
  3086. if !oprnd_t.references_error() {
  3087. match unop {
  3088. hir::UnDeref => {
  3089. oprnd_t = self.structurally_resolved_type(expr.span, oprnd_t);
  3090. if let Some(mt) = oprnd_t.builtin_deref(true, NoPreference) {
  3091. oprnd_t = mt.ty;
  3092. } else if let Some(ok) = self.try_overloaded_deref(
  3093. expr.span, Some(&oprnd), oprnd_t, lvalue_pref) {
  3094. let method = self.register_infer_ok_obligations(ok);
  3095. oprnd_t = self.make_overloaded_lvalue_return_type(method).ty;
  3096. self.tables.borrow_mut().method_map.insert(MethodCall::expr(expr.id),
  3097. method);
  3098. } else {
  3099. self.type_error_message(expr.span, |actual| {
  3100. format!("type `{}` cannot be \
  3101. dereferenced", actual)
  3102. }, oprnd_t);
  3103. oprnd_t = tcx.types.err;
  3104. }
  3105. }
  3106. hir::UnNot => {
  3107. oprnd_t = self.structurally_resolved_type(oprnd.span,
  3108. oprnd_t);
  3109. let result = self.check_user_unop("!", "not",
  3110. tcx.lang_items.not_trait(),
  3111. expr, &oprnd, oprnd_t, unop);
  3112. // If it's builtin, we can reuse the type, this helps inference.
  3113. if !(oprnd_t.is_integral() || oprnd_t.sty == ty::TyBool) {
  3114. oprnd_t = result;
  3115. }
  3116. }
  3117. hir::UnNeg => {
  3118. oprnd_t = self.structurally_resolved_type(oprnd.span,
  3119. oprnd_t);
  3120. let result = self.check_user_unop("-", "neg",
  3121. tcx.lang_items.neg_trait(),
  3122. expr, &oprnd, oprnd_t, unop);
  3123. // If it's builtin, we can reuse the type, this helps inference.
  3124. if !(oprnd_t.is_integral() || oprnd_t.is_fp()) {
  3125. oprnd_t = result;
  3126. }
  3127. }
  3128. }
  3129. }
  3130. oprnd_t
  3131. }
  3132. hir::ExprAddrOf(mutbl, ref oprnd) => {
  3133. let hint = expected.only_has_type(self).map_or(NoExpectation, |ty| {
  3134. match ty.sty {
  3135. ty::TyRef(_, ref mt) | ty::TyRawPtr(ref mt) => {
  3136. if self.tcx.expr_is_lval(&oprnd) {
  3137. // Lvalues may legitimately have unsized types.
  3138. // For example, dereferences of a fat pointer and
  3139. // the last field of a struct can be unsized.
  3140. ExpectHasType(mt.ty)
  3141. } else {
  3142. Expectation::rvalue_hint(self, mt.ty)
  3143. }
  3144. }
  3145. _ => NoExpectation
  3146. }
  3147. });
  3148. let lvalue_pref = LvaluePreference::from_mutbl(mutbl);
  3149. let ty = self.check_expr_with_expectation_and_lvalue_pref(&oprnd, hint, lvalue_pref);
  3150. let tm = ty::TypeAndMut { ty: ty, mutbl: mutbl };
  3151. if tm.ty.references_error() {
  3152. tcx.types.err
  3153. } else {
  3154. // Note: at this point, we cannot say what the best lifetime
  3155. // is to use for resulting pointer. We want to use the
  3156. // shortest lifetime possible so as to avoid spurious borrowck
  3157. // errors. Moreover, the longest lifetime will depend on the
  3158. // precise details of the value whose address is being taken
  3159. // (and how long it is valid), which we don't know yet until type
  3160. // inference is complete.
  3161. //
  3162. // Therefore, here we simply generate a region variable. The
  3163. // region inferencer will then select the ultimate value.
  3164. // Finally, borrowck is charged with guaranteeing that the
  3165. // value whose address was taken can actually be made to live
  3166. // as long as it needs to live.
  3167. let region = self.next_region_var(infer::AddrOfRegion(expr.span));
  3168. tcx.mk_ref(region, tm)
  3169. }
  3170. }
  3171. hir::ExprPath(ref qpath) => {
  3172. let (def, opt_ty, segments) = self.resolve_ty_and_def_ufcs(qpath,
  3173. expr.id, expr.span);
  3174. let ty = if def != Def::Err {
  3175. self.instantiate_value_path(segments, opt_ty, def, expr.span, id)
  3176. } else {
  3177. self.set_tainted_by_errors();
  3178. tcx.types.err
  3179. };
  3180. // We always require that the type provided as the value for
  3181. // a type parameter outlives the moment of instantiation.
  3182. self.opt_node_ty_substs(expr.id, |item_substs| {
  3183. self.add_wf_bounds(&item_substs.substs, expr);
  3184. });
  3185. ty
  3186. }
  3187. hir::ExprInlineAsm(_, ref outputs, ref inputs) => {
  3188. for output in outputs {
  3189. self.check_expr(output);
  3190. }
  3191. for input in inputs {
  3192. self.check_expr(input);
  3193. }
  3194. tcx.mk_nil()
  3195. }
  3196. hir::ExprBreak(destination, ref expr_opt) => {
  3197. if let Some(target_id) = destination.target_id.opt_id() {
  3198. let (e_ty, e_diverges, cause);
  3199. if let Some(ref e) = *expr_opt {
  3200. // If this is a break with a value, we need to type-check
  3201. // the expression. Get an expected type from the loop context.
  3202. let opt_coerce_to = {
  3203. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
  3204. enclosing_breakables.find_breakable(target_id)
  3205. .coerce
  3206. .as_ref()
  3207. .map(|coerce| coerce.expected_ty())
  3208. };
  3209. // If the loop context is not a `loop { }`, then break with
  3210. // a value is illegal, and `opt_coerce_to` will be `None`.
  3211. // Just set expectation to error in that case.
  3212. let coerce_to = opt_coerce_to.unwrap_or(tcx.types.err);
  3213. // Recurse without `enclosing_breakables` borrowed.
  3214. e_ty = self.check_expr_with_hint(e, coerce_to);
  3215. e_diverges = self.diverges.get();
  3216. cause = self.misc(e.span);
  3217. } else {
  3218. // Otherwise, this is a break *without* a value. That's
  3219. // always legal, and is equivalent to `break ()`.
  3220. e_ty = tcx.mk_nil();
  3221. e_diverges = Diverges::Maybe;
  3222. cause = self.misc(expr.span);
  3223. }
  3224. // Now that we have type-checked `expr_opt`, borrow
  3225. // the `enclosing_loops` field and let's coerce the
  3226. // type of `expr_opt` into what is expected.
  3227. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
  3228. let ctxt = enclosing_breakables.find_breakable(target_id);
  3229. if let Some(ref mut coerce) = ctxt.coerce {
  3230. if let Some(ref e) = *expr_opt {
  3231. coerce.coerce(self, &cause, e, e_ty, e_diverges);
  3232. } else {
  3233. assert!(e_ty.is_nil());
  3234. coerce.coerce_forced_unit(self, &cause, &mut |_| (), true);
  3235. }
  3236. } else {
  3237. // If `ctxt.coerce` is `None`, we can just ignore
  3238. // the type of the expresison. This is because
  3239. // either this was a break *without* a value, in
  3240. // which case it is always a legal type (`()`), or
  3241. // else an error would have been flagged by the
  3242. // `loops` pass for using break with an expression
  3243. // where you are not supposed to.
  3244. assert!(expr_opt.is_none() || self.tcx.sess.err_count() > 0);
  3245. }
  3246. ctxt.may_break = true;
  3247. } else {
  3248. // Otherwise, we failed to find the enclosing loop;
  3249. // this can only happen if the `break` was not
  3250. // inside a loop at all, which is caught by the
  3251. // loop-checking pass.
  3252. assert!(self.tcx.sess.err_count() > 0);
  3253. }
  3254. // the type of a `break` is always `!`, since it diverges
  3255. tcx.types.never
  3256. }
  3257. hir::ExprAgain(_) => { tcx.types.never }
  3258. hir::ExprRet(ref expr_opt) => {
  3259. if self.ret_coercion.is_none() {
  3260. struct_span_err!(self.tcx.sess, expr.span, E0572,
  3261. "return statement outside of function body").emit();
  3262. } else if let Some(ref e) = *expr_opt {
  3263. self.check_return_expr(e);
  3264. } else {
  3265. let mut coercion = self.ret_coercion.as_ref().unwrap().borrow_mut();
  3266. let cause = self.cause(expr.span, ObligationCauseCode::ReturnNoExpression);
  3267. coercion.coerce_forced_unit(self, &cause, &mut |_| (), true);
  3268. }
  3269. tcx.types.never
  3270. }
  3271. hir::ExprAssign(ref lhs, ref rhs) => {
  3272. let lhs_ty = self.check_expr_with_lvalue_pref(&lhs, PreferMutLvalue);
  3273. let tcx = self.tcx;
  3274. if !tcx.expr_is_lval(&lhs) {
  3275. struct_span_err!(
  3276. tcx.sess, expr.span, E0070,
  3277. "invalid left-hand side expression")
  3278. .span_label(
  3279. expr.span,
  3280. "left-hand of expression not valid")
  3281. .emit();
  3282. }
  3283. let rhs_ty = self.check_expr_coercable_to_type(&rhs, lhs_ty);
  3284. self.require_type_is_sized(lhs_ty, lhs.span, traits::AssignmentLhsSized);
  3285. if lhs_ty.references_error() || rhs_ty.references_error() {
  3286. tcx.types.err
  3287. } else {
  3288. tcx.mk_nil()
  3289. }
  3290. }
  3291. hir::ExprIf(ref cond, ref then_expr, ref opt_else_expr) => {
  3292. self.check_then_else(&cond, then_expr, opt_else_expr.as_ref().map(|e| &**e),
  3293. expr.span, expected)
  3294. }
  3295. hir::ExprWhile(ref cond, ref body, _) => {
  3296. let ctxt = BreakableCtxt {
  3297. // cannot use break with a value from a while loop
  3298. coerce: None,
  3299. may_break: true,
  3300. };
  3301. self.with_breakable_ctxt(expr.id, ctxt, || {
  3302. self.check_expr_has_type(&cond, tcx.types.bool);
  3303. let cond_diverging = self.diverges.get();
  3304. self.check_block_no_value(&body);
  3305. // We may never reach the body so it diverging means nothing.
  3306. self.diverges.set(cond_diverging);
  3307. });
  3308. self.tcx.mk_nil()
  3309. }
  3310. hir::ExprLoop(ref body, _, source) => {
  3311. let coerce = match source {
  3312. // you can only use break with a value from a normal `loop { }`
  3313. hir::LoopSource::Loop => {
  3314. let coerce_to = expected.coercion_target_type(self, body.span);
  3315. Some(CoerceMany::new(coerce_to))
  3316. }
  3317. hir::LoopSource::WhileLet |
  3318. hir::LoopSource::ForLoop => {
  3319. None
  3320. }
  3321. };
  3322. let ctxt = BreakableCtxt {
  3323. coerce: coerce,
  3324. may_break: false, // will get updated if/when we find a `break`
  3325. };
  3326. let (ctxt, ()) = self.with_breakable_ctxt(expr.id, ctxt, || {
  3327. self.check_block_no_value(&body);
  3328. });
  3329. if ctxt.may_break {
  3330. // No way to know whether it's diverging because
  3331. // of a `break` or an outer `break` or `return.
  3332. self.diverges.set(Diverges::Maybe);
  3333. }
  3334. // If we permit break with a value, then result type is
  3335. // the LUB of the breaks (possibly ! if none); else, it
  3336. // is nil. This makes sense because infinite loops
  3337. // (which would have type !) are only possible iff we
  3338. // permit break with a value [1].
  3339. assert!(ctxt.coerce.is_some() || ctxt.may_break); // [1]
  3340. ctxt.coerce.map(|c| c.complete(self)).unwrap_or(self.tcx.mk_nil())
  3341. }
  3342. hir::ExprMatch(ref discrim, ref arms, match_src) => {
  3343. self.check_match(expr, &discrim, arms, expected, match_src)
  3344. }
  3345. hir::ExprClosure(capture, ref decl, body_id, _) => {
  3346. self.check_expr_closure(expr, capture, &decl, body_id, expected)
  3347. }
  3348. hir::ExprBlock(ref body) => {
  3349. self.check_block_with_expected(&body, expected)
  3350. }
  3351. hir::ExprCall(ref callee, ref args) => {
  3352. self.check_call(expr, &callee, args, expected)
  3353. }
  3354. hir::ExprMethodCall(name, ref tps, ref args) => {
  3355. self.check_method_call(expr, name, args, &tps[..], expected, lvalue_pref)
  3356. }
  3357. hir::ExprCast(ref e, ref t) => {
  3358. // Find the type of `e`. Supply hints based on the type we are casting to,
  3359. // if appropriate.
  3360. let t_cast = self.to_ty(t);
  3361. let t_cast = self.resolve_type_vars_if_possible(&t_cast);
  3362. let t_expr = self.check_expr_with_expectation(e, ExpectCastableToType(t_cast));
  3363. let t_cast = self.resolve_type_vars_if_possible(&t_cast);
  3364. let diverges = self.diverges.get();
  3365. // Eagerly check for some obvious errors.
  3366. if t_expr.references_error() || t_cast.references_error() {
  3367. tcx.types.err
  3368. } else {
  3369. // Defer other checks until we're done type checking.
  3370. let mut deferred_cast_checks = self.deferred_cast_checks.borrow_mut();
  3371. match cast::CastCheck::new(self, e, t_expr, diverges, t_cast, t.span, expr.span) {
  3372. Ok(cast_check) => {
  3373. deferred_cast_checks.push(cast_check);
  3374. t_cast
  3375. }
  3376. Err(ErrorReported) => {
  3377. tcx.types.err
  3378. }
  3379. }
  3380. }
  3381. }
  3382. hir::ExprType(ref e, ref t) => {
  3383. let typ = self.to_ty(&t);
  3384. self.check_expr_eq_type(&e, typ);
  3385. typ
  3386. }
  3387. hir::ExprArray(ref args) => {
  3388. let uty = expected.to_option(self).and_then(|uty| {
  3389. match uty.sty {
  3390. ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
  3391. _ => None
  3392. }
  3393. });
  3394. let element_ty = if !args.is_empty() {
  3395. let coerce_to = uty.unwrap_or_else(
  3396. || self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span)));
  3397. let mut coerce = CoerceMany::with_coercion_sites(coerce_to, args);
  3398. assert_eq!(self.diverges.get(), Diverges::Maybe);
  3399. for e in args {
  3400. let e_ty = self.check_expr_with_hint(e, coerce_to);
  3401. let cause = self.misc(e.span);
  3402. coerce.coerce(self, &cause, e, e_ty, self.diverges.get());
  3403. }
  3404. coerce.complete(self)
  3405. } else {
  3406. self.next_ty_var(TypeVariableOrigin::TypeInference(expr.span))
  3407. };
  3408. tcx.mk_array(element_ty, args.len())
  3409. }
  3410. hir::ExprRepeat(ref element, count) => {
  3411. let count = eval_length(self.tcx, count, "repeat count")
  3412. .unwrap_or(0);
  3413. let uty = match expected {
  3414. ExpectHasType(uty) => {
  3415. match uty.sty {
  3416. ty::TyArray(ty, _) | ty::TySlice(ty) => Some(ty),
  3417. _ => None
  3418. }
  3419. }
  3420. _ => None
  3421. };
  3422. let (element_ty, t) = match uty {
  3423. Some(uty) => {
  3424. self.check_expr_coercable_to_type(&element, uty);
  3425. (uty, uty)
  3426. }
  3427. None => {
  3428. let t: Ty = self.next_ty_var(TypeVariableOrigin::MiscVariable(element.span));
  3429. let element_ty = self.check_expr_has_type(&element, t);
  3430. (element_ty, t)
  3431. }
  3432. };
  3433. if count > 1 {
  3434. // For [foo, ..n] where n > 1, `foo` must have
  3435. // Copy type:
  3436. let lang_item = self.tcx.require_lang_item(lang_items::CopyTraitLangItem);
  3437. self.require_type_meets(t, expr.span, traits::RepeatVec, lang_item);
  3438. }
  3439. if element_ty.references_error() {
  3440. tcx.types.err
  3441. } else {
  3442. tcx.mk_array(t, count)
  3443. }
  3444. }
  3445. hir::ExprTup(ref elts) => {
  3446. let flds = expected.only_has_type(self).and_then(|ty| {
  3447. match ty.sty {
  3448. ty::TyTuple(ref flds, _) => Some(&flds[..]),
  3449. _ => None
  3450. }
  3451. });
  3452. let elt_ts_iter = elts.iter().enumerate().map(|(i, e)| {
  3453. let t = match flds {
  3454. Some(ref fs) if i < fs.len() => {
  3455. let ety = fs[i];
  3456. self.check_expr_coercable_to_type(&e, ety);
  3457. ety
  3458. }
  3459. _ => {
  3460. self.check_expr_with_expectation(&e, NoExpectation)
  3461. }
  3462. };
  3463. t
  3464. });
  3465. let tuple = tcx.mk_tup(elt_ts_iter, false);
  3466. if tuple.references_error() {
  3467. tcx.types.err
  3468. } else {
  3469. tuple
  3470. }
  3471. }
  3472. hir::ExprStruct(ref qpath, ref fields, ref base_expr) => {
  3473. self.check_expr_struct(expr, expected, qpath, fields, base_expr)
  3474. }
  3475. hir::ExprField(ref base, ref field) => {
  3476. self.check_field(expr, lvalue_pref, &base, field)
  3477. }
  3478. hir::ExprTupField(ref base, idx) => {
  3479. self.check_tup_field(expr, lvalue_pref, &base, idx)
  3480. }
  3481. hir::ExprIndex(ref base, ref idx) => {
  3482. let base_t = self.check_expr_with_lvalue_pref(&base, lvalue_pref);
  3483. let idx_t = self.check_expr(&idx);
  3484. if base_t.references_error() {
  3485. base_t
  3486. } else if idx_t.references_error() {
  3487. idx_t
  3488. } else {
  3489. let base_t = self.structurally_resolved_type(expr.span, base_t);
  3490. match self.lookup_indexing(expr, base, base_t, idx_t, lvalue_pref) {
  3491. Some((index_ty, element_ty)) => {
  3492. self.demand_coerce(idx, idx_t, index_ty);
  3493. element_ty
  3494. }
  3495. None => {
  3496. let mut err = self.type_error_struct(
  3497. expr.span,
  3498. |actual| {
  3499. format!("cannot index a value of type `{}`",
  3500. actual)
  3501. },
  3502. base_t);
  3503. // Try to give some advice about indexing tuples.
  3504. if let ty::TyTuple(..) = base_t.sty {
  3505. let mut needs_note = true;
  3506. // If the index is an integer, we can show the actual
  3507. // fixed expression:
  3508. if let hir::ExprLit(ref lit) = idx.node {
  3509. if let ast::LitKind::Int(i,
  3510. ast::LitIntType::Unsuffixed) = lit.node {
  3511. let snip = tcx.sess.codemap().span_to_snippet(base.span);
  3512. if let Ok(snip) = snip {
  3513. err.span_suggestion(expr.span,
  3514. "to access tuple elements, use",
  3515. format!("{}.{}", snip, i));
  3516. needs_note = false;
  3517. }
  3518. }
  3519. }
  3520. if needs_note {
  3521. err.help("to access tuple elements, use tuple indexing \
  3522. syntax (e.g. `tuple.0`)");
  3523. }
  3524. }
  3525. err.emit();
  3526. self.tcx.types.err
  3527. }
  3528. }
  3529. }
  3530. }
  3531. }
  3532. }
  3533. // Finish resolving a path in a struct expression or pattern `S::A { .. }` if necessary.
  3534. // The newly resolved definition is written into `type_relative_path_defs`.
  3535. fn finish_resolving_struct_path(&self,
  3536. qpath: &hir::QPath,
  3537. path_span: Span,
  3538. node_id: ast::NodeId)
  3539. -> (Def, Ty<'tcx>)
  3540. {
  3541. match *qpath {
  3542. hir::QPath::Resolved(ref maybe_qself, ref path) => {
  3543. let opt_self_ty = maybe_qself.as_ref().map(|qself| self.to_ty(qself));
  3544. let ty = AstConv::def_to_ty(self, opt_self_ty, path, true);
  3545. (path.def, ty)
  3546. }
  3547. hir::QPath::TypeRelative(ref qself, ref segment) => {
  3548. let ty = self.to_ty(qself);
  3549. let def = if let hir::TyPath(hir::QPath::Resolved(_, ref path)) = qself.node {
  3550. path.def
  3551. } else {
  3552. Def::Err
  3553. };
  3554. let (ty, def) = AstConv::associated_path_def_to_ty(self, node_id, path_span,
  3555. ty, def, segment);
  3556. // Write back the new resolution.
  3557. self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
  3558. (def, ty)
  3559. }
  3560. }
  3561. }
  3562. // Resolve associated value path into a base type and associated constant or method definition.
  3563. // The newly resolved definition is written into `type_relative_path_defs`.
  3564. pub fn resolve_ty_and_def_ufcs<'b>(&self,
  3565. qpath: &'b hir::QPath,
  3566. node_id: ast::NodeId,
  3567. span: Span)
  3568. -> (Def, Option<Ty<'tcx>>, &'b [hir::PathSegment])
  3569. {
  3570. let (ty, item_segment) = match *qpath {
  3571. hir::QPath::Resolved(ref opt_qself, ref path) => {
  3572. return (path.def,
  3573. opt_qself.as_ref().map(|qself| self.to_ty(qself)),
  3574. &path.segments[..]);
  3575. }
  3576. hir::QPath::TypeRelative(ref qself, ref segment) => {
  3577. (self.to_ty(qself), segment)
  3578. }
  3579. };
  3580. let item_name = item_segment.name;
  3581. let def = match self.resolve_ufcs(span, item_name, ty, node_id) {
  3582. Ok(def) => def,
  3583. Err(error) => {
  3584. let def = match error {
  3585. method::MethodError::PrivateMatch(def) => def,
  3586. _ => Def::Err,
  3587. };
  3588. if item_name != keywords::Invalid.name() {
  3589. self.report_method_error(span, ty, item_name, None, error, None);
  3590. }
  3591. def
  3592. }
  3593. };
  3594. // Write back the new resolution.
  3595. self.tables.borrow_mut().type_relative_path_defs.insert(node_id, def);
  3596. (def, Some(ty), slice::ref_slice(&**item_segment))
  3597. }
  3598. pub fn check_decl_initializer(&self,
  3599. local: &'gcx hir::Local,
  3600. init: &'gcx hir::Expr) -> Ty<'tcx>
  3601. {
  3602. let ref_bindings = local.pat.contains_ref_binding();
  3603. let local_ty = self.local_ty(init.span, local.id);
  3604. if let Some(m) = ref_bindings {
  3605. // Somewhat subtle: if we have a `ref` binding in the pattern,
  3606. // we want to avoid introducing coercions for the RHS. This is
  3607. // both because it helps preserve sanity and, in the case of
  3608. // ref mut, for soundness (issue #23116). In particular, in
  3609. // the latter case, we need to be clear that the type of the
  3610. // referent for the reference that results is *equal to* the
  3611. // type of the lvalue it is referencing, and not some
  3612. // supertype thereof.
  3613. let init_ty = self.check_expr_with_lvalue_pref(init, LvaluePreference::from_mutbl(m));
  3614. self.demand_eqtype(init.span, init_ty, local_ty);
  3615. init_ty
  3616. } else {
  3617. self.check_expr_coercable_to_type(init, local_ty)
  3618. }
  3619. }
  3620. pub fn check_decl_local(&self, local: &'gcx hir::Local) {
  3621. let t = self.local_ty(local.span, local.id);
  3622. self.write_ty(local.id, t);
  3623. if let Some(ref init) = local.init {
  3624. let init_ty = self.check_decl_initializer(local, &init);
  3625. if init_ty.references_error() {
  3626. self.write_ty(local.id, init_ty);
  3627. }
  3628. }
  3629. self.check_pat(&local.pat, t);
  3630. let pat_ty = self.node_ty(local.pat.id);
  3631. if pat_ty.references_error() {
  3632. self.write_ty(local.id, pat_ty);
  3633. }
  3634. }
  3635. pub fn check_stmt(&self, stmt: &'gcx hir::Stmt) {
  3636. // Don't do all the complex logic below for DeclItem.
  3637. match stmt.node {
  3638. hir::StmtDecl(ref decl, id) => {
  3639. match decl.node {
  3640. hir::DeclLocal(_) => {}
  3641. hir::DeclItem(_) => {
  3642. self.write_nil(id);
  3643. return;
  3644. }
  3645. }
  3646. }
  3647. hir::StmtExpr(..) | hir::StmtSemi(..) => {}
  3648. }
  3649. self.warn_if_unreachable(stmt.node.id(), stmt.span, "statement");
  3650. // Hide the outer diverging and has_errors flags.
  3651. let old_diverges = self.diverges.get();
  3652. let old_has_errors = self.has_errors.get();
  3653. self.diverges.set(Diverges::Maybe);
  3654. self.has_errors.set(false);
  3655. let (node_id, _span) = match stmt.node {
  3656. hir::StmtDecl(ref decl, id) => {
  3657. let span = match decl.node {
  3658. hir::DeclLocal(ref l) => {
  3659. self.check_decl_local(&l);
  3660. l.span
  3661. }
  3662. hir::DeclItem(_) => {/* ignore for now */
  3663. DUMMY_SP
  3664. }
  3665. };
  3666. (id, span)
  3667. }
  3668. hir::StmtExpr(ref expr, id) => {
  3669. // Check with expected type of ()
  3670. self.check_expr_has_type(&expr, self.tcx.mk_nil());
  3671. (id, expr.span)
  3672. }
  3673. hir::StmtSemi(ref expr, id) => {
  3674. self.check_expr(&expr);
  3675. (id, expr.span)
  3676. }
  3677. };
  3678. if self.has_errors.get() {
  3679. self.write_error(node_id);
  3680. } else {
  3681. self.write_nil(node_id);
  3682. }
  3683. // Combine the diverging and has_error flags.
  3684. self.diverges.set(self.diverges.get() | old_diverges);
  3685. self.has_errors.set(self.has_errors.get() | old_has_errors);
  3686. }
  3687. pub fn check_block_no_value(&self, blk: &'gcx hir::Block) {
  3688. let unit = self.tcx.mk_nil();
  3689. let ty = self.check_block_with_expected(blk, ExpectHasType(unit));
  3690. // if the block produces a `!` value, that can always be
  3691. // (effectively) coerced to unit.
  3692. if !ty.is_never() {
  3693. self.demand_suptype(blk.span, unit, ty);
  3694. }
  3695. }
  3696. fn check_block_with_expected(&self,
  3697. blk: &'gcx hir::Block,
  3698. expected: Expectation<'tcx>) -> Ty<'tcx> {
  3699. let prev = {
  3700. let mut fcx_ps = self.ps.borrow_mut();
  3701. let unsafety_state = fcx_ps.recurse(blk);
  3702. replace(&mut *fcx_ps, unsafety_state)
  3703. };
  3704. // In some cases, blocks have just one exit, but other blocks
  3705. // can be targeted by multiple breaks. This cannot happen in
  3706. // normal Rust syntax today, but it can happen when we desugar
  3707. // a `do catch { ... }` expression.
  3708. //
  3709. // Example 1:
  3710. //
  3711. // 'a: { if true { break 'a Err(()); } Ok(()) }
  3712. //
  3713. // Here we would wind up with two coercions, one from
  3714. // `Err(())` and the other from the tail expression
  3715. // `Ok(())`. If the tail expression is omitted, that's a
  3716. // "forced unit" -- unless the block diverges, in which
  3717. // case we can ignore the tail expression (e.g., `'a: {
  3718. // break 'a 22; }` would not force the type of the block
  3719. // to be `()`).
  3720. let tail_expr = blk.expr.as_ref();
  3721. let coerce_to_ty = expected.coercion_target_type(self, blk.span);
  3722. let coerce = if blk.targeted_by_break {
  3723. CoerceMany::new(coerce_to_ty)
  3724. } else {
  3725. let tail_expr: &[P<hir::Expr>] = match tail_expr {
  3726. Some(e) => ref_slice(e),
  3727. None => &[],
  3728. };
  3729. CoerceMany::with_coercion_sites(coerce_to_ty, tail_expr)
  3730. };
  3731. let ctxt = BreakableCtxt {
  3732. coerce: Some(coerce),
  3733. may_break: false,
  3734. };
  3735. let (ctxt, ()) = self.with_breakable_ctxt(blk.id, ctxt, || {
  3736. for s in &blk.stmts {
  3737. self.check_stmt(s);
  3738. }
  3739. // check the tail expression **without** holding the
  3740. // `enclosing_breakables` lock below.
  3741. let tail_expr_ty = tail_expr.map(|t| self.check_expr_with_expectation(t, expected));
  3742. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
  3743. let mut ctxt = enclosing_breakables.find_breakable(blk.id);
  3744. let mut coerce = ctxt.coerce.as_mut().unwrap();
  3745. if let Some(tail_expr_ty) = tail_expr_ty {
  3746. let tail_expr = tail_expr.unwrap();
  3747. coerce.coerce(self,
  3748. &self.misc(tail_expr.span),
  3749. tail_expr,
  3750. tail_expr_ty,
  3751. self.diverges.get());
  3752. } else {
  3753. // Subtle: if there is no explicit tail expression,
  3754. // that is typically equivalent to a tail expression
  3755. // of `()` -- except if the block diverges. In that
  3756. // case, there is no value supplied from the tail
  3757. // expression (assuming there are no other breaks,
  3758. // this implies that the type of the block will be
  3759. // `!`).
  3760. //
  3761. // #41425 -- label the implicit `()` as being the
  3762. // "found type" here, rather than the "expected type".
  3763. if !self.diverges.get().always() {
  3764. coerce.coerce_forced_unit(self, &self.misc(blk.span), &mut |err| {
  3765. if let Some(expected_ty) = expected.only_has_type(self) {
  3766. self.consider_hint_about_removing_semicolon(blk,
  3767. expected_ty,
  3768. err);
  3769. }
  3770. }, false);
  3771. }
  3772. }
  3773. });
  3774. let mut ty = ctxt.coerce.unwrap().complete(self);
  3775. if self.has_errors.get() || ty.references_error() {
  3776. ty = self.tcx.types.err
  3777. }
  3778. self.write_ty(blk.id, ty);
  3779. *self.ps.borrow_mut() = prev;
  3780. ty
  3781. }
  3782. /// A common error is to add an extra semicolon:
  3783. ///
  3784. /// ```
  3785. /// fn foo() -> usize {
  3786. /// 22;
  3787. /// }
  3788. /// ```
  3789. ///
  3790. /// This routine checks if the final statement in a block is an
  3791. /// expression with an explicit semicolon whose type is compatible
  3792. /// with `expected_ty`. If so, it suggests removing the semicolon.
  3793. fn consider_hint_about_removing_semicolon(&self,
  3794. blk: &'gcx hir::Block,
  3795. expected_ty: Ty<'tcx>,
  3796. err: &mut DiagnosticBuilder) {
  3797. // Be helpful when the user wrote `{... expr;}` and
  3798. // taking the `;` off is enough to fix the error.
  3799. let last_stmt = match blk.stmts.last() {
  3800. Some(s) => s,
  3801. None => return,
  3802. };
  3803. let last_expr = match last_stmt.node {
  3804. hir::StmtSemi(ref e, _) => e,
  3805. _ => return,
  3806. };
  3807. let last_expr_ty = self.expr_ty(last_expr);
  3808. if self.can_sub_types(last_expr_ty, expected_ty).is_err() {
  3809. return;
  3810. }
  3811. let original_span = original_sp(last_stmt.span, blk.span);
  3812. let span_semi = Span {
  3813. lo: original_span.hi - BytePos(1),
  3814. hi: original_span.hi,
  3815. ctxt: original_span.ctxt,
  3816. };
  3817. err.span_help(span_semi, "consider removing this semicolon:");
  3818. }
  3819. // Instantiates the given path, which must refer to an item with the given
  3820. // number of type parameters and type.
  3821. pub fn instantiate_value_path(&self,
  3822. segments: &[hir::PathSegment],
  3823. opt_self_ty: Option<Ty<'tcx>>,
  3824. def: Def,
  3825. span: Span,
  3826. node_id: ast::NodeId)
  3827. -> Ty<'tcx> {
  3828. debug!("instantiate_value_path(path={:?}, def={:?}, node_id={})",
  3829. segments,
  3830. def,
  3831. node_id);
  3832. // We need to extract the type parameters supplied by the user in
  3833. // the path `path`. Due to the current setup, this is a bit of a
  3834. // tricky-process; the problem is that resolve only tells us the
  3835. // end-point of the path resolution, and not the intermediate steps.
  3836. // Luckily, we can (at least for now) deduce the intermediate steps
  3837. // just from the end-point.
  3838. //
  3839. // There are basically four cases to consider:
  3840. //
  3841. // 1. Reference to a constructor of enum variant or struct:
  3842. //
  3843. // struct Foo<T>(...)
  3844. // enum E<T> { Foo(...) }
  3845. //
  3846. // In these cases, the parameters are declared in the type
  3847. // space.
  3848. //
  3849. // 2. Reference to a fn item or a free constant:
  3850. //
  3851. // fn foo<T>() { }
  3852. //
  3853. // In this case, the path will again always have the form
  3854. // `a::b::foo::<T>` where only the final segment should have
  3855. // type parameters. However, in this case, those parameters are
  3856. // declared on a value, and hence are in the `FnSpace`.
  3857. //
  3858. // 3. Reference to a method or an associated constant:
  3859. //
  3860. // impl<A> SomeStruct<A> {
  3861. // fn foo<B>(...)
  3862. // }
  3863. //
  3864. // Here we can have a path like
  3865. // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
  3866. // may appear in two places. The penultimate segment,
  3867. // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
  3868. // final segment, `foo::<B>` contains parameters in fn space.
  3869. //
  3870. // 4. Reference to a local variable
  3871. //
  3872. // Local variables can't have any type parameters.
  3873. //
  3874. // The first step then is to categorize the segments appropriately.
  3875. assert!(!segments.is_empty());
  3876. let mut ufcs_associated = None;
  3877. let mut type_segment = None;
  3878. let mut fn_segment = None;
  3879. match def {
  3880. // Case 1. Reference to a struct/variant constructor.
  3881. Def::StructCtor(def_id, ..) |
  3882. Def::VariantCtor(def_id, ..) => {
  3883. // Everything but the final segment should have no
  3884. // parameters at all.
  3885. let mut generics = self.tcx.generics_of(def_id);
  3886. if let Some(def_id) = generics.parent {
  3887. // Variant and struct constructors use the
  3888. // generics of their parent type definition.
  3889. generics = self.tcx.generics_of(def_id);
  3890. }
  3891. type_segment = Some((segments.last().unwrap(), generics));
  3892. }
  3893. // Case 2. Reference to a top-level value.
  3894. Def::Fn(def_id) |
  3895. Def::Const(def_id) |
  3896. Def::Static(def_id, _) => {
  3897. fn_segment = Some((segments.last().unwrap(),
  3898. self.tcx.generics_of(def_id)));
  3899. }
  3900. // Case 3. Reference to a method or associated const.
  3901. Def::Method(def_id) |
  3902. Def::AssociatedConst(def_id) => {
  3903. let container = self.tcx.associated_item(def_id).container;
  3904. match container {
  3905. ty::TraitContainer(trait_did) => {
  3906. callee::check_legal_trait_for_method_call(self.tcx, span, trait_did)
  3907. }
  3908. ty::ImplContainer(_) => {}
  3909. }
  3910. let generics = self.tcx.generics_of(def_id);
  3911. if segments.len() >= 2 {
  3912. let parent_generics = self.tcx.generics_of(generics.parent.unwrap());
  3913. type_segment = Some((&segments[segments.len() - 2], parent_generics));
  3914. } else {
  3915. // `<T>::assoc` will end up here, and so can `T::assoc`.
  3916. let self_ty = opt_self_ty.expect("UFCS sugared assoc missing Self");
  3917. ufcs_associated = Some((container, self_ty));
  3918. }
  3919. fn_segment = Some((segments.last().unwrap(), generics));
  3920. }
  3921. // Case 4. Local variable, no generics.
  3922. Def::Local(..) | Def::Upvar(..) => {}
  3923. _ => bug!("unexpected definition: {:?}", def),
  3924. }
  3925. debug!("type_segment={:?} fn_segment={:?}", type_segment, fn_segment);
  3926. // Now that we have categorized what space the parameters for each
  3927. // segment belong to, let's sort out the parameters that the user
  3928. // provided (if any) into their appropriate spaces. We'll also report
  3929. // errors if type parameters are provided in an inappropriate place.
  3930. let poly_segments = type_segment.is_some() as usize +
  3931. fn_segment.is_some() as usize;
  3932. AstConv::prohibit_type_params(self, &segments[..segments.len() - poly_segments]);
  3933. match def {
  3934. Def::Local(def_id) | Def::Upvar(def_id, ..) => {
  3935. let nid = self.tcx.hir.as_local_node_id(def_id).unwrap();
  3936. let ty = self.local_ty(span, nid);
  3937. let ty = self.normalize_associated_types_in(span, &ty);
  3938. self.write_ty(node_id, ty);
  3939. self.write_substs(node_id, ty::ItemSubsts {
  3940. substs: self.tcx.intern_substs(&[])
  3941. });
  3942. return ty;
  3943. }
  3944. _ => {}
  3945. }
  3946. // Now we have to compare the types that the user *actually*
  3947. // provided against the types that were *expected*. If the user
  3948. // did not provide any types, then we want to substitute inference
  3949. // variables. If the user provided some types, we may still need
  3950. // to add defaults. If the user provided *too many* types, that's
  3951. // a problem.
  3952. self.check_path_parameter_count(span, &mut type_segment);
  3953. self.check_path_parameter_count(span, &mut fn_segment);
  3954. let (fn_start, has_self) = match (type_segment, fn_segment) {
  3955. (_, Some((_, generics))) => {
  3956. (generics.parent_count(), generics.has_self)
  3957. }
  3958. (Some((_, generics)), None) => {
  3959. (generics.own_count(), generics.has_self)
  3960. }
  3961. (None, None) => (0, false)
  3962. };
  3963. let substs = Substs::for_item(self.tcx, def.def_id(), |def, _| {
  3964. let mut i = def.index as usize;
  3965. let segment = if i < fn_start {
  3966. i -= has_self as usize;
  3967. type_segment
  3968. } else {
  3969. i -= fn_start;
  3970. fn_segment
  3971. };
  3972. let lifetimes = match segment.map(|(s, _)| &s.parameters) {
  3973. Some(&hir::AngleBracketedParameters(ref data)) => &data.lifetimes[..],
  3974. Some(&hir::ParenthesizedParameters(_)) => bug!(),
  3975. None => &[]
  3976. };
  3977. if let Some(lifetime) = lifetimes.get(i) {
  3978. AstConv::ast_region_to_region(self, lifetime, Some(def))
  3979. } else {
  3980. self.re_infer(span, Some(def)).unwrap()
  3981. }
  3982. }, |def, substs| {
  3983. let mut i = def.index as usize;
  3984. let segment = if i < fn_start {
  3985. // Handle Self first, so we can adjust the index to match the AST.
  3986. if has_self && i == 0 {
  3987. return opt_self_ty.unwrap_or_else(|| {
  3988. self.type_var_for_def(span, def, substs)
  3989. });
  3990. }
  3991. i -= has_self as usize;
  3992. type_segment
  3993. } else {
  3994. i -= fn_start;
  3995. fn_segment
  3996. };
  3997. let (types, infer_types) = match segment.map(|(s, _)| &s.parameters) {
  3998. Some(&hir::AngleBracketedParameters(ref data)) => {
  3999. (&data.types[..], data.infer_types)
  4000. }
  4001. Some(&hir::ParenthesizedParameters(_)) => bug!(),
  4002. None => (&[][..], true)
  4003. };
  4004. // Skip over the lifetimes in the same segment.
  4005. if let Some((_, generics)) = segment {
  4006. i -= generics.regions.len();
  4007. }
  4008. if let Some(ast_ty) = types.get(i) {
  4009. // A provided type parameter.
  4010. self.to_ty(ast_ty)
  4011. } else if !infer_types && def.has_default {
  4012. // No type parameter provided, but a default exists.
  4013. let default = self.tcx.type_of(def.def_id);
  4014. self.normalize_ty(
  4015. span,
  4016. default.subst_spanned(self.tcx, substs, Some(span))
  4017. )
  4018. } else {
  4019. // No type parameters were provided, we can infer all.
  4020. // This can also be reached in some error cases:
  4021. // We prefer to use inference variables instead of
  4022. // TyError to let type inference recover somewhat.
  4023. self.type_var_for_def(span, def, substs)
  4024. }
  4025. });
  4026. // The things we are substituting into the type should not contain
  4027. // escaping late-bound regions, and nor should the base type scheme.
  4028. let ty = self.tcx.type_of(def.def_id());
  4029. assert!(!substs.has_escaping_regions());
  4030. assert!(!ty.has_escaping_regions());
  4031. // Add all the obligations that are required, substituting and
  4032. // normalized appropriately.
  4033. let bounds = self.instantiate_bounds(span, def.def_id(), &substs);
  4034. self.add_obligations_for_parameters(
  4035. traits::ObligationCause::new(span, self.body_id, traits::ItemObligation(def.def_id())),
  4036. &bounds);
  4037. // Substitute the values for the type parameters into the type of
  4038. // the referenced item.
  4039. let ty_substituted = self.instantiate_type_scheme(span, &substs, &ty);
  4040. if let Some((ty::ImplContainer(impl_def_id), self_ty)) = ufcs_associated {
  4041. // In the case of `Foo<T>::method` and `<Foo<T>>::method`, if `method`
  4042. // is inherent, there is no `Self` parameter, instead, the impl needs
  4043. // type parameters, which we can infer by unifying the provided `Self`
  4044. // with the substituted impl type.
  4045. let ty = self.tcx.type_of(impl_def_id);
  4046. let impl_ty = self.instantiate_type_scheme(span, &substs, &ty);
  4047. match self.sub_types(false, &self.misc(span), self_ty, impl_ty) {
  4048. Ok(ok) => self.register_infer_ok_obligations(ok),
  4049. Err(_) => {
  4050. span_bug!(span,
  4051. "instantiate_value_path: (UFCS) {:?} was a subtype of {:?} but now is not?",
  4052. self_ty,
  4053. impl_ty);
  4054. }
  4055. }
  4056. }
  4057. debug!("instantiate_value_path: type of {:?} is {:?}",
  4058. node_id,
  4059. ty_substituted);
  4060. self.write_substs(node_id, ty::ItemSubsts {
  4061. substs: substs
  4062. });
  4063. ty_substituted
  4064. }
  4065. /// Report errors if the provided parameters are too few or too many.
  4066. fn check_path_parameter_count(&self,
  4067. span: Span,
  4068. segment: &mut Option<(&hir::PathSegment, &ty::Generics)>) {
  4069. let (lifetimes, types, infer_types, bindings) = {
  4070. match segment.map(|(s, _)| &s.parameters) {
  4071. Some(&hir::AngleBracketedParameters(ref data)) => {
  4072. (&data.lifetimes[..], &data.types[..], data.infer_types, &data.bindings[..])
  4073. }
  4074. Some(&hir::ParenthesizedParameters(_)) => {
  4075. span_bug!(span, "parenthesized parameters cannot appear in ExprPath");
  4076. }
  4077. None => (&[][..], &[][..], true, &[][..])
  4078. }
  4079. };
  4080. let count_lifetime_params = |n| {
  4081. format!("{} lifetime parameter{}", n, if n == 1 { "" } else { "s" })
  4082. };
  4083. let count_type_params = |n| {
  4084. format!("{} type parameter{}", n, if n == 1 { "" } else { "s" })
  4085. };
  4086. // Check provided lifetime parameters.
  4087. let lifetime_defs = segment.map_or(&[][..], |(_, generics)| &generics.regions);
  4088. if lifetimes.len() > lifetime_defs.len() {
  4089. let expected_text = count_lifetime_params(lifetime_defs.len());
  4090. let actual_text = count_lifetime_params(lifetimes.len());
  4091. struct_span_err!(self.tcx.sess, span, E0088,
  4092. "too many lifetime parameters provided: \
  4093. expected at most {}, found {}",
  4094. expected_text, actual_text)
  4095. .span_label(span, format!("expected {}", expected_text))
  4096. .emit();
  4097. } else if lifetimes.len() > 0 && lifetimes.len() < lifetime_defs.len() {
  4098. let expected_text = count_lifetime_params(lifetime_defs.len());
  4099. let actual_text = count_lifetime_params(lifetimes.len());
  4100. struct_span_err!(self.tcx.sess, span, E0090,
  4101. "too few lifetime parameters provided: \
  4102. expected {}, found {}",
  4103. expected_text, actual_text)
  4104. .span_label(span, format!("expected {}", expected_text))
  4105. .emit();
  4106. }
  4107. // The case where there is not enough lifetime parameters is not checked,
  4108. // because this is not possible - a function never takes lifetime parameters.
  4109. // See discussion for Pull Request 36208.
  4110. // Check provided type parameters.
  4111. let type_defs = segment.map_or(&[][..], |(_, generics)| {
  4112. if generics.parent.is_none() {
  4113. &generics.types[generics.has_self as usize..]
  4114. } else {
  4115. &generics.types
  4116. }
  4117. });
  4118. let required_len = type_defs.iter().take_while(|d| !d.has_default).count();
  4119. if types.len() > type_defs.len() {
  4120. let span = types[type_defs.len()].span;
  4121. let expected_text = count_type_params(type_defs.len());
  4122. let actual_text = count_type_params(types.len());
  4123. struct_span_err!(self.tcx.sess, span, E0087,
  4124. "too many type parameters provided: \
  4125. expected at most {}, found {}",
  4126. expected_text, actual_text)
  4127. .span_label(span, format!("expected {}", expected_text))
  4128. .emit();
  4129. // To prevent derived errors to accumulate due to extra
  4130. // type parameters, we force instantiate_value_path to
  4131. // use inference variables instead of the provided types.
  4132. *segment = None;
  4133. } else if !infer_types && types.len() < required_len {
  4134. let expected_text = count_type_params(required_len);
  4135. let actual_text = count_type_params(types.len());
  4136. struct_span_err!(self.tcx.sess, span, E0089,
  4137. "too few type parameters provided: \
  4138. expected {}, found {}",
  4139. expected_text, actual_text)
  4140. .span_label(span, format!("expected {}", expected_text))
  4141. .emit();
  4142. }
  4143. if !bindings.is_empty() {
  4144. span_err!(self.tcx.sess, bindings[0].span, E0182,
  4145. "unexpected binding of associated item in expression path \
  4146. (only allowed in type paths)");
  4147. }
  4148. }
  4149. fn structurally_resolve_type_or_else<F>(&self, sp: Span, ty: Ty<'tcx>, f: F)
  4150. -> Ty<'tcx>
  4151. where F: Fn() -> Ty<'tcx>
  4152. {
  4153. let mut ty = self.resolve_type_vars_with_obligations(ty);
  4154. if ty.is_ty_var() {
  4155. let alternative = f();
  4156. // If not, error.
  4157. if alternative.is_ty_var() || alternative.references_error() {
  4158. if !self.is_tainted_by_errors() {
  4159. self.type_error_message(sp, |_actual| {
  4160. "the type of this value must be known in this context".to_string()
  4161. }, ty);
  4162. }
  4163. self.demand_suptype(sp, self.tcx.types.err, ty);
  4164. ty = self.tcx.types.err;
  4165. } else {
  4166. self.demand_suptype(sp, alternative, ty);
  4167. ty = alternative;
  4168. }
  4169. }
  4170. ty
  4171. }
  4172. // Resolves `typ` by a single level if `typ` is a type variable. If no
  4173. // resolution is possible, then an error is reported.
  4174. pub fn structurally_resolved_type(&self, sp: Span, ty: Ty<'tcx>) -> Ty<'tcx> {
  4175. self.structurally_resolve_type_or_else(sp, ty, || {
  4176. self.tcx.types.err
  4177. })
  4178. }
  4179. fn with_breakable_ctxt<F: FnOnce() -> R, R>(&self, id: ast::NodeId,
  4180. ctxt: BreakableCtxt<'gcx, 'tcx>, f: F)
  4181. -> (BreakableCtxt<'gcx, 'tcx>, R) {
  4182. let index;
  4183. {
  4184. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
  4185. index = enclosing_breakables.stack.len();
  4186. enclosing_breakables.by_id.insert(id, index);
  4187. enclosing_breakables.stack.push(ctxt);
  4188. }
  4189. let result = f();
  4190. let ctxt = {
  4191. let mut enclosing_breakables = self.enclosing_breakables.borrow_mut();
  4192. debug_assert!(enclosing_breakables.stack.len() == index + 1);
  4193. enclosing_breakables.by_id.remove(&id).expect("missing breakable context");
  4194. enclosing_breakables.stack.pop().expect("missing breakable context")
  4195. };
  4196. (ctxt, result)
  4197. }
  4198. }
  4199. pub fn check_bounds_are_used<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
  4200. generics: &hir::Generics,
  4201. ty: Ty<'tcx>) {
  4202. debug!("check_bounds_are_used(n_tps={}, ty={:?})",
  4203. generics.ty_params.len(), ty);
  4204. // make a vector of booleans initially false, set to true when used
  4205. if generics.ty_params.is_empty() { return; }
  4206. let mut tps_used = vec![false; generics.ty_params.len()];
  4207. for leaf_ty in ty.walk() {
  4208. if let ty::TyParam(ParamTy {idx, ..}) = leaf_ty.sty {
  4209. debug!("Found use of ty param num {}", idx);
  4210. tps_used[idx as usize - generics.lifetimes.len()] = true;
  4211. }
  4212. }
  4213. for (&used, param) in tps_used.iter().zip(&generics.ty_params) {
  4214. if !used {
  4215. struct_span_err!(tcx.sess, param.span, E0091,
  4216. "type parameter `{}` is unused",
  4217. param.name)
  4218. .span_label(param.span, "unused type parameter")
  4219. .emit();
  4220. }
  4221. }
  4222. }