From 621767136eae13b2d9ebd462d3b33d6f1ad6b4e9 Mon Sep 17 00:00:00 2001 From: Marcin Serwin Date: Thu, 19 Mar 2020 16:54:19 +0100 Subject: [PATCH] Handle evaluating constant index expression --- clippy_lints/src/consts.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/clippy_lints/src/consts.rs b/clippy_lints/src/consts.rs index c64c00134e89..c25200c33388 100644 --- a/clippy_lints/src/consts.rs +++ b/clippy_lints/src/consts.rs @@ -268,6 +268,7 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { } } }, + ExprKind::Index(ref arr, ref index) => self.index(arr, index), // TODO: add other expressions. _ => None, } @@ -345,6 +346,20 @@ impl<'c, 'cc> ConstEvalLateContext<'c, 'cc> { } } + fn index(&mut self, lhs: &'_ Expr<'_>, index: &'_ Expr<'_>) -> Option { + let lhs = self.expr(lhs); + let index = self.expr(index); + + match (lhs, index) { + (Some(Constant::Vec(vec)), Some(Constant::Int(index))) => match vec[index as usize] { + Constant::F32(x) => Some(Constant::F32(x)), + Constant::F64(x) => Some(Constant::F64(x)), + _ => None, + }, + _ => None, + } + } + /// A block can only yield a constant if it only has one constant expression. fn block(&mut self, block: &Block<'_>) -> Option { if block.stmts.is_empty() {