Skip to content

Commit 3585321

Browse files
committed
Auto merge of #33337 - birkenfeld:issue-27842, r=jseyfried
typeck: show a note about tuple indexing for erroneous tup[i] Fixes: #27842
2 parents 1939b76 + b48b509 commit 3585321

File tree

2 files changed

+48
-1
lines changed

2 files changed

+48
-1
lines changed

src/librustc_typeck/check/mod.rs

+24-1
Original file line numberDiff line numberDiff line change
@@ -3691,14 +3691,37 @@ fn check_expr_with_expectation_and_lvalue_pref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
36913691
}
36923692
None => {
36933693
check_expr_has_type(fcx, &idx, fcx.tcx().types.err);
3694-
fcx.type_error_message(
3694+
let mut err = fcx.type_error_struct(
36953695
expr.span,
36963696
|actual| {
36973697
format!("cannot index a value of type `{}`",
36983698
actual)
36993699
},
37003700
base_t,
37013701
None);
3702+
// Try to give some advice about indexing tuples.
3703+
if let ty::TyTuple(_) = base_t.sty {
3704+
let mut needs_note = true;
3705+
// If the index is an integer, we can show the actual
3706+
// fixed expression:
3707+
if let hir::ExprLit(ref lit) = idx.node {
3708+
if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
3709+
let snip = fcx.tcx().sess.codemap().span_to_snippet(base.span);
3710+
if let Ok(snip) = snip {
3711+
err.span_suggestion(expr.span,
3712+
"to access tuple elements, use tuple \
3713+
indexing syntax as shown",
3714+
format!("{}.{}", snip, i));
3715+
needs_note = false;
3716+
}
3717+
}
3718+
}
3719+
if needs_note {
3720+
err.help("to access tuple elements, use tuple indexing \
3721+
syntax (e.g. `tuple.0`)");
3722+
}
3723+
}
3724+
err.emit();
37023725
fcx.write_ty(id, fcx.tcx().types.err);
37033726
}
37043727
}

src/test/compile-fail/issue-27842.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
fn main() {
12+
let tup = (0, 1, 2);
13+
// the case where we show a suggestion
14+
let _ = tup[0];
15+
//~^ ERROR cannot index a value of type
16+
//~| HELP to access tuple elements, use tuple indexing syntax as shown
17+
//~| SUGGESTION let _ = tup.0
18+
19+
// the case where we show just a general hint
20+
let i = 0_usize;
21+
let _ = tup[i];
22+
//~^ ERROR cannot index a value of type
23+
//~| HELP to access tuple elements, use tuple indexing syntax (e.g. `tuple.0`)
24+
}

0 commit comments

Comments
 (0)