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
use infer;
use super::{InferCtxt, TypeTrace, SubregionOrigin, RegionVariableOrigin, ValuePairs};
use super::region_inference::{RegionResolutionError, ConcreteFailure, SubSupConflict,
GenericBoundFailure, GenericKind};
use std::fmt;
use hir;
use hir::map as hir_map;
use hir::def_id::DefId;
use middle::region;
use traits::{ObligationCause, ObligationCauseCode};
use ty::{self, TyCtxt, TypeFoldable};
use ty::{Region, Issue32330};
use ty::error::TypeError;
use syntax_pos::{Pos, Span};
use errors::DiagnosticBuilder;
mod note;
impl<'a, 'gcx, 'tcx> TyCtxt<'a, 'gcx, 'tcx> {
pub fn note_and_explain_region(self,
err: &mut DiagnosticBuilder,
prefix: &str,
region: &'tcx ty::Region,
suffix: &str) {
fn item_scope_tag(item: &hir::Item) -> &'static str {
match item.node {
hir::ItemImpl(..) => "impl",
hir::ItemStruct(..) => "struct",
hir::ItemUnion(..) => "union",
hir::ItemEnum(..) => "enum",
hir::ItemTrait(..) => "trait",
hir::ItemFn(..) => "function body",
_ => "item"
}
}
fn trait_item_scope_tag(item: &hir::TraitItem) -> &'static str {
match item.node {
hir::TraitItemKind::Method(..) => "method body",
hir::TraitItemKind::Const(..) |
hir::TraitItemKind::Type(..) => "associated item"
}
}
fn impl_item_scope_tag(item: &hir::ImplItem) -> &'static str {
match item.node {
hir::ImplItemKind::Method(..) => "method body",
hir::ImplItemKind::Const(..) |
hir::ImplItemKind::Type(_) => "associated item"
}
}
fn explain_span<'a, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
heading: &str, span: Span)
-> (String, Option<Span>) {
let lo = tcx.sess.codemap().lookup_char_pos_adj(span.lo);
(format!("the {} at {}:{}", heading, lo.line, lo.col.to_usize()),
Some(span))
}
let (description, span) = match *region {
ty::ReScope(scope) => {
let new_string;
let unknown_scope = || {
format!("{}unknown scope: {:?}{}. Please report a bug.",
prefix, scope, suffix)
};
let span = match scope.span(&self.region_maps, &self.hir) {
Some(s) => s,
None => {
err.note(&unknown_scope());
return;
}
};
let tag = match self.hir.find(scope.node_id(&self.region_maps)) {
Some(hir_map::NodeBlock(_)) => "block",
Some(hir_map::NodeExpr(expr)) => match expr.node {
hir::ExprCall(..) => "call",
hir::ExprMethodCall(..) => "method call",
hir::ExprMatch(.., hir::MatchSource::IfLetDesugar { .. }) => "if let",
hir::ExprMatch(.., hir::MatchSource::WhileLetDesugar) => "while let",
hir::ExprMatch(.., hir::MatchSource::ForLoopDesugar) => "for",
hir::ExprMatch(..) => "match",
_ => "expression",
},
Some(hir_map::NodeStmt(_)) => "statement",
Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
Some(_) | None => {
err.span_note(span, &unknown_scope());
return;
}
};
let scope_decorated_tag = match self.region_maps.code_extent_data(scope) {
region::CodeExtentData::Misc(_) => tag,
region::CodeExtentData::CallSiteScope { .. } => {
"scope of call-site for function"
}
region::CodeExtentData::ParameterScope { .. } => {
"scope of function body"
}
region::CodeExtentData::DestructionScope(_) => {
new_string = format!("destruction scope surrounding {}", tag);
&new_string[..]
}
region::CodeExtentData::Remainder(r) => {
new_string = format!("block suffix following statement {}",
r.first_statement_index);
&new_string[..]
}
};
explain_span(self, scope_decorated_tag, span)
}
ty::ReFree(ref fr) => {
let prefix = match fr.bound_region {
ty::BrAnon(idx) => {
format!("the anonymous lifetime #{} defined on", idx + 1)
}
ty::BrFresh(_) => "an anonymous lifetime defined on".to_owned(),
_ => {
format!("the lifetime {} as defined on",
fr.bound_region)
}
};
let node = fr.scope.node_id(&self.region_maps);
let unknown;
let tag = match self.hir.find(node) {
Some(hir_map::NodeBlock(_)) |
Some(hir_map::NodeExpr(_)) => "body",
Some(hir_map::NodeItem(it)) => item_scope_tag(&it),
Some(hir_map::NodeTraitItem(it)) => trait_item_scope_tag(&it),
Some(hir_map::NodeImplItem(it)) => impl_item_scope_tag(&it),
Some(_) => {
unknown = format!("unexpected node ({}) for scope {:?}. \
Please report a bug.",
self.hir.node_to_string(node), fr.scope);
&unknown
}
None => {
unknown = format!("unknown node for scope {:?}. \
Please report a bug.", fr.scope);
&unknown
}
};
let (msg, opt_span) = explain_span(self, tag, self.hir.span(node));
(format!("{} {}", prefix, msg), opt_span)
}
ty::ReStatic => ("the static lifetime".to_owned(), None),
ty::ReEmpty => ("the empty lifetime".to_owned(), None),
ty::ReEarlyBound(ref data) => (data.name.to_string(), None),
ty::ReSkolemized(..) |
ty::ReVar(_) |
ty::ReLateBound(..) |
ty::ReErased => {
(format!("lifetime {:?}", region), None)
}
};
let message = format!("{}{}{}", prefix, description, suffix);
if let Some(span) = span {
err.span_note(span, &message);
} else {
err.note(&message);
}
}
}
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
pub fn report_region_errors(&self,
errors: &Vec<RegionResolutionError<'tcx>>) {
debug!("report_region_errors(): {} errors to start", errors.len());
let errors = self.process_errors(errors);
debug!("report_region_errors: {} errors after preprocessing", errors.len());
for error in errors {
debug!("report_region_errors: error = {:?}", error);
match error.clone() {
ConcreteFailure(origin, sub, sup) => {
self.report_concrete_failure(origin, sub, sup).emit();
}
GenericBoundFailure(kind, param_ty, sub) => {
self.report_generic_bound_failure(kind, param_ty, sub);
}
SubSupConflict(var_origin,
sub_origin, sub_r,
sup_origin, sup_r) => {
self.report_sub_sup_conflict(var_origin,
sub_origin, sub_r,
sup_origin, sup_r);
}
}
}
}
fn process_errors(&self, errors: &Vec<RegionResolutionError<'tcx>>)
-> Vec<RegionResolutionError<'tcx>> {
debug!("process_errors()");
let is_bound_failure = |e: &RegionResolutionError<'tcx>| match *e {
ConcreteFailure(..) => false,
SubSupConflict(..) => false,
GenericBoundFailure(..) => true,
};
if errors.iter().all(|e| is_bound_failure(e)) {
errors.clone()
} else {
errors.iter().filter(|&e| !is_bound_failure(e)).cloned().collect()
}
}
fn check_and_note_conflicting_crates(&self,
err: &mut DiagnosticBuilder,
terr: &TypeError<'tcx>,
sp: Span) {
let report_path_match = |err: &mut DiagnosticBuilder, did1: DefId, did2: DefId| {
if !(did1.is_local() || did2.is_local()) && did1.krate != did2.krate {
let exp_path = self.tcx.item_path_str(did1);
let found_path = self.tcx.item_path_str(did2);
if exp_path == found_path {
let crate_name = self.tcx.sess.cstore.crate_name(did1.krate);
err.span_note(sp, &format!("Perhaps two different versions \
of crate `{}` are being used?",
crate_name));
}
}
};
match *terr {
TypeError::Sorts(ref exp_found) => {
match (&exp_found.expected.sty, &exp_found.found.sty) {
(&ty::TyAdt(exp_adt, _), &ty::TyAdt(found_adt, _)) => {
report_path_match(err, exp_adt.did, found_adt.did);
},
_ => ()
}
},
TypeError::Traits(ref exp_found) => {
report_path_match(err, exp_found.expected, exp_found.found);
},
_ => ()
}
}
fn note_error_origin(&self,
err: &mut DiagnosticBuilder<'tcx>,
cause: &ObligationCause<'tcx>)
{
match cause.code {
ObligationCauseCode::MatchExpressionArm { arm_span, source } => match source {
hir::MatchSource::IfLetDesugar {..} => {
err.span_note(arm_span, "`if let` arm with an incompatible type");
}
_ => {
err.span_note(arm_span, "match arm with an incompatible type");
}
},
_ => ()
}
}
pub fn note_type_err(&self,
diag: &mut DiagnosticBuilder<'tcx>,
cause: &ObligationCause<'tcx>,
secondary_span: Option<(Span, String)>,
values: Option<ValuePairs<'tcx>>,
terr: &TypeError<'tcx>)
{
let (expected_found, is_simple_error) = match values {
None => (None, false),
Some(values) => {
let is_simple_error = match values {
ValuePairs::Types(exp_found) => {
exp_found.expected.is_primitive() && exp_found.found.is_primitive()
}
_ => false,
};
let vals = match self.values_str(&values) {
Some((expected, found)) => Some((expected, found)),
None => {
self.tcx.sess.diagnostic().cancel(diag);
return
}
};
(vals, is_simple_error)
}
};
let span = cause.span;
if let Some((expected, found)) = expected_found {
match (terr, is_simple_error, expected == found) {
(&TypeError::Sorts(ref values), false, true) => {
diag.note_expected_found_extra(
&"type", &expected, &found,
&format!(" ({})", values.expected.sort_string(self.tcx)),
&format!(" ({})", values.found.sort_string(self.tcx)));
}
(_, false, _) => {
diag.note_expected_found(&"type", &expected, &found);
}
_ => (),
}
}
diag.span_label(span, &terr);
if let Some((sp, msg)) = secondary_span {
diag.span_label(sp, &msg);
}
self.note_error_origin(diag, &cause);
self.check_and_note_conflicting_crates(diag, terr, span);
self.tcx.note_and_explain_type_err(diag, terr, span);
}
pub fn note_issue_32330(&self,
diag: &mut DiagnosticBuilder<'tcx>,
terr: &TypeError<'tcx>)
{
debug!("note_issue_32330: terr={:?}", terr);
match *terr {
TypeError::RegionsInsufficientlyPolymorphic(_, _, Some(box Issue32330 {
fn_def_id, region_name
})) |
TypeError::RegionsOverlyPolymorphic(_, _, Some(box Issue32330 {
fn_def_id, region_name
})) => {
diag.note(
&format!("lifetime parameter `{0}` declared on fn `{1}` \
appears only in the return type, \
but here is required to be higher-ranked, \
which means that `{0}` must appear in both \
argument and return types",
region_name,
self.tcx.item_path_str(fn_def_id)));
diag.note(
&format!("this error is the result of a recent bug fix; \
for more information, see issue #33685 \
<https://github.com/rust-lang/rust/issues/33685>"));
}
_ => {}
}
}
pub fn report_and_explain_type_error(&self,
trace: TypeTrace<'tcx>,
terr: &TypeError<'tcx>)
-> DiagnosticBuilder<'tcx>
{
let span = trace.cause.span;
let failure_str = trace.cause.as_failure_str();
let mut diag = match trace.cause.code {
ObligationCauseCode::IfExpressionWithNoElse => {
struct_span_err!(self.tcx.sess, span, E0317, "{}", failure_str)
}
ObligationCauseCode::MainFunctionType => {
struct_span_err!(self.tcx.sess, span, E0580, "{}", failure_str)
}
_ => {
struct_span_err!(self.tcx.sess, span, E0308, "{}", failure_str)
}
};
self.note_type_err(&mut diag, &trace.cause, None, Some(trace.values), terr);
self.note_issue_32330(&mut diag, terr);
diag
}
fn values_str(&self, values: &ValuePairs<'tcx>) -> Option<(String, String)> {
match *values {
infer::Types(ref exp_found) => self.expected_found_str(exp_found),
infer::TraitRefs(ref exp_found) => self.expected_found_str(exp_found),
infer::PolyTraitRefs(ref exp_found) => self.expected_found_str(exp_found),
}
}
fn expected_found_str<T: fmt::Display + TypeFoldable<'tcx>>(
&self,
exp_found: &ty::error::ExpectedFound<T>)
-> Option<(String, String)>
{
let exp_found = self.resolve_type_vars_if_possible(exp_found);
if exp_found.references_error() {
return None;
}
Some((format!("{}", exp_found.expected), format!("{}", exp_found.found)))
}
fn report_generic_bound_failure(&self,
origin: SubregionOrigin<'tcx>,
bound_kind: GenericKind<'tcx>,
sub: &'tcx Region)
{
let labeled_user_string = match bound_kind {
GenericKind::Param(ref p) =>
format!("the parameter type `{}`", p),
GenericKind::Projection(ref p) =>
format!("the associated type `{}`", p),
};
if let SubregionOrigin::CompareImplMethodObligation {
span, item_name, impl_item_def_id, trait_item_def_id, lint_id
} = origin {
self.report_extra_impl_obligation(span,
item_name,
impl_item_def_id,
trait_item_def_id,
&format!("`{}: {}`", bound_kind, sub),
lint_id)
.emit();
return;
}
let mut err = match *sub {
ty::ReFree(ty::FreeRegion {bound_region: ty::BrNamed(..), ..}) => {
let mut err = struct_span_err!(self.tcx.sess,
origin.span(),
E0309,
"{} may not live long enough",
labeled_user_string);
err.help(&format!("consider adding an explicit lifetime bound `{}: {}`...",
bound_kind,
sub));
err
}
ty::ReStatic => {
let mut err = struct_span_err!(self.tcx.sess,
origin.span(),
E0310,
"{} may not live long enough",
labeled_user_string);
err.help(&format!("consider adding an explicit lifetime \
bound `{}: 'static`...",
bound_kind));
err
}
_ => {
let mut err = struct_span_err!(self.tcx.sess,
origin.span(),
E0311,
"{} may not live long enough",
labeled_user_string);
err.help(&format!("consider adding an explicit lifetime bound for `{}`",
bound_kind));
self.tcx.note_and_explain_region(
&mut err,
&format!("{} must be valid for ", labeled_user_string),
sub,
"...");
err
}
};
self.note_region_origin(&mut err, &origin);
err.emit();
}
fn report_sub_sup_conflict(&self,
var_origin: RegionVariableOrigin,
sub_origin: SubregionOrigin<'tcx>,
sub_region: &'tcx Region,
sup_origin: SubregionOrigin<'tcx>,
sup_region: &'tcx Region) {
let mut err = self.report_inference_failure(var_origin);
self.tcx.note_and_explain_region(&mut err,
"first, the lifetime cannot outlive ",
sup_region,
"...");
self.note_region_origin(&mut err, &sup_origin);
self.tcx.note_and_explain_region(&mut err,
"but, the lifetime must be valid for ",
sub_region,
"...");
self.note_region_origin(&mut err, &sub_origin);
err.emit();
}
}
impl<'a, 'gcx, 'tcx> InferCtxt<'a, 'gcx, 'tcx> {
fn report_inference_failure(&self,
var_origin: RegionVariableOrigin)
-> DiagnosticBuilder<'tcx> {
let br_string = |br: ty::BoundRegion| {
let mut s = br.to_string();
if !s.is_empty() {
s.push_str(" ");
}
s
};
let var_description = match var_origin {
infer::MiscVariable(_) => "".to_string(),
infer::PatternRegion(_) => " for pattern".to_string(),
infer::AddrOfRegion(_) => " for borrow expression".to_string(),
infer::Autoref(_) => " for autoref".to_string(),
infer::Coercion(_) => " for automatic coercion".to_string(),
infer::LateBoundRegion(_, br, infer::FnCall) => {
format!(" for lifetime parameter {}in function call",
br_string(br))
}
infer::LateBoundRegion(_, br, infer::HigherRankedType) => {
format!(" for lifetime parameter {}in generic type", br_string(br))
}
infer::LateBoundRegion(_, br, infer::AssocTypeProjection(type_name)) => {
format!(" for lifetime parameter {}in trait containing associated type `{}`",
br_string(br), type_name)
}
infer::EarlyBoundRegion(_, name, _) => {
format!(" for lifetime parameter `{}`",
name)
}
infer::BoundRegionInCoherence(name) => {
format!(" for lifetime parameter `{}` in coherence check",
name)
}
infer::UpvarRegion(ref upvar_id, _) => {
format!(" for capture of `{}` by closure",
self.tcx.local_var_name_str(upvar_id.var_id).to_string())
}
};
struct_span_err!(self.tcx.sess, var_origin.span(), E0495,
"cannot infer an appropriate lifetime{} \
due to conflicting requirements",
var_description)
}
}
impl<'tcx> ObligationCause<'tcx> {
fn as_failure_str(&self) -> &'static str {
use traits::ObligationCauseCode::*;
match self.code {
CompareImplMethodObligation { .. } => "method not compatible with trait",
MatchExpressionArm { source, .. } => match source {
hir::MatchSource::IfLetDesugar{..} => "`if let` arms have incompatible types",
_ => "match arms have incompatible types",
},
IfExpression => "if and else have incompatible types",
IfExpressionWithNoElse => "if may be missing an else clause",
EquatePredicate => "equality predicate not satisfied",
MainFunctionType => "main function has wrong type",
StartFunctionType => "start function has wrong type",
IntrinsicType => "intrinsic has wrong type",
MethodReceiver => "mismatched method receiver",
_ => "mismatched types",
}
}
fn as_requirement_str(&self) -> &'static str {
use traits::ObligationCauseCode::*;
match self.code {
CompareImplMethodObligation { .. } => "method type is compatible with trait",
ExprAssignable => "expression is assignable",
MatchExpressionArm { source, .. } => match source {
hir::MatchSource::IfLetDesugar{..} => "`if let` arms have compatible types",
_ => "match arms have compatible types",
},
IfExpression => "if and else have compatible types",
IfExpressionWithNoElse => "if missing an else returns ()",
EquatePredicate => "equality where clause is satisfied",
MainFunctionType => "`main` function has the correct type",
StartFunctionType => "`start` function has the correct type",
IntrinsicType => "intrinsic has the correct type",
MethodReceiver => "method receiver has the correct type",
_ => "types are compatible",
}
}
}