Skip to content

Commit 36732a8

Browse files
Rollup merge of #159689 - estebank:issue-81816, r=chenyukang
Account for missing turbofish in resolve errors When encountering resolve errors caused by a missing turbofish having parsed as binops of types, emit a single error explaining the mistake clearly and silence redundant resolve errors. ``` error: can't compare two types --> $DIR/suggest-turbofish-parsed-as-comparisons.rs:11:41 | LL | let _ = Arc::new(RwLock::new(HashMap<i32, i64>::default())); | ^ ^ these are parsed as "less than" and "greater than" | help: you likely intended to write type `HashMap` with type parameters, but type parameters in expression contexts require the use of the "turbofish" `::<>` | LL | let _ = Arc::new(RwLock::new(HashMap::<i32, i64>::default())); | ++ ``` Address #81816. We should reduce the verbosity of the output and not complain about too many arguments.
2 parents 0cefa27 + c4b1049 commit 36732a8

7 files changed

Lines changed: 563 additions & 5 deletions

File tree

‎compiler/rustc_hir_typeck/src/fn_ctxt/checks.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -924,6 +924,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
924924

925925
let mut err = fn_call_diag_ctxt.initial_final_diagnostic();
926926
fn_call_diag_ctxt.suggest_confusable(&mut err);
927+
fn_call_diag_ctxt.detect_missing_turbofish(&mut err);
927928

928929
// As we encounter issues, keep track of what we want to provide for the suggestion.
929930

@@ -3227,6 +3228,45 @@ impl<'a, 'tcx> ArgMatchingCtxt<'a, 'tcx> {
32273228
self.annotate_alternative_method_deref(err, self.call_expr, None);
32283229
}
32293230

3231+
fn detect_missing_turbofish(&self, err: &mut Diag<'_>) {
3232+
if self.tcx.dcx().has_errors().is_none() {
3233+
return;
3234+
}
3235+
let mut iter = self.provided_args.iter().peekable();
3236+
while let Some(arg) = iter.next() {
3237+
let hir::ExprKind::Binary(lt, lt_left, lt_right) = arg.kind else {
3238+
continue;
3239+
};
3240+
let hir::BinOpKind::Lt = lt.node else { continue };
3241+
let hir::ExprKind::Path(_) = lt_left.kind else { continue };
3242+
let hir::ExprKind::Path(_) = lt_right.kind else { continue };
3243+
3244+
let Some(mut next) = iter.next() else { break };
3245+
loop {
3246+
match next.kind {
3247+
hir::ExprKind::Binary(gt, gt_left, gt_right)
3248+
if let hir::BinOpKind::Gt = gt.node
3249+
&& let hir::ExprKind::Path(_) = gt_left.kind
3250+
&& let hir::ExprKind::Call(..) = gt_right.kind =>
3251+
{
3252+
// We've encountered a likely missing turbofish error, for which we've already
3253+
// emitted a more targeted diagnostic during name resolution making this one
3254+
// redundant (`LateResolutionVisitor::detect_missing_turbofish`).
3255+
err.downgrade_to_delayed_bug();
3256+
}
3257+
hir::ExprKind::Path(_) => {
3258+
if let Some(n) = iter.next() {
3259+
next = n;
3260+
continue;
3261+
}
3262+
}
3263+
_ => {}
3264+
}
3265+
break;
3266+
}
3267+
}
3268+
}
3269+
32303270
/// A "softer" version of the `demand_compatible`, which checks types without persisting them,
32313271
/// and treats error types differently
32323272
/// This will allow us to "probe" for other argument orders that would likely have been correct

‎compiler/rustc_resolve/src/late.rs‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5166,6 +5166,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
51665166
}
51675167

51685168
/// Handles paths that may refer to associated items.
5169+
#[tracing::instrument(skip(self, source), level = "debug")]
51695170
fn resolve_qpath(
51705171
&mut self,
51715172
qself: &Option<Box<QSelf>>,
@@ -5174,11 +5175,6 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
51745175
finalize: Finalize,
51755176
source: PathSource<'_, 'ast, 'ra>,
51765177
) -> Result<Option<PartialRes>, Spanned<ResolutionError<'ra>>> {
5177-
debug!(
5178-
"resolve_qpath(qself={:?}, path={:?}, ns={:?}, finalize={:?})",
5179-
qself, path, ns, finalize,
5180-
);
5181-
51825178
if let Some(qself) = qself {
51835179
if qself.position == 0 {
51845180
// This is a case like `<T>::B`, where there is no
@@ -5578,6 +5574,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
55785574
self.resolve_expr(arg, None);
55795575
}
55805576
self.visit_path_segment(seg);
5577+
self.detect_missing_turbofish(&args);
55815578
}
55825579

55835580
ExprKind::Call(ref callee, ref arguments) => {
@@ -5599,6 +5596,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
55995596
self.resolve_expr(argument, None);
56005597
}
56015598
}
5599+
self.detect_missing_turbofish(&arguments);
56025600
}
56035601
ExprKind::FormatArgs(ref args) => {
56045602
for arg in args.arguments.all_args() {

‎compiler/rustc_resolve/src/late/diagnostics.rs‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1768,6 +1768,170 @@ impl<'ast, 'ra, 'tcx> LateResolutionVisitor<'_, 'ast, 'ra, 'tcx> {
17681768
}
17691769
}
17701770

1771+
/// When encountering `Ty < Ty, Ty > call()` in function and method call arguments, suggest
1772+
/// using the turbofish and silence redundant resolve errors.
1773+
pub(in crate::late) fn detect_missing_turbofish(&mut self, arguments: &'ast [Box<Expr>]) {
1774+
if self.use_injections.is_empty() {
1775+
// Avoid doing unnecessary work, we would have had resolve errors by now if this mistake
1776+
// had happened.
1777+
return;
1778+
}
1779+
let mut iter = arguments.iter().peekable();
1780+
// Look through every call argument expression, when encountering `a < b`, try to find a
1781+
// closing `c > ::d()` that would make the whole thing be syntactically valid as a
1782+
// fully-qualified path `a::<b, c>::d()`.
1783+
while let Some(arg) = iter.next() {
1784+
// foo(left < right, bar, baz>::qux())
1785+
// ^^^^ ^^^^^
1786+
let ExprKind::Binary(lt, left, right) = &arg.kind else { continue };
1787+
// foo(left < right, bar, baz>::qux())
1788+
// ^
1789+
let ast::BinOpKind::Lt = lt.node else {
1790+
continue;
1791+
};
1792+
// foo(left < right, bar, baz>::qux())
1793+
// ^^^^ is a path
1794+
let ExprKind::Path(_, lt_left) = &left.kind else { continue };
1795+
// foo(a::B < right, bar, baz>::qux())
1796+
// ^ ^ lt_left_segments
1797+
let lt_left_segments: Vec<_> = lt_left.segments.iter().map(|seg| seg.into()).collect();
1798+
// `a::B` is a type-like.
1799+
let lt_res = if let PathResult::NonModule(res) =
1800+
self.resolve_path(&lt_left_segments, Some(TypeNS), None, PathSource::Expr(None))
1801+
&& let Some(lt_res) = res.full_res()
1802+
{
1803+
lt_res
1804+
} else {
1805+
continue;
1806+
};
1807+
1808+
// Same thing we do for `left`, for `right`:
1809+
// foo(left < right, bar, baz>::qux())
1810+
// ^^^^^ is a path
1811+
let ExprKind::Path(_, lt_right) = &right.kind else { continue };
1812+
let lt_right_segments: Vec<_> =
1813+
lt_right.segments.iter().map(|seg| seg.into()).collect();
1814+
if let PathResult::NonModule(res) =
1815+
self.resolve_path(&lt_right_segments, Some(TypeNS), None, PathSource::Expr(None))
1816+
&& let Some(_res) = res.full_res()
1817+
{
1818+
} else {
1819+
continue;
1820+
}
1821+
1822+
// foo(left < right, bar, baz>::qux())
1823+
// next is ^^^ or ^^^^^^^^^^^
1824+
let Some(mut next) = iter.next() else {
1825+
break;
1826+
};
1827+
let mut other_path_spans = vec![];
1828+
loop {
1829+
match &next.kind {
1830+
// foo(left < right, bar, baz>::qux())
1831+
// ^^^^^^^^^
1832+
ExprKind::Binary(gt, gt_left, gt_right)
1833+
// foo(left < right, bar, baz>::qux())
1834+
// ^
1835+
if let ast::BinOpKind::Gt = gt.node
1836+
// foo(left < right, bar, baz>::qux())
1837+
// ^^^
1838+
&& let ExprKind::Path(_, gt_left) = &gt_left.kind
1839+
// foo(left < right, bar, baz>::qux())
1840+
// ^^^^^^^
1841+
&& let ExprKind::Call(call_expr, _) = &gt_right.kind
1842+
&& let ExprKind::Path(_, call_path) = &call_expr.kind
1843+
&& let gt_left_segments = gt_left
1844+
.segments
1845+
.iter()
1846+
.map(|seg| seg.into())
1847+
.collect::<Vec<_>>()
1848+
&& let PathResult::NonModule(res) = self.resolve_path(
1849+
&gt_left_segments,
1850+
Some(TypeNS),
1851+
None,
1852+
PathSource::Expr(None),
1853+
)
1854+
&& let Some(_res) = res.full_res() =>
1855+
{
1856+
// We've encountered an expression where we have `Ty < Ty, Ty > call(...)`.
1857+
// A binop between two types is non-sensical in (current?) Rust, and the
1858+
// presence of two binops separated by a comma of less-than followed by
1859+
// greater-than heavily implies a missing turbofish in an expression.
1860+
let mut any = false;
1861+
let spans: Vec<Span> = lt_left_segments
1862+
.iter()
1863+
.map(|s| s.ident.span)
1864+
.chain(lt_right_segments.iter().map(|s| s.ident.span))
1865+
.chain(gt_left_segments.iter().map(|s| s.ident.span))
1866+
.chain(gt_left_segments.iter().map(|s| s.ident.span))
1867+
.chain(call_path.segments.iter().map(|seg| seg.span()))
1868+
.chain(other_path_spans.iter().cloned())
1869+
.collect();
1870+
for injection in self.use_injections.iter_mut() {
1871+
// Silence all already constructed resolution errors that are contained
1872+
// by the likely missing turbofish.
1873+
if injection.path.iter().any(|s| spans.contains(&s.ident.span)) {
1874+
any = true;
1875+
injection.err.downgrade_to_delayed_bug();
1876+
}
1877+
}
1878+
if any {
1879+
let sp = MultiSpan::from(vec![lt.span, gt.span]);
1880+
let mut err =
1881+
self.r.tcx.dcx().struct_span_err(sp, "can't compare two types");
1882+
err.span_label(
1883+
gt.span,
1884+
"these are parsed as \"less than\" and \"greater than\"",
1885+
);
1886+
let name = if let Some(def_id) = lt_res.opt_def_id()
1887+
&& let Some(name) = self.r.tcx.opt_item_name(def_id)
1888+
{
1889+
name.to_string()
1890+
} else {
1891+
lt_right_segments
1892+
.iter()
1893+
.map(|s| s.ident.name.to_string())
1894+
.collect::<Vec<String>>()
1895+
.join("::")
1896+
};
1897+
err.span_suggestion_verbose(
1898+
lt.span.shrink_to_lo(),
1899+
format!(
1900+
"you likely intended to write type `{name}` with type parameters, but \
1901+
type parameters in expression contexts require the use of the \
1902+
\"turbofish\" `::<>`",
1903+
),
1904+
"::".to_string(),
1905+
Applicability::MachineApplicable,
1906+
);
1907+
err.emit();
1908+
}
1909+
}
1910+
1911+
// foo(left < right, bat, bar, baz>::qux())
1912+
// ^^^
1913+
ExprKind::Path(_, path) => {
1914+
// foo(left < right, bat, bar, baz>::qux())
1915+
// ^^^ or ^^^^^^^^^^^
1916+
if let Some(n) = iter.next() {
1917+
next = n;
1918+
other_path_spans.extend(path.segments.iter().map(|seg| seg.ident.span));
1919+
// Only case where we don't break from the `loop` advancing the parsed
1920+
// call arguments , we've encountered a path that is likely one of the
1921+
// type parameters for the missing turbofish.
1922+
continue;
1923+
}
1924+
}
1925+
1926+
_ => {}
1927+
}
1928+
// This doesn't look like a turbofish, look for more missing turbofishes on the
1929+
// following arguments.
1930+
break;
1931+
}
1932+
}
1933+
}
1934+
17711935
fn suggest_at_operator_in_slice_pat_with_range(&self, err: &mut Diag<'_>, path: &[Segment]) {
17721936
let Some(pat) = self.diag_metadata.current_pat else { return };
17731937
let (bound, side, range) = match &pat.kind {
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
fn set_alert(_: bool) {}
2+
fn current_limit() -> i32 {
3+
100
4+
}
5+
6+
fn main() {
7+
let used = 120;
8+
let warning = 90;
9+
set_alert(used < warning, used > current_limit());
10+
//~^ ERROR: this function takes 1 argument but 2 arguments were supplied
11+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
error[E0061]: this function takes 1 argument but 2 arguments were supplied
2+
--> $DIR/suggest-turbofish-parsed-as-comparisons-2.rs:9:5
3+
|
4+
LL | set_alert(used < warning, used > current_limit());
5+
| ^^^^^^^^^ ---------------------- unexpected argument #2 of type `bool`
6+
|
7+
note: function defined here
8+
--> $DIR/suggest-turbofish-parsed-as-comparisons-2.rs:1:4
9+
|
10+
LL | fn set_alert(_: bool) {}
11+
| ^^^^^^^^^
12+
help: remove the extra argument
13+
|
14+
LL - set_alert(used < warning, used > current_limit());
15+
LL + set_alert(used < warning);
16+
|
17+
18+
error: aborting due to 1 previous error
19+
20+
For more information about this error, try `rustc --explain E0061`.
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Issue #81816.
2+
use std::sync::Arc;
3+
use std::sync::RwLock;
4+
use std::collections::HashMap;
5+
6+
struct S;
7+
impl S {
8+
fn foo(&self, _: HashMap<i32, i64>) {}
9+
fn bar(&self, _: Many<i32, i32, i32, i32>) {}
10+
}
11+
fn bar(_: Many<i32, i32, i32, i32>) {}
12+
struct Many<A, B, C, D> {
13+
a: A,
14+
b: B,
15+
c: C,
16+
d: D,
17+
}
18+
19+
impl<A, B, C, D> Many<A, B, C, D> {
20+
fn new() -> Self { todo!() }
21+
}
22+
23+
fn main() {
24+
let _ = Arc::new(RwLock::new(HashMap<i32, i64>::default()));
25+
//~^ ERROR can't compare two types
26+
let _ = S.foo(HashMap<i32, i64>::default());
27+
//~^ ERROR can't compare two types
28+
let _ = bar(Many<i32, i32, i32, i32>::new());
29+
//~^ ERROR can't compare two types
30+
let _ = S.bar(Many<i32, i32, i32, i32>::new());
31+
//~^ ERROR can't compare two types
32+
let _ = bar(Many<i32, i32, i32, i32>::new(), Many<i32, i32, i32, i32>::new());
33+
//~^ ERROR can't compare two types
34+
//~| ERROR can't compare two types
35+
let _ = S.bar(Many<i32, i32, i32, i32>::new(), Many<i32, i32, i32, i32>::new());
36+
//~^ ERROR can't compare two types
37+
//~| ERROR can't compare two types
38+
let _ = bar(1, 2, Many<i32, i32, i32, i32>::new());
39+
//~^ ERROR can't compare two types
40+
let _ = S.bar(1, 2, Many<i32, i32, i32, i32>::new());
41+
//~^ ERROR can't compare two types
42+
let _ = bar(a, b, Many<i32, i32, i32, i32>::new(), c, d);
43+
//~^ ERROR can't compare two types
44+
//~| ERROR cannot find value `a` in this scope
45+
//~| ERROR cannot find value `b` in this scope
46+
//~| ERROR cannot find value `c` in this scope
47+
//~| ERROR cannot find value `d` in this scope
48+
let _ = S.bar(a, b, Many<i32, i32, i32, i32>::new(), c, d);
49+
//~^ ERROR can't compare two types
50+
//~| ERROR cannot find value `a` in this scope
51+
//~| ERROR cannot find value `b` in this scope
52+
//~| ERROR cannot find value `c` in this scope
53+
//~| ERROR cannot find value `d` in this scope
54+
}

0 commit comments

Comments
 (0)