Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Suggestion for 'static impl Trait return #51444

Merged
merged 4 commits into from
Jun 28, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/librustc/infer/error_reporting/nice_region_error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod different_lifetimes;
mod find_anon_type;
mod named_anon_conflict;
mod outlives_closure;
mod static_impl_trait;
mod util;

impl<'cx, 'gcx, 'tcx> InferCtxt<'cx, 'gcx, 'tcx> {
Expand Down Expand Up @@ -67,6 +68,7 @@ impl<'cx, 'gcx, 'tcx> NiceRegionError<'cx, 'gcx, 'tcx> {
self.try_report_named_anon_conflict()
.or_else(|| self.try_report_anon_anon_conflict())
.or_else(|| self.try_report_outlives_closure())
.or_else(|| self.try_report_static_impl_trait())
}

pub fn get_regions(&self) -> (Span, ty::Region<'tcx>, ty::Region<'tcx>) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2012-2013 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.

//! Error Reporting for static impl Traits.

use infer::error_reporting::nice_region_error::NiceRegionError;
use infer::lexical_region_resolve::RegionResolutionError;
use ty::RegionKind;
use util::common::ErrorReported;

impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> {
/// Print the error message for lifetime errors when the return type is a static impl Trait.
pub(super) fn try_report_static_impl_trait(&self) -> Option<ErrorReported> {
if let Some(ref error) = self.error {
match error.clone() {
RegionResolutionError::SubSupConflict(
var_origin,
sub_origin,
sub_r,
sup_origin,
sup_r,
) => {
let anon_reg_sup = self.is_suitable_region(sup_r)?;
if sub_r == &RegionKind::ReStatic &&
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we just concluding that any time that we have a bound of 'static and a fn with an impl Trait return, the two are connected?

e.g., what happens with this example?

use std::fmt::Debug;
fn foo(x: &u32) -> impl Debug {
  let _: &'static u32 = x;
  ()
}

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we just concluding that any time that we have a bound of 'static and a fn with an impl Trait return, the two are connected?

Close, unless I misunderstand, the code checks that the return type is impl Trait and that it is bound to 'static.

what happens with

The two provided examples keep the current output:

error[E0621]: explicit lifetime required in the type of `x`
 --> file.rs:3:25
  |
2 | fn foo(x: &u32) -> impl Debug {
  |        - consider changing the type of `x` to `&'static u32`
3 |   let _: &'static u32 = x;
  |                         ^ lifetime `'static` required

error[E0621]: explicit lifetime required in the type of `x`
 --> file.rs:7:29
  |
7 | fn bar(x: &u32, y: &u32) -> impl Debug {
  |        -                    ^^^^^^^^^^ lifetime `'static` required
  |        |
  |        consider changing the type of `x` to `&'static u32`

For the second case, we could expand this code handle it and suggest the following, but it'll be very involved:

fn bar<'a>(x: &'a u32, y: &u32) -> impl Debug + 'a {
  x
}

self._is_return_type_impl_trait(anon_reg_sup.def_id)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: We don't normally use method names with a leading _.

{
let sp = var_origin.span();
let return_sp = sub_origin.span();
let mut err = self.tcx.sess.struct_span_err(
sp,
"can't infer an appropriate lifetime",
);
err.span_label(sp, "can't infer an appropriate lifetime");
err.span_label(
return_sp,
"this return type evaluates to the `'static` lifetime...",
);
err.span_label(
sup_origin.span(),
"...but this borrow...",
);

let (lifetime, lt_sp_opt) = self.tcx.msg_span_from_free_region(sup_r);
if let Some(lifetime_sp) = lt_sp_opt {
err.span_note(
lifetime_sp,
&format!("...can't outlive {}", lifetime),
);
}

if let Ok(snippet) = self.tcx.sess.codemap().span_to_snippet(return_sp) {
err.span_suggestion(
return_sp,
&format!(
"you can add a constraint to the return type to make it last \
less than `'static` and match {}",
lifetime,
),
format!("{} + '_", snippet),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the case where the lifetime is named, think it would be more useful to recommend adding a named lifetime here (rather than '_).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree somewhat, the only reason I didn't implement it that way is that from my cursory tests '_ always works, but I could contrive a case where 'a wouldn't. That being said, I can change it if you feel strongly enough (or we could also leave that as a follow up task).

Copy link
Member

@cramertj cramertj Jun 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That makes sense. Thanks for the investigation!

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to suggest 'a.

);
}
err.emit();
return Some(ErrorReported);
}
}
_ => {}
}
}
None
}
}
17 changes: 17 additions & 0 deletions src/librustc/infer/error_reporting/nice_region_error/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,23 @@ impl<'a, 'gcx, 'tcx> NiceRegionError<'a, 'gcx, 'tcx> {
}
None
}

pub(super) fn _is_return_type_impl_trait(
&self,
scope_def_id: DefId,
) -> bool {
let ret_ty = self.tcx.type_of(scope_def_id);
match ret_ty.sty {
ty::TyFnDef(_, _) => {
let sig = ret_ty.fn_sig(self.tcx);
let output = self.tcx.erase_late_bound_regions(&sig.output());
return output.is_impl_trait();
}
_ => {}
}
false
}

// Here we check for the case where anonymous region
// corresponds to self and if yes, we display E0312.
// FIXME(#42700) - Need to format self properly to
Expand Down
2 changes: 1 addition & 1 deletion src/librustc/middle/mem_categorization.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ pub enum Note {
// and how it is located, as well as the mutability of the memory in
// which the value is stored.
//
// *WARNING* The field `cmt.type` is NOT necessarily the same as the
// *WARNING* The field `cmt.ty` is NOT necessarily the same as the
// result of `node_id_to_type(cmt.id)`. This is because the `id` is
// always the `id` of the node producing the type; in an expression
// like `*x`, the type of this deref node is the deref'd type (`T`),
Expand Down
7 changes: 7 additions & 0 deletions src/librustc/ty/sty.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1754,6 +1754,13 @@ impl<'a, 'gcx, 'tcx> TyS<'tcx> {
}
}

pub fn is_impl_trait(&self) -> bool {
match self.sty {
TyAnon(..) => true,
_ => false,
}
}

pub fn ty_to_def_id(&self) -> Option<DefId> {
match self.sty {
TyDynamic(ref tt, ..) => tt.principal().map(|p| p.def_id()),
Expand Down
26 changes: 26 additions & 0 deletions src/test/ui/impl-trait/static-return-lifetime-infered.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
// Copyright 2018 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.

struct A {
x: [(u32, u32); 10]
}

impl A {
fn iter_values_anon(&self) -> impl Iterator<Item=u32> {
self.x.iter().map(|a| a.0)
}
//~^^^ ERROR can't infer an appropriate lifetime
fn iter_values<'a>(&'a self) -> impl Iterator<Item=u32> {
self.x.iter().map(|a| a.0)
}
//~^^^ ERROR can't infer an appropriate lifetime
}

fn main() {}
44 changes: 44 additions & 0 deletions src/test/ui/impl-trait/static-return-lifetime-infered.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
error: can't infer an appropriate lifetime
--> $DIR/static-return-lifetime-infered.rs:17:16
|
LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> {
| ----------------------- this return type evaluates to the `'static` lifetime...
LL | self.x.iter().map(|a| a.0)
| ------ ^^^^ can't infer an appropriate lifetime
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this cant infer an appropriate lifetime hint seems out-of-place to me. it interjects in the middle of the sentence "this return type evaluates to the 'static lifetime but this borrow...". Perhaps move it or combine it somehow with the "can't outlive the anonymous lifetime" error?

Copy link
Contributor Author

@estebank estebank Jun 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree. I tried a couple of different outputs, including:

error: can't infer an appropriate lifetime
  --> file.rs:11:16
   |
11 |         self.x.iter().map(|a| a.0)
   |                ^^^^ can't infer an appropriate lifetime for this
   |
note: this return type evaluates to the `'static` lifetime...
  --> file.rs:10:35
   |
10 |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> {
   |                                   ^^^^^^^^^^^^^^^^^^^^^^^
note: ...but this borrow...
  --> file.rs:11:9
   |
11 |         self.x.iter().map(|a| a.0)
   |         ^^^^^^
note: ...can't outlive the anonymous lifetime #1 defined on the method body at 10:5
  --> file.rs:10:5
   |
10 | /     fn iter_values_anon(&self) -> impl Iterator<Item=u32> {
11 | |         self.x.iter().map(|a| a.0)
12 | |     }
   | |_____^
help: you can add a constraint to make the `impl Trait` non`'static` and match the anonymous lifetime #1 defined on the method body at 10:5
   |
10 |     fn iter_values_anon(&self) -> impl Iterator<Item=u32> + '_ {
   |                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

I feel that the current output without any primary label would look reasonably good.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I actually like what you have above, but I think you could remove the "can't infer an appropriate lifetime for this" at the top, since that's covered in the "but this borrow... can't outlive the anonymous lifetime".

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you take a look at the current output? I removed the primary label and it does seem slightly easier to read.

| |
| ...but this borrow...
|
note: ...can't outlive the anonymous lifetime #1 defined on the method body at 16:5
--> $DIR/static-return-lifetime-infered.rs:16:5
|
LL | / fn iter_values_anon(&self) -> impl Iterator<Item=u32> {
LL | | self.x.iter().map(|a| a.0)
LL | | }
| |_____^
help: you can add a constraint to the return type to make it last less than `'static` and match the anonymous lifetime #1 defined on the method body at 16:5
|
LL | fn iter_values_anon(&self) -> impl Iterator<Item=u32> + '_ {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: can't infer an appropriate lifetime
--> $DIR/static-return-lifetime-infered.rs:21:16
|
LL | fn iter_values<'a>(&'a self) -> impl Iterator<Item=u32> {
| ----------------------- this return type evaluates to the `'static` lifetime...
LL | self.x.iter().map(|a| a.0)
| ------ ^^^^ can't infer an appropriate lifetime
| |
| ...but this borrow...
|
note: ...can't outlive the lifetime 'a as defined on the method body at 20:5
--> $DIR/static-return-lifetime-infered.rs:20:5
|
LL | fn iter_values<'a>(&'a self) -> impl Iterator<Item=u32> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
help: you can add a constraint to the return type to make it last less than `'static` and match the lifetime 'a as defined on the method body at 20:5
|
LL | fn iter_values<'a>(&'a self) -> impl Iterator<Item=u32> + '_ {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to 2 previous errors