/
mod.rs
4263 lines (3892 loc) · 161 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*
# check.rs
Within the check phase of type check, we check each item one at a time
(bodies of function expressions are checked as part of the containing
function). Inference is used to supply types wherever they are
unknown.
By far the most complex case is checking the body of a function. This
can be broken down into several distinct phases:
- gather: creates type variables to represent the type of each local
variable and pattern binding.
- main: the main pass does the lion's share of the work: it
determines the types of all expressions, resolves
methods, checks for most invalid conditions, and so forth. In
some cases, where a type is unknown, it may create a type or region
variable and use that as the type of an expression.
In the process of checking, various constraints will be placed on
these type variables through the subtyping relationships requested
through the `demand` module. The `typeck::infer` module is in charge
of resolving those constraints.
- regionck: after main is complete, the regionck pass goes over all
types looking for regions and making sure that they did not escape
into places they are not in scope. This may also influence the
final assignments of the various region variables if there is some
flexibility.
- vtable: find and records the impls to use for each trait bound that
appears on a type parameter.
- writeback: writes the final types within a function body, replacing
type variables with their final inferred types. These final types
are written into the `tcx.node_types` table, which should *never* contain
any reference to a type variable.
## Intermediate types
While type checking a function, the intermediate types for the
expressions, blocks, and so forth contained within the function are
stored in `fcx.node_types` and `fcx.node_type_substs`. These types
may contain unresolved type variables. After type checking is
complete, the functions in the writeback module are used to take the
types from this table, resolve them, and then write them into their
permanent home in the type context `ccx.tcx`.
This means that during inferencing you should use `fcx.write_ty()`
and `fcx.expr_ty()` / `fcx.node_ty()` to write/obtain the types of
nodes within the function.
The types of top-level items, which never contain unbound type
variables, are stored directly into the `tcx` tables.
n.b.: A type variable is not the same thing as a type parameter. A
type variable is rather an "instance" of a type parameter: that is,
given a generic function `fn foo<T>(t: T)`: while checking the
function `foo`, the type `ty_param(0)` refers to the type `T`, which
is treated in abstract. When `foo()` is called, however, `T` will be
substituted for a fresh type variable `N`. This variable will
eventually be resolved to some concrete type (which might itself be
type parameter).
*/
use middle::const_eval;
use middle::lang_items::{ExchangeHeapLangItem, GcLangItem};
use middle::lang_items::{ManagedHeapLangItem};
use middle::lint::UnreachableCode;
use middle::pat_util::pat_id_map;
use middle::pat_util;
use middle::subst::Subst;
use middle::ty::{FnSig, VariantInfo};
use middle::ty::{ty_param_bounds_and_ty, ty_param_substs_and_ty};
use middle::ty::{substs, param_ty, Disr, ExprTyProvider};
use middle::ty;
use middle::ty_fold::TypeFolder;
use middle::typeck::astconv::AstConv;
use middle::typeck::astconv::{ast_region_to_region, ast_ty_to_ty};
use middle::typeck::astconv;
use middle::typeck::check::_match::pat_ctxt;
use middle::typeck::check::method::{AutoderefReceiver};
use middle::typeck::check::method::{AutoderefReceiverFlag};
use middle::typeck::check::method::{CheckTraitsAndInherentMethods};
use middle::typeck::check::method::{DontAutoderefReceiver};
use middle::typeck::check::regionmanip::replace_bound_regions_in_fn_sig;
use middle::typeck::check::regionmanip::relate_free_regions;
use middle::typeck::check::vtable::{LocationInfo, VtableContext};
use middle::typeck::CrateCtxt;
use middle::typeck::infer::{resolve_type, force_tvar};
use middle::typeck::infer;
use middle::typeck::rscope::RegionScope;
use middle::typeck::{lookup_def_ccx};
use middle::typeck::no_params;
use middle::typeck::{require_same_types, MethodMap, vtable_map};
use middle::lang_items::TypeIdLangItem;
use util::common::{block_query, indenter, loop_query};
use util::ppaux;
use util::ppaux::{UserString, Repr};
use std::cell::{Cell, RefCell};
use collections::HashMap;
use std::mem::replace;
use std::result;
use std::vec;
use syntax::abi::AbiSet;
use syntax::ast::{Provided, Required};
use syntax::ast;
use syntax::ast_util::local_def;
use syntax::ast_util;
use syntax::attr;
use syntax::codemap::Span;
use syntax::codemap;
use syntax::opt_vec::OptVec;
use syntax::opt_vec;
use syntax::parse::token;
use syntax::print::pprust;
use syntax::visit;
use syntax::visit::Visitor;
use syntax;
pub mod _match;
pub mod vtable;
pub mod writeback;
pub mod regionmanip;
pub mod regionck;
pub mod demand;
pub mod method;
/// Fields that are part of a `FnCtxt` which are inherited by
/// closures defined within the function. For example:
///
/// fn foo() {
/// bar(proc() { ... })
/// }
///
/// Here, the function `foo()` and the closure passed to
/// `bar()` will each have their own `FnCtxt`, but they will
/// share the inherited fields.
pub struct Inherited {
infcx: infer::InferCtxt,
locals: @RefCell<HashMap<ast::NodeId, ty::t>>,
param_env: ty::ParameterEnvironment,
// Temporary tables:
node_types: RefCell<HashMap<ast::NodeId, ty::t>>,
node_type_substs: RefCell<HashMap<ast::NodeId, ty::substs>>,
adjustments: RefCell<HashMap<ast::NodeId, @ty::AutoAdjustment>>,
method_map: MethodMap,
vtable_map: vtable_map,
upvar_borrow_map: RefCell<ty::UpvarBorrowMap>,
}
#[deriving(Clone)]
pub enum FnKind {
// A do-closure.
DoBlock,
// A normal closure or fn item.
Vanilla
}
#[deriving(Clone)]
pub struct PurityState {
def: ast::NodeId,
purity: ast::Purity,
priv from_fn: bool
}
impl PurityState {
pub fn function(purity: ast::Purity, def: ast::NodeId) -> PurityState {
PurityState { def: def, purity: purity, from_fn: true }
}
pub fn recurse(&mut self, blk: &ast::Block) -> PurityState {
match self.purity {
// If this unsafe, then if the outer function was already marked as
// unsafe we shouldn't attribute the unsafe'ness to the block. This
// way the block can be warned about instead of ignoring this
// extraneous block (functions are never warned about).
ast::UnsafeFn if self.from_fn => *self,
purity => {
let (purity, def) = match blk.rules {
ast::UnsafeBlock(..) => (ast::UnsafeFn, blk.id),
ast::DefaultBlock => (purity, self.def),
};
PurityState{ def: def,
purity: purity,
from_fn: false }
}
}
}
}
/// Whether `check_binop` is part of an assignment or not.
/// Used to know wether we allow user overloads and to print
/// better messages on error.
#[deriving(Eq)]
enum IsBinopAssignment{
SimpleBinop,
BinopAssignment,
}
#[deriving(Clone)]
pub struct FnCtxt {
// Number of errors that had been reported when we started
// checking this function. On exit, if we find that *more* errors
// have been reported, we will skip regionck and other work that
// expects the types within the function to be consistent.
err_count_on_creation: uint,
ret_ty: ty::t,
ps: RefCell<PurityState>,
// Sometimes we generate region pointers where the precise region
// to use is not known. For example, an expression like `&x.f`
// where `x` is of type `@T`: in this case, we will be rooting
// `x` onto the stack frame, and we could choose to root it until
// the end of (almost) any enclosing block or expression. We
// want to pick the narrowest block that encompasses all uses.
//
// What we do in such cases is to generate a region variable with
// `region_lb` as a lower bound. The regionck pass then adds
// other constriants based on how the variable is used and region
// inference selects the ultimate value. Finally, borrowck is
// charged with guaranteeing that the value whose address was taken
// can actually be made to live as long as it needs to live.
region_lb: Cell<ast::NodeId>,
// Says whether we're inside a for loop, in a do block
// or neither. Helps with error messages involving the
// function return type.
fn_kind: FnKind,
inh: @Inherited,
ccx: @CrateCtxt,
}
impl Inherited {
fn new(tcx: ty::ctxt,
param_env: ty::ParameterEnvironment)
-> Inherited {
Inherited {
infcx: infer::new_infer_ctxt(tcx),
locals: @RefCell::new(HashMap::new()),
param_env: param_env,
node_types: RefCell::new(HashMap::new()),
node_type_substs: RefCell::new(HashMap::new()),
adjustments: RefCell::new(HashMap::new()),
method_map: @RefCell::new(HashMap::new()),
vtable_map: @RefCell::new(HashMap::new()),
upvar_borrow_map: RefCell::new(HashMap::new()),
}
}
}
// Used by check_const and check_enum_variants
pub fn blank_fn_ctxt(ccx: @CrateCtxt,
rty: ty::t,
region_bnd: ast::NodeId)
-> @FnCtxt {
// It's kind of a kludge to manufacture a fake function context
// and statement context, but we might as well do write the code only once
let param_env = ty::ParameterEnvironment { free_substs: substs::empty(),
self_param_bound: None,
type_param_bounds: ~[] };
@FnCtxt {
err_count_on_creation: ccx.tcx.sess.err_count(),
ret_ty: rty,
ps: RefCell::new(PurityState::function(ast::ImpureFn, 0)),
region_lb: Cell::new(region_bnd),
fn_kind: Vanilla,
inh: @Inherited::new(ccx.tcx, param_env),
ccx: ccx
}
}
impl ExprTyProvider for FnCtxt {
fn expr_ty(&self, ex: &ast::Expr) -> ty::t {
self.expr_ty(ex)
}
fn ty_ctxt(&self) -> ty::ctxt {
self.ccx.tcx
}
}
struct CheckItemTypesVisitor { ccx: @CrateCtxt }
impl Visitor<()> for CheckItemTypesVisitor {
fn visit_item(&mut self, i: &ast::Item, _: ()) {
check_item(self.ccx, i);
visit::walk_item(self, i, ());
}
}
pub fn check_item_types(ccx: @CrateCtxt, krate: &ast::Crate) {
let mut visit = CheckItemTypesVisitor { ccx: ccx };
visit::walk_crate(&mut visit, krate, ());
}
fn check_bare_fn(ccx: @CrateCtxt,
decl: &ast::FnDecl,
body: &ast::Block,
id: ast::NodeId,
fty: ty::t,
param_env: ty::ParameterEnvironment) {
match ty::get(fty).sty {
ty::ty_bare_fn(ref fn_ty) => {
let fcx =
check_fn(ccx, fn_ty.purity, &fn_ty.sig, decl, id, body,
Vanilla, @Inherited::new(ccx.tcx, param_env));
vtable::resolve_in_block(fcx, body);
regionck::regionck_fn(fcx, body);
writeback::resolve_type_vars_in_fn(fcx, decl, body);
}
_ => ccx.tcx.sess.impossible_case(body.span,
"check_bare_fn: function type expected")
}
}
struct GatherLocalsVisitor {
fcx: @FnCtxt,
tcx: ty::ctxt,
}
impl GatherLocalsVisitor {
fn assign(&mut self, nid: ast::NodeId, ty_opt: Option<ty::t>) {
match ty_opt {
None => {
// infer the variable's type
let var_id = self.fcx.infcx().next_ty_var_id();
let var_ty = ty::mk_var(self.fcx.tcx(), var_id);
let mut locals = self.fcx.inh.locals.borrow_mut();
locals.get().insert(nid, var_ty);
}
Some(typ) => {
// take type that the user specified
let mut locals = self.fcx.inh.locals.borrow_mut();
locals.get().insert(nid, typ);
}
}
}
}
impl Visitor<()> for GatherLocalsVisitor {
// Add explicitly-declared locals.
fn visit_local(&mut self, local: &ast::Local, _: ()) {
let o_ty = match local.ty.node {
ast::TyInfer => None,
_ => Some(self.fcx.to_ty(local.ty))
};
self.assign(local.id, o_ty);
{
let locals = self.fcx.inh.locals.borrow();
debug!("Local variable {} is assigned type {}",
self.fcx.pat_to_str(local.pat),
self.fcx.infcx().ty_to_str(
locals.get().get_copy(&local.id)));
}
visit::walk_local(self, local, ());
}
// Add pattern bindings.
fn visit_pat(&mut self, p: &ast::Pat, _: ()) {
match p.node {
ast::PatIdent(_, ref path, _)
if pat_util::pat_is_binding(self.fcx.ccx.tcx.def_map, p) => {
self.assign(p.id, None);
{
let locals = self.fcx.inh.locals.borrow();
debug!("Pattern binding {} is assigned to {}",
token::get_ident(path.segments[0].identifier),
self.fcx.infcx().ty_to_str(
locals.get().get_copy(&p.id)));
}
}
_ => {}
}
visit::walk_pat(self, p, ());
}
fn visit_block(&mut self, b: &ast::Block, _: ()) {
// non-obvious: the `blk` variable maps to region lb, so
// we have to keep this up-to-date. This
// is... unfortunate. It'd be nice to not need this.
self.fcx.with_region_lb(b.id, || visit::walk_block(self, b, ()));
}
// Don't descend into fns and items
fn visit_fn(&mut self, _: &visit::FnKind, _: &ast::FnDecl,
_: &ast::Block, _: Span, _: ast::NodeId, _: ()) { }
fn visit_item(&mut self, _: &ast::Item, _: ()) { }
}
fn check_fn(ccx: @CrateCtxt,
purity: ast::Purity,
fn_sig: &ty::FnSig,
decl: &ast::FnDecl,
id: ast::NodeId,
body: &ast::Block,
fn_kind: FnKind,
inherited: @Inherited) -> @FnCtxt
{
/*!
* Helper used by check_bare_fn and check_expr_fn. Does the
* grungy work of checking a function body and returns the
* function context used for that purpose, since in the case of a
* fn item there is still a bit more to do.
*
* - ...
* - inherited: other fields inherited from the enclosing fn (if any)
*/
let tcx = ccx.tcx;
let err_count_on_creation = tcx.sess.err_count();
// First, we have to replace any bound regions in the fn type with free ones.
// The free region references will be bound the node_id of the body block.
let (_, fn_sig) = replace_bound_regions_in_fn_sig(tcx, fn_sig, |br| {
ty::ReFree(ty::FreeRegion {scope_id: body.id, bound_region: br})
});
relate_free_regions(tcx, &fn_sig);
let arg_tys = fn_sig.inputs.as_slice();
let ret_ty = fn_sig.output;
debug!("check_fn(arg_tys={:?}, ret_ty={:?})",
arg_tys.map(|&a| ppaux::ty_to_str(tcx, a)),
ppaux::ty_to_str(tcx, ret_ty));
// Create the function context. This is either derived from scratch or,
// in the case of function expressions, based on the outer context.
let fcx = @FnCtxt {
err_count_on_creation: err_count_on_creation,
ret_ty: ret_ty,
ps: RefCell::new(PurityState::function(purity, id)),
region_lb: Cell::new(body.id),
fn_kind: fn_kind,
inh: inherited,
ccx: ccx
};
{
let mut visit = GatherLocalsVisitor { fcx: fcx, tcx: tcx, };
// Add formal parameters.
for (arg_ty, input) in arg_tys.iter().zip(decl.inputs.iter()) {
// Create type variables for each argument.
pat_util::pat_bindings(tcx.def_map,
input.pat,
|_bm, pat_id, _sp, _path| {
visit.assign(pat_id, None);
});
// Check the pattern.
let pcx = pat_ctxt {
fcx: fcx,
map: pat_id_map(tcx.def_map, input.pat),
};
_match::check_pat(&pcx, input.pat, *arg_ty);
}
visit.visit_block(body, ());
}
check_block_with_expected(fcx, body, Some(ret_ty));
// We unify the tail expr's type with the
// function result type, if there is a tail expr.
match body.expr {
Some(tail_expr) => {
// Special case: we print a special error if there appears
// to be do-block/for-loop confusion
demand::suptype_with_fn(fcx, tail_expr.span, false,
fcx.ret_ty, fcx.expr_ty(tail_expr),
|sp, e, a, s| {
fcx.report_mismatched_return_types(sp, e, a, s);
});
}
None => {}
}
for (input, arg) in decl.inputs.iter().zip(arg_tys.iter()) {
fcx.write_ty(input.id, *arg);
}
fcx
}
pub fn check_no_duplicate_fields(tcx: ty::ctxt,
fields: ~[(ast::Ident, Span)]) {
let mut field_names = HashMap::new();
for p in fields.iter() {
let (id, sp) = *p;
let orig_sp = field_names.find(&id).map(|x| *x);
match orig_sp {
Some(orig_sp) => {
tcx.sess.span_err(sp, format!("duplicate field name {} in record type declaration",
token::get_ident(id)));
tcx.sess.span_note(orig_sp, "first declaration of this field occurred here");
break;
}
None => {
field_names.insert(id, sp);
}
}
}
}
pub fn check_struct(ccx: @CrateCtxt, id: ast::NodeId, span: Span) {
let tcx = ccx.tcx;
// Check that the struct is representable
check_representable(tcx, span, id, "struct");
// Check that the struct is instantiable
check_instantiable(tcx, span, id);
if ty::lookup_simd(tcx, local_def(id)) {
check_simd(tcx, span, id);
}
}
pub fn check_item(ccx: @CrateCtxt, it: &ast::Item) {
debug!("check_item(it.id={}, it.ident={})",
it.id,
ty::item_path_str(ccx.tcx, local_def(it.id)));
let _indenter = indenter();
match it.node {
ast::ItemStatic(_, _, e) => check_const(ccx, it.span, e, it.id),
ast::ItemEnum(ref enum_definition, _) => {
check_enum_variants(ccx,
it.span,
enum_definition.variants,
it.id);
}
ast::ItemFn(decl, _, _, _, body) => {
let fn_tpt = ty::lookup_item_type(ccx.tcx, ast_util::local_def(it.id));
// FIXME(#5121) -- won't work for lifetimes that appear in type bounds
let param_env = ty::construct_parameter_environment(
ccx.tcx,
None,
fn_tpt.generics.type_param_defs(),
[],
[],
body.id);
check_bare_fn(ccx, decl, body, it.id, fn_tpt.ty, param_env);
}
ast::ItemImpl(_, ref opt_trait_ref, _, ref ms) => {
debug!("ItemImpl {} with id {}", token::get_ident(it.ident), it.id);
let impl_tpt = ty::lookup_item_type(ccx.tcx, ast_util::local_def(it.id));
for m in ms.iter() {
check_method_body(ccx, &impl_tpt.generics, None, *m);
}
match *opt_trait_ref {
Some(ref ast_trait_ref) => {
let impl_trait_ref =
ty::node_id_to_trait_ref(ccx.tcx, ast_trait_ref.ref_id);
check_impl_methods_against_trait(ccx,
it.span,
&impl_tpt.generics,
ast_trait_ref,
impl_trait_ref,
*ms);
vtable::resolve_impl(ccx.tcx, it, &impl_tpt.generics, impl_trait_ref);
}
None => { }
}
}
ast::ItemTrait(_, _, ref trait_methods) => {
let trait_def = ty::lookup_trait_def(ccx.tcx, local_def(it.id));
for trait_method in (*trait_methods).iter() {
match *trait_method {
Required(..) => {
// Nothing to do, since required methods don't have
// bodies to check.
}
Provided(m) => {
check_method_body(ccx, &trait_def.generics,
Some(trait_def.trait_ref), m);
}
}
}
}
ast::ItemStruct(..) => {
check_struct(ccx, it.id, it.span);
}
ast::ItemTy(ref t, ref generics) => {
let tpt_ty = ty::node_id_to_type(ccx.tcx, it.id);
check_bounds_are_used(ccx, t.span, &generics.ty_params, tpt_ty);
}
ast::ItemForeignMod(ref m) => {
if m.abis.is_intrinsic() {
for item in m.items.iter() {
check_intrinsic_type(ccx, *item);
}
} else {
for item in m.items.iter() {
let tpt = ty::lookup_item_type(ccx.tcx, local_def(item.id));
if tpt.generics.has_type_params() {
ccx.tcx.sess.span_err(item.span, "foreign items may not have type parameters");
}
match item.node {
ast::ForeignItemFn(ref fn_decl, _) => {
if fn_decl.variadic && !m.abis.is_c() {
ccx.tcx.sess.span_err(
item.span, "variadic function must have C calling convention");
}
}
_ => {}
}
}
}
}
_ => {/* nothing to do */ }
}
}
fn check_method_body(ccx: @CrateCtxt,
item_generics: &ty::Generics,
self_bound: Option<@ty::TraitRef>,
method: &ast::Method) {
/*!
* Type checks a method body.
*
* # Parameters
* - `item_generics`: generics defined on the impl/trait that contains
* the method
* - `self_bound`: bound for the `Self` type parameter, if any
* - `method`: the method definition
*/
debug!("check_method_body(item_generics={}, \
self_bound={}, \
method.id={})",
item_generics.repr(ccx.tcx),
self_bound.repr(ccx.tcx),
method.id);
let method_def_id = local_def(method.id);
let method_ty = ty::method(ccx.tcx, method_def_id);
let method_generics = &method_ty.generics;
let param_env =
ty::construct_parameter_environment(
ccx.tcx,
self_bound,
item_generics.type_param_defs(),
method_generics.type_param_defs(),
item_generics.region_param_defs(),
method.body.id);
// Compute the fty from point of view of inside fn
let fty = ty::node_id_to_type(ccx.tcx, method.id);
let fty = fty.subst(ccx.tcx, ¶m_env.free_substs);
check_bare_fn(ccx, method.decl, method.body, method.id, fty, param_env);
}
fn check_impl_methods_against_trait(ccx: @CrateCtxt,
impl_span: Span,
impl_generics: &ty::Generics,
ast_trait_ref: &ast::TraitRef,
impl_trait_ref: &ty::TraitRef,
impl_methods: &[@ast::Method]) {
// Locate trait methods
let tcx = ccx.tcx;
let trait_methods = ty::trait_methods(tcx, impl_trait_ref.def_id);
// Check existing impl methods to see if they are both present in trait
// and compatible with trait signature
for impl_method in impl_methods.iter() {
let impl_method_def_id = local_def(impl_method.id);
let impl_method_ty = ty::method(ccx.tcx, impl_method_def_id);
// If this is an impl of a trait method, find the corresponding
// method definition in the trait.
let opt_trait_method_ty =
trait_methods.iter().
find(|tm| tm.ident.name == impl_method_ty.ident.name);
match opt_trait_method_ty {
Some(trait_method_ty) => {
compare_impl_method(ccx.tcx,
impl_generics,
impl_method_ty,
impl_method.span,
impl_method.body.id,
*trait_method_ty,
&impl_trait_ref.substs);
}
None => {
tcx.sess.span_err(
impl_method.span,
format!("method `{}` is not a member of trait `{}`",
token::get_ident(impl_method_ty.ident),
pprust::path_to_str(&ast_trait_ref.path)));
}
}
}
// Check for missing methods from trait
let provided_methods = ty::provided_trait_methods(tcx,
impl_trait_ref.def_id);
let mut missing_methods = ~[];
for trait_method in trait_methods.iter() {
let is_implemented =
impl_methods.iter().any(
|m| m.ident.name == trait_method.ident.name);
let is_provided =
provided_methods.iter().any(
|m| m.ident.name == trait_method.ident.name);
if !is_implemented && !is_provided {
missing_methods.push(
format!("`{}`", token::get_ident(trait_method.ident)));
}
}
if !missing_methods.is_empty() {
tcx.sess.span_err(
impl_span,
format!("not all trait methods implemented, missing: {}",
missing_methods.connect(", ")));
}
}
/**
* Checks that a method from an impl/class conforms to the signature of
* the same method as declared in the trait.
*
* # Parameters
*
* - impl_generics: the generics declared on the impl itself (not the method!)
* - impl_m: type of the method we are checking
* - impl_m_span: span to use for reporting errors
* - impl_m_body_id: id of the method body
* - trait_m: the method in the trait
* - trait_substs: the substitutions used on the type of the trait
*/
fn compare_impl_method(tcx: ty::ctxt,
impl_generics: &ty::Generics,
impl_m: @ty::Method,
impl_m_span: Span,
impl_m_body_id: ast::NodeId,
trait_m: &ty::Method,
trait_substs: &ty::substs) {
debug!("compare_impl_method()");
let infcx = infer::new_infer_ctxt(tcx);
let impl_tps = impl_generics.type_param_defs().len();
// Try to give more informative error messages about self typing
// mismatches. Note that any mismatch will also be detected
// below, where we construct a canonical function type that
// includes the self parameter as a normal parameter. It's just
// that the error messages you get out of this code are a bit more
// inscrutable, particularly for cases where one method has no
// self.
match (&trait_m.explicit_self, &impl_m.explicit_self) {
(&ast::SelfStatic, &ast::SelfStatic) => {}
(&ast::SelfStatic, _) => {
tcx.sess.span_err(
impl_m_span,
format!("method `{}` has a `{}` declaration in the impl, \
but not in the trait",
token::get_ident(trait_m.ident),
pprust::explicit_self_to_str(&impl_m.explicit_self)));
return;
}
(_, &ast::SelfStatic) => {
tcx.sess.span_err(
impl_m_span,
format!("method `{}` has a `{}` declaration in the trait, \
but not in the impl",
token::get_ident(trait_m.ident),
pprust::explicit_self_to_str(&trait_m.explicit_self)));
return;
}
_ => {
// Let the type checker catch other errors below
}
}
let num_impl_m_type_params = impl_m.generics.type_param_defs().len();
let num_trait_m_type_params = trait_m.generics.type_param_defs().len();
if num_impl_m_type_params != num_trait_m_type_params {
tcx.sess.span_err(
impl_m_span,
format!("method `{}` has {} type parameter(s), but its trait \
declaration has {} type parameter(s)",
token::get_ident(trait_m.ident),
num_impl_m_type_params,
num_trait_m_type_params));
return;
}
if impl_m.fty.sig.inputs.len() != trait_m.fty.sig.inputs.len() {
tcx.sess.span_err(
impl_m_span,
format!("method `{}` has {} parameter{} \
but the declaration in trait `{}` has {}",
token::get_ident(trait_m.ident),
impl_m.fty.sig.inputs.len(),
if impl_m.fty.sig.inputs.len() == 1 { "" } else { "s" },
ty::item_path_str(tcx, trait_m.def_id),
trait_m.fty.sig.inputs.len()));
return;
}
let it = trait_m.generics.type_param_defs().iter()
.zip(impl_m.generics.type_param_defs().iter());
for (i, (trait_param_def, impl_param_def)) in it.enumerate() {
// Check that the impl does not require any builtin-bounds
// that the trait does not guarantee:
let extra_bounds =
impl_param_def.bounds.builtin_bounds -
trait_param_def.bounds.builtin_bounds;
if !extra_bounds.is_empty() {
tcx.sess.span_err(
impl_m_span,
format!("in method `{}`, \
type parameter {} requires `{}`, \
which is not required by \
the corresponding type parameter \
in the trait declaration",
token::get_ident(trait_m.ident),
i,
extra_bounds.user_string(tcx)));
return;
}
// FIXME(#2687)---we should be checking that the bounds of the
// trait imply the bounds of the subtype, but it appears we
// are...not checking this.
if impl_param_def.bounds.trait_bounds.len() !=
trait_param_def.bounds.trait_bounds.len()
{
tcx.sess.span_err(
impl_m_span,
format!("in method `{}`, \
type parameter {} has {} trait bound(s), but the \
corresponding type parameter in \
the trait declaration has {} trait bound(s)",
token::get_ident(trait_m.ident),
i, impl_param_def.bounds.trait_bounds.len(),
trait_param_def.bounds.trait_bounds.len()));
return;
}
}
// Create a substitution that maps the type parameters on the impl
// to themselves and which replace any references to bound regions
// in the self type with free regions. So, for example, if the
// impl type is "&'a str", then this would replace the self
// type with a free region `self`.
let dummy_impl_tps: ~[ty::t] =
impl_generics.type_param_defs().iter().enumerate().
map(|(i,t)| ty::mk_param(tcx, i, t.def_id)).
collect();
let dummy_method_tps: ~[ty::t] =
impl_m.generics.type_param_defs().iter().enumerate().
map(|(i,t)| ty::mk_param(tcx, i + impl_tps, t.def_id)).
collect();
let dummy_impl_regions: OptVec<ty::Region> =
impl_generics.region_param_defs().iter().
map(|l| ty::ReFree(ty::FreeRegion {
scope_id: impl_m_body_id,
bound_region: ty::BrNamed(l.def_id, l.ident)})).
collect();
let dummy_substs = ty::substs {
tps: vec::append(dummy_impl_tps, dummy_method_tps),
regions: ty::NonerasedRegions(dummy_impl_regions),
self_ty: None };
// Create a bare fn type for trait/impl
// It'd be nice to refactor so as to provide the bare fn types instead.
let trait_fty = ty::mk_bare_fn(tcx, trait_m.fty.clone());
let impl_fty = ty::mk_bare_fn(tcx, impl_m.fty.clone());
// Perform substitutions so that the trait/impl methods are expressed
// in terms of the same set of type/region parameters:
// - replace trait type parameters with those from `trait_substs`,
// except with any reference to bound self replaced with `dummy_self_r`
// - replace method parameters on the trait with fresh, dummy parameters
// that correspond to the parameters we will find on the impl
// - replace self region with a fresh, dummy region
let impl_fty = {
debug!("impl_fty (pre-subst): {}", ppaux::ty_to_str(tcx, impl_fty));
impl_fty.subst(tcx, &dummy_substs)
};
debug!("impl_fty (post-subst): {}", ppaux::ty_to_str(tcx, impl_fty));
let trait_fty = {
let substs { regions: trait_regions,
tps: trait_tps,
self_ty: self_ty } = trait_substs.subst(tcx, &dummy_substs);
let substs = substs {
regions: trait_regions,
tps: vec::append(trait_tps, dummy_method_tps),
self_ty: self_ty,
};
debug!("trait_fty (pre-subst): {} substs={}",
trait_fty.repr(tcx), substs.repr(tcx));
trait_fty.subst(tcx, &substs)
};
debug!("trait_fty (post-subst): {}", trait_fty.repr(tcx));
match infer::mk_subty(&infcx, false, infer::MethodCompatCheck(impl_m_span),
impl_fty, trait_fty) {
result::Ok(()) => {}
result::Err(ref terr) => {
tcx.sess.span_err(
impl_m_span,
format!("method `{}` has an incompatible type: {}",
token::get_ident(trait_m.ident),
ty::type_err_to_str(tcx, terr)));
ty::note_and_explain_type_err(tcx, terr);
}
}
}
impl AstConv for FnCtxt {
fn tcx(&self) -> ty::ctxt { self.ccx.tcx }
fn get_item_ty(&self, id: ast::DefId) -> ty::ty_param_bounds_and_ty {
ty::lookup_item_type(self.tcx(), id)
}
fn get_trait_def(&self, id: ast::DefId) -> @ty::TraitDef {
ty::lookup_trait_def(self.tcx(), id)
}
fn ty_infer(&self, _span: Span) -> ty::t {
self.infcx().next_ty_var()
}
}
impl FnCtxt {
pub fn infcx<'a>(&'a self) -> &'a infer::InferCtxt {
&self.inh.infcx
}
pub fn err_count_since_creation(&self) -> uint {
self.ccx.tcx.sess.err_count() - self.err_count_on_creation
}
pub fn vtable_context<'a>(&'a self) -> VtableContext<'a> {
VtableContext {
infcx: self.infcx(),
param_env: &self.inh.param_env
}
}
}
impl RegionScope for infer::InferCtxt {
fn anon_regions(&self, span: Span, count: uint)
-> Result<~[ty::Region], ()> {
Ok(vec::from_fn(count, |_| {
self.next_region_var(infer::MiscVariable(span))
}))
}
}
impl FnCtxt {
pub fn tag(&self) -> ~str {
format!("{}", self as *FnCtxt)
}
pub fn local_ty(&self, span: Span, nid: ast::NodeId) -> ty::t {
let locals = self.inh.locals.borrow();
match locals.get().find(&nid) {
Some(&t) => t,
None => {