[PATCH] coccicheck: Add redundant return variable test

From: cgel . zte
Date: Tue Mar 22 2022 - 03:59:30 EST


From: Minghao Chi <chi.minghao@xxxxxxxxxx>

This semantic patch looks for variables that are only used
as parameter returned by the function.

Reported-by: Zeal Robot <zealci@xxxxxxxxxx>
Signed-off-by: Minghao Chi <chi.minghao@xxxxxxxxxx>
---
scripts/coccinelle/misc/redundant.cocci | 57 +++++++++++++++++++++++++
1 file changed, 57 insertions(+)
create mode 100644 scripts/coccinelle/misc/redundant.cocci

diff --git a/scripts/coccinelle/misc/redundant.cocci b/scripts/coccinelle/misc/redundant.cocci
new file mode 100644
index 000000000000..57a4546783cb
--- /dev/null
+++ b/scripts/coccinelle/misc/redundant.cocci
@@ -0,0 +1,57 @@
+// SPDX-License-Identifier: GPL-2.0-only
+///
+/// Remove redundant variables and return the value directly.
+///
+// Confidence: Moderate
+// Copyright: (C) 2022 Minghao Chi, ZTE.
+// URL: http://coccinelle.lip6.fr/
+// Comments:
+// Options: --no-includes --include-headers
+
+virtual report
+virtual org
+
+@dislike@
+position p;
+identifier var;
+expression E;
+@@
+
+if(...)
+{
+ var = E;@p
+ return var;
+}
+
+@hope@
+identifier var, stru;
+expression E;
+position p!=dislike.p, p2;
+Type T;
+constant C;
+@@
+
+...when != T* var
+ when != struct stru* var;
+ when != var=C
+(
+ var = E;@p
+ return var;@p2
+)
+
+@script:python depends on report@
+p << hope.p;
+p2 << hope.p2;
+var << hope.var;
+@@
+
+coccilib.report.print_report(p[0], "Redundant variable: \"" + var + "\". Return \"" + var + "\" on line " + p2[0].line)
+
+@script:python depends on org@
+p << hope.p;
+p2 << hope.p2;
+var << hope.var;
+@@
+
+cocci.print_main("redundant \"" + var + "\" variable", p)
+cocci.print_sec("return " + var + " here ", p2)
--
2.25.1