-
Notifications
You must be signed in to change notification settings - Fork 12.8k
/
fulfill.rs
551 lines (488 loc) · 21.4 KB
/
fulfill.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
// Copyright 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.
use middle::infer::InferCtxt;
use middle::ty::{self, RegionEscape, Ty, HasTypeFlags};
use syntax::ast;
use util::common::ErrorReported;
use util::nodemap::{FnvHashSet, NodeMap};
use super::CodeAmbiguity;
use super::CodeProjectionError;
use super::CodeSelectionError;
use super::is_object_safe;
use super::FulfillmentError;
use super::ObligationCause;
use super::ObligationCauseCode;
use super::PredicateObligation;
use super::project;
use super::RFC1214Warning;
use super::select::SelectionContext;
use super::Unimplemented;
use super::util::predicate_for_builtin_bound;
pub struct FulfilledPredicates<'tcx> {
set: FnvHashSet<(RFC1214Warning, ty::Predicate<'tcx>)>
}
/// The fulfillment context is used to drive trait resolution. It
/// consists of a list of obligations that must be (eventually)
/// satisfied. The job is to track which are satisfied, which yielded
/// errors, and which are still pending. At any point, users can call
/// `select_where_possible`, and the fulfilment context will try to do
/// selection, retaining only those obligations that remain
/// ambiguous. This may be helpful in pushing type inference
/// along. Once all type inference constraints have been generated, the
/// method `select_all_or_error` can be used to report any remaining
/// ambiguous cases as errors.
pub struct FulfillmentContext<'tcx> {
// a simple cache that aims to cache *exact duplicate obligations*
// and avoid adding them twice. This serves a different purpose
// than the `SelectionCache`: it avoids duplicate errors and
// permits recursive obligations, which are often generated from
// traits like `Send` et al.
//
// Note that because of type inference, a predicate can still
// occur twice in the predicates list, for example when 2
// initially-distinct type variables are unified after being
// inserted. Deduplicating the predicate set on selection had a
// significant performance cost the last time I checked.
duplicate_set: FulfilledPredicates<'tcx>,
// A list of all obligations that have been registered with this
// fulfillment context.
predicates: Vec<PredicateObligation<'tcx>>,
// Remembers the count of trait obligations that we have already
// attempted to select. This is used to avoid repeating work
// when `select_new_obligations` is called.
attempted_mark: usize,
// A set of constraints that regionck must validate. Each
// constraint has the form `T:'a`, meaning "some type `T` must
// outlive the lifetime 'a". These constraints derive from
// instantiated type parameters. So if you had a struct defined
// like
//
// struct Foo<T:'static> { ... }
//
// then in some expression `let x = Foo { ... }` it will
// instantiate the type parameter `T` with a fresh type `$0`. At
// the same time, it will record a region obligation of
// `$0:'static`. This will get checked later by regionck. (We
// can't generally check these things right away because we have
// to wait until types are resolved.)
//
// These are stored in a map keyed to the id of the innermost
// enclosing fn body / static initializer expression. This is
// because the location where the obligation was incurred can be
// relevant with respect to which sublifetime assumptions are in
// place. The reason that we store under the fn-id, and not
// something more fine-grained, is so that it is easier for
// regionck to be sure that it has found *all* the region
// obligations (otherwise, it's easy to fail to walk to a
// particular node-id).
region_obligations: NodeMap<Vec<RegionObligation<'tcx>>>,
pub errors_will_be_reported: bool,
}
#[derive(Clone)]
pub struct RegionObligation<'tcx> {
pub sub_region: ty::Region,
pub sup_type: Ty<'tcx>,
pub cause: ObligationCause<'tcx>,
}
impl<'tcx> FulfillmentContext<'tcx> {
/// Creates a new fulfillment context.
///
/// `errors_will_be_reported` indicates whether ALL errors that
/// are generated by this fulfillment context will be reported to
/// the end user. This is used to inform caching, because it
/// allows us to conclude that traits that resolve successfully
/// will in fact always resolve successfully (in particular, it
/// guarantees that if some dependent obligation encounters a
/// problem, compilation will be aborted). If you're not sure of
/// the right value here, pass `false`, as that is the more
/// conservative option.
///
/// FIXME -- a better option would be to hold back on modifying
/// the global cache until we know that all dependent obligations
/// are also satisfied. In that case, we could actually remove
/// this boolean flag, and we'd also avoid the problem of squelching
/// duplicate errors that occur across fns.
pub fn new(errors_will_be_reported: bool) -> FulfillmentContext<'tcx> {
FulfillmentContext {
duplicate_set: FulfilledPredicates::new(),
predicates: Vec::new(),
attempted_mark: 0,
region_obligations: NodeMap(),
errors_will_be_reported: errors_will_be_reported,
}
}
/// "Normalize" a projection type `<SomeType as SomeTrait>::X` by
/// creating a fresh type variable `$0` as well as a projection
/// predicate `<SomeType as SomeTrait>::X == $0`. When the
/// inference engine runs, it will attempt to find an impl of
/// `SomeTrait` or a where clause that lets us unify `$0` with
/// something concrete. If this fails, we'll unify `$0` with
/// `projection_ty` again.
pub fn normalize_projection_type<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
projection_ty: ty::ProjectionTy<'tcx>,
cause: ObligationCause<'tcx>)
-> Ty<'tcx>
{
debug!("normalize_associated_type(projection_ty={:?})",
projection_ty);
assert!(!projection_ty.has_escaping_regions());
// FIXME(#20304) -- cache
let mut selcx = SelectionContext::new(infcx);
let normalized = project::normalize_projection_type(&mut selcx, projection_ty, cause, 0);
for obligation in normalized.obligations {
self.register_predicate_obligation(infcx, obligation);
}
debug!("normalize_associated_type: result={:?}", normalized.value);
normalized.value
}
pub fn register_builtin_bound<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
ty: Ty<'tcx>,
builtin_bound: ty::BuiltinBound,
cause: ObligationCause<'tcx>)
{
match predicate_for_builtin_bound(infcx.tcx, cause, builtin_bound, 0, ty) {
Ok(predicate) => {
self.register_predicate_obligation(infcx, predicate);
}
Err(ErrorReported) => { }
}
}
pub fn register_region_obligation<'a>(&mut self,
t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>)
{
register_region_obligation(t_a, r_b, cause, &mut self.region_obligations);
}
pub fn register_predicate_obligation<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>,
obligation: PredicateObligation<'tcx>)
{
// this helps to reduce duplicate errors, as well as making
// debug output much nicer to read and so on.
let obligation = infcx.resolve_type_vars_if_possible(&obligation);
assert!(!obligation.has_escaping_regions());
let w = RFC1214Warning(obligation.cause.code.is_rfc1214());
if self.is_duplicate_or_add(infcx.tcx, w, &obligation.predicate) {
debug!("register_predicate({:?}) -- already seen, skip", obligation);
return;
}
debug!("register_predicate({:?})", obligation);
self.predicates.push(obligation);
}
pub fn region_obligations(&self,
body_id: ast::NodeId)
-> &[RegionObligation<'tcx>]
{
match self.region_obligations.get(&body_id) {
None => Default::default(),
Some(vec) => vec,
}
}
pub fn select_all_or_error<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
try!(self.select_where_possible(infcx));
// Anything left is ambiguous.
let errors: Vec<FulfillmentError> =
self.predicates
.iter()
.map(|o| FulfillmentError::new((*o).clone(), CodeAmbiguity))
.collect();
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
/// Attempts to select obligations that were registered since the call to a selection routine.
/// This is used by the type checker to eagerly attempt to resolve obligations in hopes of
/// gaining type information. It'd be equally valid to use `select_where_possible` but it
/// results in `O(n^2)` performance (#18208).
pub fn select_new_obligations<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx);
self.select(&mut selcx, true)
}
pub fn select_where_possible<'a>(&mut self,
infcx: &InferCtxt<'a,'tcx>)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
let mut selcx = SelectionContext::new(infcx);
self.select(&mut selcx, false)
}
pub fn pending_obligations(&self) -> &[PredicateObligation<'tcx>] {
&self.predicates
}
fn is_duplicate_or_add(&mut self,
tcx: &ty::ctxt<'tcx>,
w: RFC1214Warning,
predicate: &ty::Predicate<'tcx>)
-> bool {
// This is a kind of dirty hack to allow us to avoid "rederiving"
// things that we have already proven in other methods.
//
// The idea is that any predicate that doesn't involve type
// parameters and which only involves the 'static region (and
// no other regions) is universally solvable, since impls are global.
//
// This is particularly important since even if we have a
// cache hit in the selection context, we still wind up
// evaluating the 'nested obligations'. This cache lets us
// skip those.
let will_warn_due_to_rfc1214 = w.0;
let errors_will_be_reported = self.errors_will_be_reported && !will_warn_due_to_rfc1214;
if errors_will_be_reported && predicate.is_global() {
tcx.fulfilled_predicates.borrow_mut().is_duplicate_or_add(w, predicate)
} else {
self.duplicate_set.is_duplicate_or_add(w, predicate)
}
}
/// Attempts to select obligations using `selcx`. If `only_new_obligations` is true, then it
/// only attempts to select obligations that haven't been seen before.
fn select<'a>(&mut self,
selcx: &mut SelectionContext<'a, 'tcx>,
only_new_obligations: bool)
-> Result<(),Vec<FulfillmentError<'tcx>>>
{
debug!("select({} obligations, only_new_obligations={}) start",
self.predicates.len(),
only_new_obligations);
let mut errors = Vec::new();
loop {
let count = self.predicates.len();
debug!("select_where_possible({} obligations) iteration",
count);
let mut new_obligations = Vec::new();
// If we are only attempting obligations we haven't seen yet,
// then set `skip` to the number of obligations we've already
// seen.
let mut skip = if only_new_obligations {
self.attempted_mark
} else {
0
};
// First pass: walk each obligation, retaining
// only those that we cannot yet process.
{
let region_obligations = &mut self.region_obligations;
self.predicates.retain(|predicate| {
// Hack: Retain does not pass in the index, but we want
// to avoid processing the first `start_count` entries.
let processed =
if skip == 0 {
process_predicate(selcx, predicate,
&mut new_obligations, &mut errors, region_obligations)
} else {
skip -= 1;
false
};
!processed
});
}
self.attempted_mark = self.predicates.len();
if self.predicates.len() == count {
// Nothing changed.
break;
}
// Now go through all the successful ones,
// registering any nested obligations for the future.
for new_obligation in new_obligations {
self.register_predicate_obligation(selcx.infcx(), new_obligation);
}
}
debug!("select({} obligations, {} errors) done",
self.predicates.len(),
errors.len());
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
fn process_predicate<'a,'tcx>(selcx: &mut SelectionContext<'a,'tcx>,
obligation: &PredicateObligation<'tcx>,
new_obligations: &mut Vec<PredicateObligation<'tcx>>,
errors: &mut Vec<FulfillmentError<'tcx>>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
-> bool
{
/*!
* Processes a predicate obligation and modifies the appropriate
* output array with the successful/error result. Returns `false`
* if the predicate could not be processed due to insufficient
* type inference.
*/
match obligation.predicate {
ty::Predicate::Trait(ref data) => {
let trait_obligation = obligation.with(data.clone());
match selcx.select(&trait_obligation) {
Ok(None) => {
false
}
Ok(Some(s)) => {
new_obligations.append(&mut s.nested_obligations());
true
}
Err(selection_err) => {
debug!("predicate: {:?} error: {:?}",
obligation,
selection_err);
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(selection_err)));
true
}
}
}
ty::Predicate::Equate(ref binder) => {
match selcx.infcx().equality_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::RegionOutlives(ref binder) => {
match selcx.infcx().region_outlives_predicate(obligation.cause.span, binder) {
Ok(()) => { }
Err(_) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
}
true
}
ty::Predicate::TypeOutlives(ref binder) => {
// Check if there are higher-ranked regions.
match selcx.tcx().no_late_bound_regions(binder) {
// If there are, inspect the underlying type further.
None => {
// Convert from `Binder<OutlivesPredicate<Ty, Region>>` to `Binder<Ty>`.
let binder = binder.map_bound_ref(|pred| pred.0);
// Check if the type has any bound regions.
match selcx.tcx().no_late_bound_regions(&binder) {
// If so, this obligation is an error (for now). Eventually we should be
// able to support additional cases here, like `for<'a> &'a str: 'a`.
None => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)))
}
// Otherwise, we have something of the form
// `for<'a> T: 'a where 'a not in T`, which we can treat as `T: 'static`.
Some(t_a) => {
register_region_obligation(t_a, ty::ReStatic,
obligation.cause.clone(),
region_obligations);
}
}
}
// If there aren't, register the obligation.
Some(ty::OutlivesPredicate(t_a, r_b)) => {
register_region_obligation(t_a, r_b,
obligation.cause.clone(),
region_obligations);
}
}
true
}
ty::Predicate::Projection(ref data) => {
let project_obligation = obligation.with(data.clone());
let result = project::poly_project_and_unify_type(selcx, &project_obligation);
debug!("process_predicate: poly_project_and_unify_type({:?}) returned {:?}",
project_obligation,
result);
match result {
Ok(Some(obligations)) => {
new_obligations.extend(obligations);
true
}
Ok(None) => {
false
}
Err(err) => {
errors.push(
FulfillmentError::new(
obligation.clone(),
CodeProjectionError(err)));
true
}
}
}
ty::Predicate::ObjectSafe(trait_def_id) => {
if !is_object_safe(selcx.tcx(), trait_def_id) {
errors.push(FulfillmentError::new(
obligation.clone(),
CodeSelectionError(Unimplemented)));
}
true
}
ty::Predicate::WellFormed(ty) => {
let rfc1214 = match obligation.cause.code {
ObligationCauseCode::RFC1214(_) => true,
_ => false,
};
match ty::wf::obligations(selcx.infcx(), obligation.cause.body_id,
ty, obligation.cause.span, rfc1214) {
Some(obligations) => {
new_obligations.extend(obligations);
true
}
None => {
false
}
}
}
}
}
fn register_region_obligation<'tcx>(t_a: Ty<'tcx>,
r_b: ty::Region,
cause: ObligationCause<'tcx>,
region_obligations: &mut NodeMap<Vec<RegionObligation<'tcx>>>)
{
let region_obligation = RegionObligation { sup_type: t_a,
sub_region: r_b,
cause: cause };
debug!("register_region_obligation({:?}, cause={:?})",
region_obligation, region_obligation.cause);
region_obligations.entry(region_obligation.cause.body_id)
.or_insert(vec![])
.push(region_obligation);
}
impl<'tcx> FulfilledPredicates<'tcx> {
pub fn new() -> FulfilledPredicates<'tcx> {
FulfilledPredicates {
set: FnvHashSet()
}
}
pub fn is_duplicate(&self, w: RFC1214Warning, p: &ty::Predicate<'tcx>) -> bool {
let key = (w, p.clone());
self.set.contains(&key)
}
fn is_duplicate_or_add(&mut self, w: RFC1214Warning, p: &ty::Predicate<'tcx>) -> bool {
let key = (w, p.clone());
!self.set.insert(key)
}
}