Skip to content

Commit b48b509

Browse files
committed
typeck: show a note about tuple indexing for erroneous tup[i]
Fixes: #27842
1 parent 3157691 commit b48b509

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
@@ -3687,14 +3687,37 @@ fn check_expr_with_expectation_and_lvalue_pref<'a, 'tcx>(fcx: &FnCtxt<'a, 'tcx>,
36873687
}
36883688
None => {
36893689
check_expr_has_type(fcx, &idx, fcx.tcx().types.err);
3690-
fcx.type_error_message(
3690+
let mut err = fcx.type_error_struct(
36913691
expr.span,
36923692
|actual| {
36933693
format!("cannot index a value of type `{}`",
36943694
actual)
36953695
},
36963696
base_t,
36973697
None);
3698+
// Try to give some advice about indexing tuples.
3699+
if let ty::TyTuple(_) = base_t.sty {
3700+
let mut needs_note = true;
3701+
// If the index is an integer, we can show the actual
3702+
// fixed expression:
3703+
if let hir::ExprLit(ref lit) = idx.node {
3704+
if let ast::LitKind::Int(i, ast::LitIntType::Unsuffixed) = lit.node {
3705+
let snip = fcx.tcx().sess.codemap().span_to_snippet(base.span);
3706+
if let Ok(snip) = snip {
3707+
err.span_suggestion(expr.span,
3708+
"to access tuple elements, use tuple \
3709+
indexing syntax as shown",
3710+
format!("{}.{}", snip, i));
3711+
needs_note = false;
3712+
}
3713+
}
3714+
}
3715+
if needs_note {
3716+
err.help("to access tuple elements, use tuple indexing \
3717+
syntax (e.g. `tuple.0`)");
3718+
}
3719+
}
3720+
err.emit();
36983721
fcx.write_ty(id, fcx.tcx().types.err);
36993722
}
37003723
}

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)