Skip to content

Fix range literals borrowing suggestions #54734

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

Merged
merged 6 commits into from
Oct 10, 2018
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
82 changes: 79 additions & 3 deletions src/librustc_typeck/check/demand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,11 +309,16 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
};
if self.can_coerce(ref_ty, expected) {
if let Ok(src) = cm.span_to_snippet(sp) {
let sugg_expr = match expr.node { // parenthesize if needed (Issue #46756)
let needs_parens = match expr.node {
// parenthesize if needed (Issue #46756)
hir::ExprKind::Cast(_, _) |
hir::ExprKind::Binary(_, _, _) => format!("({})", src),
_ => src,
hir::ExprKind::Binary(_, _, _) => true,
// parenthesize borrows of range literals (Issue #54505)
_ if self.is_range_literal(expr) => true,
_ => false,
};
let sugg_expr = if needs_parens { format!("({})", src) } else { src };
Copy link
Member

Choose a reason for hiding this comment

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

Generally prefer to split if-else across separate lines.


if let Some(sugg) = self.can_use_as_ref(expr) {
return Some(sugg);
}
Expand Down Expand Up @@ -374,6 +379,77 @@ impl<'a, 'gcx, 'tcx> FnCtxt<'a, 'gcx, 'tcx> {
None
}

// This function checks if the specified expression is a built-in range literal
Copy link
Member

Choose a reason for hiding this comment

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

Use /// for documentation comments for functions. (Nit: And full stops for the ends of sentences 😄)

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Right. Does nightly rustdoc support code references yet?

Copy link
Member

Choose a reason for hiding this comment

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

As in references to source files? Not that I'm aware of.

// (See: librustc/hir/lowering.rs::LoweringContext::lower_expr() )
Copy link
Member

Choose a reason for hiding this comment

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

Nit: I'd surround the path with backticks, like any piece of code.

fn is_range_literal(&self, expr: &hir::Expr) -> bool {
use hir::{Path, QPath, ExprKind, TyKind};

// we support `::std::ops::Range` and `::std::core::Range` prefixes
// (via split on "|")
let ops_path = ["{{root}}", "std|core", "ops"];

let is_range_path = |path: &Path| {
Copy link
Member

Choose a reason for hiding this comment

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

I might be alone in this (cc @estebank), but I think for a short path like this, a more explicit approach (like below) is more readable. (I specifically don't like splitting on "|" because it feels a little too ad hoc.)

let is_range_path = |path: &Path| {
    let segs = path.segments.iter().map(|seg| seg.ident.as_str());
	if let (Some("{{root}}"), std_core, "ops", range, None) = (segs.next(), segs.next(), segs.next(), segs.next(), segs.next()) {
		(std_core == "std" || std_core == "ops") && range.starts_with("Range")
	} else {
		false
	}
};

Copy link
Contributor Author

Choose a reason for hiding this comment

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

That's a great suggestion! I was looking for something concise like this syntax-wise, it didn't occur to me that I could use .next() and rely on it returning None when there's no more elements.

let ident_names: Vec<_> = path.segments
.iter()
.map(|seg| seg.ident.as_str())
.collect();

if let Some((last, preceding)) = ident_names.split_last() {
last.starts_with("Range") &&
preceding.len() == 3 &&
preceding.iter()
.zip(ops_path.iter())
.all(|(seg, match_seg)| {
match_seg.split("|")
.into_iter()
.any(|ref spl_seg| seg == spl_seg)
})
} else {
false
}
};

let is_range_struct_snippet = |span: &Span| {
// Tell if expression span snippet looks like an explicit
// Range struct or new() call. This is to allow rejecting
// Ranges constructed with non-literals.
let source_map = self.tcx.sess.source_map();
let end_point = source_map.end_point(*span);

if let Ok(end_string) = source_map.span_to_snippet(end_point) {
end_string.ends_with("}") || end_string.ends_with(")")
} else {
false
}

Copy link
Member

Choose a reason for hiding this comment

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

Nit: delete blank line here.

};

match expr.node {
// all built-in range literals but `..=` and `..`
// desugar to Structs, `..` desugars to its struct path
ExprKind::Struct(QPath::Resolved(None, ref path), _, _) |
ExprKind::Path(QPath::Resolved(None, ref path)) => {
return is_range_path(&path) && !is_range_struct_snippet(&expr.span);
}

// `..=` desugars into RangeInclusive::new(...)
ExprKind::Call(ref func, _) => {
if let ExprKind::Path(QPath::TypeRelative(ref ty, ref segment)) = func.node {
if let TyKind::Path(QPath::Resolved(None, ref path)) = ty.node {
let calls_new = segment.ident.as_str() == "new";

return is_range_path(&path) && calls_new &&
!is_range_struct_snippet(&expr.span);
}
}
}

_ => {}
}

false
}

pub fn check_for_cast(&self,
err: &mut DiagnosticBuilder<'tcx>,
expr: &hir::Expr,
Expand Down
85 changes: 85 additions & 0 deletions src/test/ui/range/issue-54505-no-literals.fixed
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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.

// run-rustfix

// Regression test for changes introduced while fixing #54505

// This test uses non-literals for Ranges
// (expecting no parens with borrow suggestion)

use std::ops::RangeBounds;


// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}


fn main() {
take_range(&std::ops::Range { start: 0, end: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::Range { start: 0, end: 1 }

take_range(&::std::ops::Range { start: 0, end: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::Range { start: 0, end: 1 }

take_range(&std::ops::RangeFrom { start: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeFrom { start: 1 }

take_range(&::std::ops::RangeFrom { start: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeFrom { start: 1 }

take_range(&std::ops::RangeFull {});
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeFull {}

take_range(&::std::ops::RangeFull {});
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeFull {}

take_range(&std::ops::RangeInclusive::new(0, 1));
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeInclusive::new(0, 1)

take_range(&::std::ops::RangeInclusive::new(0, 1));
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeInclusive::new(0, 1)

take_range(&std::ops::RangeTo { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeTo { end: 5 }

take_range(&::std::ops::RangeTo { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeTo { end: 5 }

take_range(&std::ops::RangeToInclusive { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeToInclusive { end: 5 }

take_range(&::std::ops::RangeToInclusive { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeToInclusive { end: 5 }
}
85 changes: 85 additions & 0 deletions src/test/ui/range/issue-54505-no-literals.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
// 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.

// run-rustfix

// Regression test for changes introduced while fixing #54505

// This test uses non-literals for Ranges
// (expecting no parens with borrow suggestion)

use std::ops::RangeBounds;


// take a reference to any built-in range
fn take_range(_r: &impl RangeBounds<i8>) {}


fn main() {
take_range(std::ops::Range { start: 0, end: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::Range { start: 0, end: 1 }

take_range(::std::ops::Range { start: 0, end: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::Range { start: 0, end: 1 }

take_range(std::ops::RangeFrom { start: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeFrom { start: 1 }

take_range(::std::ops::RangeFrom { start: 1 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeFrom { start: 1 }

take_range(std::ops::RangeFull {});
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeFull {}

take_range(::std::ops::RangeFull {});
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeFull {}

take_range(std::ops::RangeInclusive::new(0, 1));
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeInclusive::new(0, 1)

take_range(::std::ops::RangeInclusive::new(0, 1));
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeInclusive::new(0, 1)

take_range(std::ops::RangeTo { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeTo { end: 5 }

take_range(::std::ops::RangeTo { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeTo { end: 5 }

take_range(std::ops::RangeToInclusive { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &std::ops::RangeToInclusive { end: 5 }

take_range(::std::ops::RangeToInclusive { end: 5 });
//~^ ERROR mismatched types [E0308]
//~| HELP consider borrowing here
//~| SUGGESTION &::std::ops::RangeToInclusive { end: 5 }
}
Loading