@@ -2810,23 +2810,26 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
28102810 "cannot index into a value of type `{base_t}`" ,
28112811 ) ;
28122812 // Try to give some advice about indexing tuples.
2813- if let ty:: Tuple ( .. ) = base_t. kind ( ) {
2813+ if let ty:: Tuple ( types ) = base_t. kind ( ) {
28142814 let mut needs_note = true ;
28152815 // If the index is an integer, we can show the actual
28162816 // fixed expression:
2817- if let ExprKind :: Lit ( ref lit) = idx. kind {
2818- if let ast:: LitKind :: Int ( i, ast:: LitIntType :: Unsuffixed ) = lit. node {
2819- let snip = self . tcx . sess . source_map ( ) . span_to_snippet ( base. span ) ;
2820- if let Ok ( snip) = snip {
2821- err. span_suggestion (
2822- expr. span ,
2823- "to access tuple elements, use" ,
2824- format ! ( "{snip}.{i}" ) ,
2825- Applicability :: MachineApplicable ,
2826- ) ;
2827- needs_note = false ;
2828- }
2817+ if let ExprKind :: Lit ( ref lit) = idx. kind
2818+ && let ast:: LitKind :: Int ( i, ast:: LitIntType :: Unsuffixed ) = lit. node
2819+ && i < types. len ( ) . try_into ( ) . expect ( "expected tuple index to be < usize length" )
2820+ {
2821+ let snip = self . tcx . sess . source_map ( ) . span_to_snippet ( base. span ) ;
2822+ if let Ok ( snip) = snip {
2823+ err. span_suggestion (
2824+ expr. span ,
2825+ "to access tuple elements, use" ,
2826+ format ! ( "{snip}.{i}" ) ,
2827+ Applicability :: MachineApplicable ,
2828+ ) ;
2829+ needs_note = false ;
28292830 }
2831+ } else if let ExprKind :: Path ( ..) = idx. peel_borrows ( ) . kind {
2832+ err. span_label ( idx. span , "cannot access tuple elements at a variable index" ) ;
28302833 }
28312834 if needs_note {
28322835 err. help (
0 commit comments