From e9379aee8bc899563e934c7ed5823a39298b7257 Mon Sep 17 00:00:00 2001 From: Tommy Muehle Date: Wed, 23 Sep 2020 14:14:35 +0200 Subject: [PATCH] Check also binary expressions in return statement, fixes #11 --- checks/return.go | 18 ++++++++++++++++++ testdata/src/return/return.go | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/checks/return.go b/checks/return.go index be7f546..84974f1 100644 --- a/checks/return.go +++ b/checks/return.go @@ -41,6 +41,24 @@ func (a *ReturnAnalyzer) Check(n ast.Node) { if a.isMagicNumber(x) { a.pass.Reportf(x.Pos(), reportMsg, x.Value, ReturnCheck) } + case *ast.BinaryExpr: + a.checkBinaryExpr(x) + } + } +} + +func (a *ReturnAnalyzer) checkBinaryExpr(expr *ast.BinaryExpr) { + switch x := expr.X.(type) { + case *ast.BasicLit: + if a.isMagicNumber(x) { + a.pass.Reportf(x.Pos(), reportMsg, x.Value, ReturnCheck) + } + } + + switch y := expr.Y.(type) { + case *ast.BasicLit: + if a.isMagicNumber(y) { + a.pass.Reportf(y.Pos(), reportMsg, y.Value, ReturnCheck) } } } diff --git a/testdata/src/return/return.go b/testdata/src/return/return.go index 0b28adb..54584b1 100644 --- a/testdata/src/return/return.go +++ b/testdata/src/return/return.go @@ -11,3 +11,19 @@ func example2() string { func example3() float64 { return 2.0 // want "Magic number: 2.0" } + +func example4(x int32) int32 { + return x + 42 // want "Magic number: 42" +} + +func example5(x int32) int32 { + return 42 + x // want "Magic number: 42" +} + +func example6(x int32) int32 { + return x + (42 * 10) // want "Magic number: 42" "Magic number: 10" +} + +func example7(x int32) int32 { + return (42 * x) + 10 // want "Magic number: 42" "Magic number: 10" +}