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
use metadata::csearch::{each_impl, get_impl_trait};
use metadata::csearch;
use middle::subst::{self, Subst};
use middle::ty::RegionEscape;
use middle::ty::{ImplContainer, ImplOrTraitItemId, MethodTraitItemId};
use middle::ty::{ParameterEnvironment, TypeTraitItemId, lookup_item_type};
use middle::ty::{Ty, ty_bool, ty_char, ty_enum, ty_err};
use middle::ty::{ty_param, TypeScheme, ty_ptr};
use middle::ty::{ty_rptr, ty_struct, ty_trait, ty_tup};
use middle::ty::{ty_str, ty_vec, ty_float, ty_infer, ty_int};
use middle::ty::{ty_uint, ty_closure, ty_uniq, ty_bare_fn};
use middle::ty::ty_projection;
use middle::ty;
use CrateCtxt;
use middle::infer::InferCtxt;
use middle::infer::new_infer_ctxt;
use std::collections::HashSet;
use std::cell::RefCell;
use std::rc::Rc;
use syntax::ast::{Crate, DefId};
use syntax::ast::{Item, ItemImpl};
use syntax::ast::{LOCAL_CRATE, TraitRef};
use syntax::ast;
use syntax::ast_map::NodeItem;
use syntax::ast_map;
use syntax::ast_util::local_def;
use syntax::codemap::Span;
use syntax::parse::token;
use syntax::visit;
use util::nodemap::{DefIdMap, FnvHashMap};
use util::ppaux::Repr;
mod orphan;
mod overlap;
mod unsafety;
fn get_base_type_def_id<'a, 'tcx>(inference_context: &InferCtxt<'a, 'tcx>,
span: Span,
ty: Ty<'tcx>)
-> Option<DefId> {
match ty.sty {
ty_enum(def_id, _) |
ty_struct(def_id, _) => {
Some(def_id)
}
ty_trait(ref t) => {
Some(t.principal_def_id())
}
ty_uniq(_) => {
inference_context.tcx.lang_items.owned_box()
}
ty_bool | ty_char | ty_int(..) | ty_uint(..) | ty_float(..) |
ty_str(..) | ty_vec(..) | ty_bare_fn(..) | ty_tup(..) |
ty_param(..) | ty_err |
ty_ptr(_) | ty_rptr(_, _) | ty_projection(..) => {
None
}
ty_infer(..) | ty_closure(..) => {
inference_context.tcx.sess.span_bug(
span,
&format!("coherence encountered unexpected type searching for base type: {}",
ty.repr(inference_context.tcx)));
}
}
}
struct CoherenceChecker<'a, 'tcx: 'a> {
crate_context: &'a CrateCtxt<'a, 'tcx>,
inference_context: InferCtxt<'a, 'tcx>,
inherent_impls: RefCell<DefIdMap<Rc<RefCell<Vec<ast::DefId>>>>>,
}
struct CoherenceCheckVisitor<'a, 'tcx: 'a> {
cc: &'a CoherenceChecker<'a, 'tcx>
}
impl<'a, 'tcx, 'v> visit::Visitor<'v> for CoherenceCheckVisitor<'a, 'tcx> {
fn visit_item(&mut self, item: &Item) {
if let ItemImpl(_, _, _, ref opt_trait, _, _) = item.node {
self.cc.check_implementation(item, opt_trait.as_ref())
}
visit::walk_item(self, item);
}
}
impl<'a, 'tcx> CoherenceChecker<'a, 'tcx> {
fn check(&self, krate: &Crate) {
let mut visitor = CoherenceCheckVisitor { cc: self };
visit::walk_crate(&mut visitor, krate);
let mut tcx_inherent_impls =
self.crate_context.tcx.inherent_impls.borrow_mut();
for (k, v) in &*self.inherent_impls.borrow() {
tcx_inherent_impls.insert((*k).clone(),
Rc::new((*v.borrow()).clone()));
}
self.add_external_crates();
self.populate_destructor_table();
self.check_implementations_of_copy();
}
fn check_implementation(&self, item: &Item, opt_trait: Option<&TraitRef>) {
let tcx = self.crate_context.tcx;
let impl_did = local_def(item.id);
let self_type = ty::lookup_item_type(tcx, impl_did);
let impl_items = self.create_impl_from_item(item);
if opt_trait.is_some() {
let trait_ref = ty::impl_id_to_trait_ref(self.crate_context.tcx, item.id);
debug!("(checking implementation) adding impl for trait '{}', item '{}'",
trait_ref.repr(self.crate_context.tcx),
token::get_ident(item.ident));
enforce_trait_manually_implementable(self.crate_context.tcx,
item.span,
trait_ref.def_id);
self.add_trait_impl(trait_ref.def_id, impl_did);
}
match get_base_type_def_id(&self.inference_context,
item.span,
self_type.ty) {
None => {
}
Some(base_type_def_id) => {
if opt_trait.is_none() {
self.add_inherent_impl(base_type_def_id, impl_did);
}
}
}
tcx.impl_items.borrow_mut().insert(impl_did, impl_items);
}
fn instantiate_default_methods(
&self,
impl_id: DefId,
trait_ref: &ty::TraitRef<'tcx>,
all_impl_items: &mut Vec<ImplOrTraitItemId>) {
let tcx = self.crate_context.tcx;
debug!("instantiate_default_methods(impl_id={:?}, trait_ref={})",
impl_id, trait_ref.repr(tcx));
let impl_type_scheme = ty::lookup_item_type(tcx, impl_id);
let prov = ty::provided_trait_methods(tcx, trait_ref.def_id);
for trait_method in &prov {
let new_id = tcx.sess.next_node_id();
let new_did = local_def(new_id);
debug!("new_did={:?} trait_method={}", new_did, trait_method.repr(tcx));
let new_method_ty =
Rc::new(subst_receiver_types_in_method_ty(
tcx,
impl_id,
&impl_type_scheme,
trait_ref,
new_did,
&**trait_method,
Some(trait_method.def_id)));
debug!("new_method_ty={}", new_method_ty.repr(tcx));
all_impl_items.push(MethodTraitItemId(new_did));
let new_polytype = ty::TypeScheme {
generics: new_method_ty.generics.clone(),
ty: ty::mk_bare_fn(tcx, Some(new_did),
tcx.mk_bare_fn(new_method_ty.fty.clone()))
};
debug!("new_polytype={}", new_polytype.repr(tcx));
tcx.tcache.borrow_mut().insert(new_did, new_polytype);
tcx.predicates.borrow_mut().insert(new_did, new_method_ty.predicates.clone());
tcx.impl_or_trait_items
.borrow_mut()
.insert(new_did, ty::MethodTraitItem(new_method_ty));
self.crate_context.tcx.provided_method_sources.borrow_mut()
.insert(new_did, trait_method.def_id);
}
}
fn add_inherent_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
match self.inherent_impls.borrow().get(&base_def_id) {
Some(implementation_list) => {
implementation_list.borrow_mut().push(impl_def_id);
return;
}
None => {}
}
self.inherent_impls.borrow_mut().insert(
base_def_id,
Rc::new(RefCell::new(vec!(impl_def_id))));
}
fn add_trait_impl(&self, base_def_id: DefId, impl_def_id: DefId) {
debug!("add_trait_impl: base_def_id={:?} impl_def_id={:?}",
base_def_id, impl_def_id);
ty::record_trait_implementation(self.crate_context.tcx,
base_def_id,
impl_def_id);
}
fn get_self_type_for_implementation(&self, impl_did: DefId)
-> TypeScheme<'tcx> {
self.crate_context.tcx.tcache.borrow().get(&impl_did).unwrap().clone()
}
fn create_impl_from_item(&self, item: &Item) -> Vec<ImplOrTraitItemId> {
match item.node {
ItemImpl(_, _, _, ref opt_trait, _, ref impl_items) => {
let mut items: Vec<ImplOrTraitItemId> =
impl_items.iter().map(|impl_item| {
match impl_item.node {
ast::MethodImplItem(..) => {
MethodTraitItemId(local_def(impl_item.id))
}
ast::TypeImplItem(_) => {
TypeTraitItemId(local_def(impl_item.id))
}
ast::MacImplItem(_) => {
self.crate_context.tcx.sess.span_bug(impl_item.span,
"unexpanded macro");
}
}
}).collect();
if opt_trait.is_some() {
let trait_ref = ty::impl_id_to_trait_ref(self.crate_context.tcx,
item.id);
self.instantiate_default_methods(local_def(item.id),
&*trait_ref,
&mut items);
}
items
}
_ => {
self.crate_context.tcx.sess.span_bug(item.span,
"can't convert a non-impl to an impl");
}
}
}
fn add_external_impl(&self,
impls_seen: &mut HashSet<DefId>,
impl_def_id: DefId) {
let tcx = self.crate_context.tcx;
let impl_items = csearch::get_impl_items(&tcx.sess.cstore,
impl_def_id);
if !impls_seen.insert(impl_def_id) {
return
}
let _ = lookup_item_type(tcx, impl_def_id);
let associated_traits = get_impl_trait(tcx, impl_def_id);
assert!(associated_traits.is_some());
if let Some(trait_ref) = associated_traits {
self.add_trait_impl(trait_ref.def_id, impl_def_id);
}
for item_def_id in &impl_items {
let impl_item = ty::impl_or_trait_item(tcx, item_def_id.def_id());
match impl_item {
ty::MethodTraitItem(ref method) => {
if let Some(source) = method.provided_source {
tcx.provided_method_sources
.borrow_mut()
.insert(item_def_id.def_id(), source);
}
}
ty::TypeTraitItem(_) => {}
}
}
tcx.impl_items.borrow_mut().insert(impl_def_id, impl_items);
}
fn add_external_crates(&self) {
let mut impls_seen = HashSet::new();
let crate_store = &self.crate_context.tcx.sess.cstore;
crate_store.iter_crate_data(|crate_number, _crate_metadata| {
each_impl(crate_store, crate_number, |def_id| {
assert_eq!(crate_number, def_id.krate);
self.add_external_impl(&mut impls_seen, def_id)
})
})
}
fn populate_destructor_table(&self) {
let tcx = self.crate_context.tcx;
let drop_trait = match tcx.lang_items.drop_trait() {
Some(id) => id, None => { return }
};
let impl_items = tcx.impl_items.borrow();
let trait_impls = match tcx.trait_impls.borrow().get(&drop_trait).cloned() {
None => return,
Some(found_impls) => found_impls
};
for &impl_did in &*trait_impls.borrow() {
let items = impl_items.get(&impl_did).unwrap();
if items.is_empty() {
continue;
}
let method_def_id = items[0];
let self_type = self.get_self_type_for_implementation(impl_did);
match self_type.ty.sty {
ty::ty_enum(type_def_id, _) |
ty::ty_struct(type_def_id, _) |
ty::ty_closure(type_def_id, _) => {
tcx.destructor_for_type
.borrow_mut()
.insert(type_def_id, method_def_id.def_id());
tcx.destructors
.borrow_mut()
.insert(method_def_id.def_id());
}
_ => {
if impl_did.krate == ast::LOCAL_CRATE {
{
match tcx.map.find(impl_did.node) {
Some(ast_map::NodeItem(item)) => {
span_err!(tcx.sess, item.span, E0120,
"the Drop trait may only be implemented on structures");
}
_ => {
tcx.sess.bug("didn't find impl in ast \
map");
}
}
}
} else {
tcx.sess.bug("found external impl of Drop trait on \
something other than a struct");
}
}
}
}
}
fn check_implementations_of_copy(&self) {
let tcx = self.crate_context.tcx;
let copy_trait = match tcx.lang_items.copy_trait() {
Some(id) => id,
None => return,
};
let trait_impls = match tcx.trait_impls
.borrow()
.get(©_trait)
.cloned() {
None => {
debug!("check_implementations_of_copy(): no types with \
implementations of `Copy` found");
return
}
Some(found_impls) => found_impls
};
let trait_impls = trait_impls.borrow().clone();
for &impl_did in &trait_impls {
debug!("check_implementations_of_copy: impl_did={}",
impl_did.repr(tcx));
if impl_did.krate != ast::LOCAL_CRATE {
debug!("check_implementations_of_copy(): impl not in this \
crate");
continue
}
let self_type = self.get_self_type_for_implementation(impl_did);
debug!("check_implementations_of_copy: self_type={} (bound)",
self_type.repr(tcx));
let span = tcx.map.span(impl_did.node);
let param_env = ParameterEnvironment::for_item(tcx, impl_did.node);
let self_type = self_type.ty.subst(tcx, ¶m_env.free_substs);
assert!(!self_type.has_escaping_regions());
debug!("check_implementations_of_copy: self_type={} (free)",
self_type.repr(tcx));
match ty::can_type_implement_copy(¶m_env, span, self_type) {
Ok(()) => {}
Err(ty::FieldDoesNotImplementCopy(name)) => {
span_err!(tcx.sess, span, E0204,
"the trait `Copy` may not be \
implemented for this type; field \
`{}` does not implement `Copy`",
token::get_name(name))
}
Err(ty::VariantDoesNotImplementCopy(name)) => {
span_err!(tcx.sess, span, E0205,
"the trait `Copy` may not be \
implemented for this type; variant \
`{}` does not implement `Copy`",
token::get_name(name))
}
Err(ty::TypeIsStructural) => {
span_err!(tcx.sess, span, E0206,
"the trait `Copy` may not be implemented \
for this type; type is not a structure or \
enumeration")
}
Err(ty::TypeHasDestructor) => {
span_err!(tcx.sess, span, E0184,
"the trait `Copy` may not be implemented for this type; \
the type has a destructor");
}
}
}
}
}
fn enforce_trait_manually_implementable(tcx: &ty::ctxt, sp: Span, trait_def_id: ast::DefId) {
if tcx.sess.features.borrow().unboxed_closures {
return
}
let did = Some(trait_def_id);
let li = &tcx.lang_items;
let trait_name = if did == li.fn_trait() {
"Fn"
} else if did == li.fn_mut_trait() {
"FnMut"
} else if did == li.fn_once_trait() {
"FnOnce"
} else {
return
};
span_err!(tcx.sess, sp, E0183, "manual implementations of `{}` are experimental", trait_name);
fileline_help!(tcx.sess, sp,
"add `#![feature(unboxed_closures)]` to the crate attributes to enable");
}
fn subst_receiver_types_in_method_ty<'tcx>(tcx: &ty::ctxt<'tcx>,
impl_id: ast::DefId,
impl_type_scheme: &ty::TypeScheme<'tcx>,
trait_ref: &ty::TraitRef<'tcx>,
new_def_id: ast::DefId,
method: &ty::Method<'tcx>,
provided_source: Option<ast::DefId>)
-> ty::Method<'tcx>
{
let combined_substs = ty::make_substs_for_receiver_types(tcx, trait_ref, method);
debug!("subst_receiver_types_in_method_ty: combined_substs={}",
combined_substs.repr(tcx));
let method_predicates = method.predicates.subst(tcx, &combined_substs);
let mut method_generics = method.generics.subst(tcx, &combined_substs);
for &space in &[subst::TypeSpace, subst::SelfSpace] {
method_generics.types.replace(
space,
impl_type_scheme.generics.types.get_slice(space).to_vec());
method_generics.regions.replace(
space,
impl_type_scheme.generics.regions.get_slice(space).to_vec());
}
debug!("subst_receiver_types_in_method_ty: method_generics={}",
method_generics.repr(tcx));
let method_fty = method.fty.subst(tcx, &combined_substs);
debug!("subst_receiver_types_in_method_ty: method_ty={}",
method.fty.repr(tcx));
ty::Method::new(
method.name,
method_generics,
method_predicates,
method_fty,
method.explicit_self,
method.vis,
new_def_id,
ImplContainer(impl_id),
provided_source
)
}
pub fn check_coherence(crate_context: &CrateCtxt) {
CoherenceChecker {
crate_context: crate_context,
inference_context: new_infer_ctxt(crate_context.tcx),
inherent_impls: RefCell::new(FnvHashMap()),
}.check(crate_context.tcx.map.krate());
unsafety::check(crate_context.tcx);
orphan::check(crate_context.tcx);
overlap::check(crate_context.tcx);
}