]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/writeback.rs
split ty::util and ty::adjustment
[rust.git] / src / librustc_typeck / check / writeback.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 // Type resolution: the phase that finds all the types in the AST with
12 // unresolved type variables and replaces "ty_var" types with their
13 // substitutions.
14 use self::ResolveReason::*;
15
16 use astconv::AstConv;
17 use check::FnCtxt;
18 use middle::def_id::DefId;
19 use middle::pat_util;
20 use middle::ty::{self, Ty, MethodCall, MethodCallee};
21 use middle::ty::adjustment;
22 use middle::ty::fold::{TypeFolder,TypeFoldable};
23 use middle::infer;
24 use write_substs_to_tcx;
25 use write_ty_to_tcx;
26
27 use std::cell::Cell;
28
29 use syntax::ast;
30 use syntax::codemap::{DUMMY_SP, Span};
31 use rustc_front::print::pprust::pat_to_string;
32 use rustc_front::visit;
33 use rustc_front::visit::Visitor;
34 use rustc_front::util as hir_util;
35 use rustc_front::hir;
36
37 ///////////////////////////////////////////////////////////////////////////
38 // Entry point functions
39
40 pub fn resolve_type_vars_in_expr(fcx: &FnCtxt, e: &hir::Expr) {
41     assert_eq!(fcx.writeback_errors.get(), false);
42     let mut wbcx = WritebackCx::new(fcx);
43     wbcx.visit_expr(e);
44     wbcx.visit_upvar_borrow_map();
45     wbcx.visit_closures();
46 }
47
48 pub fn resolve_type_vars_in_fn(fcx: &FnCtxt,
49                                decl: &hir::FnDecl,
50                                blk: &hir::Block) {
51     assert_eq!(fcx.writeback_errors.get(), false);
52     let mut wbcx = WritebackCx::new(fcx);
53     wbcx.visit_block(blk);
54     for arg in &decl.inputs {
55         wbcx.visit_node_id(ResolvingPattern(arg.pat.span), arg.id);
56         wbcx.visit_pat(&*arg.pat);
57
58         // Privacy needs the type for the whole pattern, not just each binding
59         if !pat_util::pat_is_binding(&fcx.tcx().def_map, &*arg.pat) {
60             wbcx.visit_node_id(ResolvingPattern(arg.pat.span),
61                                arg.pat.id);
62         }
63     }
64     wbcx.visit_upvar_borrow_map();
65     wbcx.visit_closures();
66 }
67
68 ///////////////////////////////////////////////////////////////////////////
69 // The Writerback context. This visitor walks the AST, checking the
70 // fn-specific tables to find references to types or regions. It
71 // resolves those regions to remove inference variables and writes the
72 // final result back into the master tables in the tcx. Here and
73 // there, it applies a few ad-hoc checks that were not convenient to
74 // do elsewhere.
75
76 struct WritebackCx<'cx, 'tcx: 'cx> {
77     fcx: &'cx FnCtxt<'cx, 'tcx>,
78 }
79
80 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
81     fn new(fcx: &'cx FnCtxt<'cx, 'tcx>) -> WritebackCx<'cx, 'tcx> {
82         WritebackCx { fcx: fcx }
83     }
84
85     fn tcx(&self) -> &'cx ty::ctxt<'tcx> {
86         self.fcx.tcx()
87     }
88
89     // Hacky hack: During type-checking, we treat *all* operators
90     // as potentially overloaded. But then, during writeback, if
91     // we observe that something like `a+b` is (known to be)
92     // operating on scalars, we clear the overload.
93     fn fix_scalar_binary_expr(&mut self, e: &hir::Expr) {
94         if let hir::ExprBinary(ref op, ref lhs, ref rhs) = e.node {
95             let lhs_ty = self.fcx.node_ty(lhs.id);
96             let lhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&lhs_ty);
97
98             let rhs_ty = self.fcx.node_ty(rhs.id);
99             let rhs_ty = self.fcx.infcx().resolve_type_vars_if_possible(&rhs_ty);
100
101             if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
102                 self.fcx.inh.tables.borrow_mut().method_map.remove(&MethodCall::expr(e.id));
103
104                 // weird but true: the by-ref binops put an
105                 // adjustment on the lhs but not the rhs; the
106                 // adjustment for rhs is kind of baked into the
107                 // system.
108                 if !hir_util::is_by_value_binop(op.node) {
109                     self.fcx.inh.tables.borrow_mut().adjustments.remove(&lhs.id);
110                 }
111             }
112         }
113     }
114 }
115
116 ///////////////////////////////////////////////////////////////////////////
117 // Impl of Visitor for Resolver
118 //
119 // This is the master code which walks the AST. It delegates most of
120 // the heavy lifting to the generic visit and resolve functions
121 // below. In general, a function is made into a `visitor` if it must
122 // traffic in node-ids or update tables in the type context etc.
123
124 impl<'cx, 'tcx, 'v> Visitor<'v> for WritebackCx<'cx, 'tcx> {
125     fn visit_item(&mut self, _: &hir::Item) {
126         // Ignore items
127     }
128
129     fn visit_stmt(&mut self, s: &hir::Stmt) {
130         if self.fcx.writeback_errors.get() {
131             return;
132         }
133
134         self.visit_node_id(ResolvingExpr(s.span), hir_util::stmt_id(s));
135         visit::walk_stmt(self, s);
136     }
137
138     fn visit_expr(&mut self, e: &hir::Expr) {
139         if self.fcx.writeback_errors.get() {
140             return;
141         }
142
143         self.fix_scalar_binary_expr(e);
144
145         self.visit_node_id(ResolvingExpr(e.span), e.id);
146         self.visit_method_map_entry(ResolvingExpr(e.span),
147                                     MethodCall::expr(e.id));
148
149         if let hir::ExprClosure(_, ref decl, _) = e.node {
150             for input in &decl.inputs {
151                 self.visit_node_id(ResolvingExpr(e.span), input.id);
152             }
153         }
154
155         visit::walk_expr(self, e);
156     }
157
158     fn visit_block(&mut self, b: &hir::Block) {
159         if self.fcx.writeback_errors.get() {
160             return;
161         }
162
163         self.visit_node_id(ResolvingExpr(b.span), b.id);
164         visit::walk_block(self, b);
165     }
166
167     fn visit_pat(&mut self, p: &hir::Pat) {
168         if self.fcx.writeback_errors.get() {
169             return;
170         }
171
172         self.visit_node_id(ResolvingPattern(p.span), p.id);
173
174         debug!("Type for pattern binding {} (id {}) resolved to {:?}",
175                pat_to_string(p),
176                p.id,
177                self.tcx().node_id_to_type(p.id));
178
179         visit::walk_pat(self, p);
180     }
181
182     fn visit_local(&mut self, l: &hir::Local) {
183         if self.fcx.writeback_errors.get() {
184             return;
185         }
186
187         let var_ty = self.fcx.local_ty(l.span, l.id);
188         let var_ty = self.resolve(&var_ty, ResolvingLocal(l.span));
189         write_ty_to_tcx(self.tcx(), l.id, var_ty);
190         visit::walk_local(self, l);
191     }
192
193     fn visit_ty(&mut self, t: &hir::Ty) {
194         match t.node {
195             hir::TyFixedLengthVec(ref ty, ref count_expr) => {
196                 self.visit_ty(&**ty);
197                 write_ty_to_tcx(self.tcx(), count_expr.id, self.tcx().types.usize);
198             }
199             _ => visit::walk_ty(self, t)
200         }
201     }
202 }
203
204 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
205     fn visit_upvar_borrow_map(&self) {
206         if self.fcx.writeback_errors.get() {
207             return;
208         }
209
210         for (upvar_id, upvar_capture) in self.fcx.inh.tables.borrow().upvar_capture_map.iter() {
211             let new_upvar_capture = match *upvar_capture {
212                 ty::UpvarCapture::ByValue => ty::UpvarCapture::ByValue,
213                 ty::UpvarCapture::ByRef(ref upvar_borrow) => {
214                     let r = upvar_borrow.region;
215                     let r = self.resolve(&r, ResolvingUpvar(*upvar_id));
216                     ty::UpvarCapture::ByRef(
217                         ty::UpvarBorrow { kind: upvar_borrow.kind, region: r })
218                 }
219             };
220             debug!("Upvar capture for {:?} resolved to {:?}",
221                    upvar_id,
222                    new_upvar_capture);
223             self.fcx.tcx()
224                     .tables
225                     .borrow_mut()
226                     .upvar_capture_map
227                     .insert(*upvar_id, new_upvar_capture);
228         }
229     }
230
231     fn visit_closures(&self) {
232         if self.fcx.writeback_errors.get() {
233             return
234         }
235
236         for (def_id, closure_ty) in self.fcx.inh.tables.borrow().closure_tys.iter() {
237             let closure_ty = self.resolve(closure_ty, ResolvingClosure(*def_id));
238             self.fcx.tcx().tables.borrow_mut().closure_tys.insert(*def_id, closure_ty);
239         }
240
241         for (def_id, &closure_kind) in self.fcx.inh.tables.borrow().closure_kinds.iter() {
242             self.fcx.tcx().tables.borrow_mut().closure_kinds.insert(*def_id, closure_kind);
243         }
244     }
245
246     fn visit_node_id(&self, reason: ResolveReason, id: ast::NodeId) {
247         // Resolve any borrowings for the node with id `id`
248         self.visit_adjustments(reason, id);
249
250         // Resolve the type of the node with id `id`
251         let n_ty = self.fcx.node_ty(id);
252         let n_ty = self.resolve(&n_ty, reason);
253         write_ty_to_tcx(self.tcx(), id, n_ty);
254         debug!("Node {} has type {:?}", id, n_ty);
255
256         // Resolve any substitutions
257         self.fcx.opt_node_ty_substs(id, |item_substs| {
258             write_substs_to_tcx(self.tcx(), id,
259                                 self.resolve(item_substs, reason));
260         });
261     }
262
263     fn visit_adjustments(&self, reason: ResolveReason, id: ast::NodeId) {
264         let adjustments = self.fcx.inh.tables.borrow_mut().adjustments.remove(&id);
265         match adjustments {
266             None => {
267                 debug!("No adjustments for node {}", id);
268             }
269
270             Some(adjustment) => {
271                 let resolved_adjustment = match adjustment {
272                     adjustment::AdjustReifyFnPointer => {
273                         adjustment::AdjustReifyFnPointer
274                     }
275
276                     adjustment::AdjustUnsafeFnPointer => {
277                         adjustment::AdjustUnsafeFnPointer
278                     }
279
280                     adjustment::AdjustDerefRef(adj) => {
281                         for autoderef in 0..adj.autoderefs {
282                             let method_call = MethodCall::autoderef(id, autoderef as u32);
283                             self.visit_method_map_entry(reason, method_call);
284                         }
285
286                         adjustment::AdjustDerefRef(adjustment::AutoDerefRef {
287                             autoderefs: adj.autoderefs,
288                             autoref: self.resolve(&adj.autoref, reason),
289                             unsize: self.resolve(&adj.unsize, reason),
290                         })
291                     }
292                 };
293                 debug!("Adjustments for node {}: {:?}", id, resolved_adjustment);
294                 self.tcx().tables.borrow_mut().adjustments.insert(
295                     id, resolved_adjustment);
296             }
297         }
298     }
299
300     fn visit_method_map_entry(&self,
301                               reason: ResolveReason,
302                               method_call: MethodCall) {
303         // Resolve any method map entry
304         let new_method = match self.fcx.inh.tables.borrow_mut().method_map.remove(&method_call) {
305             Some(method) => {
306                 debug!("writeback::resolve_method_map_entry(call={:?}, entry={:?})",
307                        method_call,
308                        method);
309                 let new_method = MethodCallee {
310                     def_id: method.def_id,
311                     ty: self.resolve(&method.ty, reason),
312                     substs: self.tcx().mk_substs(self.resolve(method.substs, reason)),
313                 };
314
315                 Some(new_method)
316             }
317             None => None
318         };
319
320         //NB(jroesch): We need to match twice to avoid a double borrow which would cause an ICE
321         match new_method {
322             Some(method) => {
323                 self.tcx().tables.borrow_mut().method_map.insert(
324                     method_call,
325                     method);
326             }
327             None => {}
328         }
329     }
330
331     fn resolve<T:TypeFoldable<'tcx>>(&self, t: &T, reason: ResolveReason) -> T {
332         t.fold_with(&mut Resolver::new(self.fcx, reason))
333     }
334 }
335
336 ///////////////////////////////////////////////////////////////////////////
337 // Resolution reason.
338
339 #[derive(Copy, Clone)]
340 enum ResolveReason {
341     ResolvingExpr(Span),
342     ResolvingLocal(Span),
343     ResolvingPattern(Span),
344     ResolvingUpvar(ty::UpvarId),
345     ResolvingClosure(DefId),
346 }
347
348 impl ResolveReason {
349     fn span(&self, tcx: &ty::ctxt) -> Span {
350         match *self {
351             ResolvingExpr(s) => s,
352             ResolvingLocal(s) => s,
353             ResolvingPattern(s) => s,
354             ResolvingUpvar(upvar_id) => {
355                 tcx.expr_span(upvar_id.closure_expr_id)
356             }
357             ResolvingClosure(did) => {
358                 if did.is_local() {
359                     tcx.expr_span(did.node)
360                 } else {
361                     DUMMY_SP
362                 }
363             }
364         }
365     }
366 }
367
368 ///////////////////////////////////////////////////////////////////////////
369 // The Resolver. This is the type folding engine that detects
370 // unresolved types and so forth.
371
372 struct Resolver<'cx, 'tcx: 'cx> {
373     tcx: &'cx ty::ctxt<'tcx>,
374     infcx: &'cx infer::InferCtxt<'cx, 'tcx>,
375     writeback_errors: &'cx Cell<bool>,
376     reason: ResolveReason,
377 }
378
379 impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
380     fn new(fcx: &'cx FnCtxt<'cx, 'tcx>,
381            reason: ResolveReason)
382            -> Resolver<'cx, 'tcx>
383     {
384         Resolver::from_infcx(fcx.infcx(), &fcx.writeback_errors, reason)
385     }
386
387     fn from_infcx(infcx: &'cx infer::InferCtxt<'cx, 'tcx>,
388                   writeback_errors: &'cx Cell<bool>,
389                   reason: ResolveReason)
390                   -> Resolver<'cx, 'tcx>
391     {
392         Resolver { infcx: infcx,
393                    tcx: infcx.tcx,
394                    writeback_errors: writeback_errors,
395                    reason: reason }
396     }
397
398     fn report_error(&self, e: infer::FixupError) {
399         self.writeback_errors.set(true);
400         if !self.tcx.sess.has_errors() {
401             match self.reason {
402                 ResolvingExpr(span) => {
403                     span_err!(self.tcx.sess, span, E0101,
404                         "cannot determine a type for this expression: {}",
405                         infer::fixup_err_to_string(e));
406                 }
407
408                 ResolvingLocal(span) => {
409                     span_err!(self.tcx.sess, span, E0102,
410                         "cannot determine a type for this local variable: {}",
411                         infer::fixup_err_to_string(e));
412                 }
413
414                 ResolvingPattern(span) => {
415                     span_err!(self.tcx.sess, span, E0103,
416                         "cannot determine a type for this pattern binding: {}",
417                         infer::fixup_err_to_string(e));
418                 }
419
420                 ResolvingUpvar(upvar_id) => {
421                     let span = self.reason.span(self.tcx);
422                     span_err!(self.tcx.sess, span, E0104,
423                         "cannot resolve lifetime for captured variable `{}`: {}",
424                         self.tcx.local_var_name_str(upvar_id.var_id).to_string(),
425                         infer::fixup_err_to_string(e));
426                 }
427
428                 ResolvingClosure(_) => {
429                     let span = self.reason.span(self.tcx);
430                     span_err!(self.tcx.sess, span, E0196,
431                               "cannot determine a type for this closure")
432                 }
433             }
434         }
435     }
436 }
437
438 impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
439     fn tcx<'a>(&'a self) -> &'a ty::ctxt<'tcx> {
440         self.tcx
441     }
442
443     fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
444         match self.infcx.fully_resolve(&t) {
445             Ok(t) => t,
446             Err(e) => {
447                 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable",
448                        t);
449                 self.report_error(e);
450                 self.tcx().types.err
451             }
452         }
453     }
454
455     fn fold_region(&mut self, r: ty::Region) -> ty::Region {
456         match self.infcx.fully_resolve(&r) {
457             Ok(r) => r,
458             Err(e) => {
459                 self.report_error(e);
460                 ty::ReStatic
461             }
462         }
463     }
464 }
465
466 ///////////////////////////////////////////////////////////////////////////
467 // During type check, we store promises with the result of trait
468 // lookup rather than the actual results (because the results are not
469 // necessarily available immediately). These routines unwind the
470 // promises. It is expected that we will have already reported any
471 // errors that may be encountered, so if the promises store an error,
472 // a dummy result is returned.