1 //          Copyright Brian Schott (Hackerpilot) 2014.
2 // Distributed under the Boost Software License, Version 1.0.
3 //    (See accompanying file LICENSE_1_0.txt or copy at
4 //          http://www.boost.org/LICENSE_1_0.txt)
5 
6 module analysis.logic_precedence;
7 
8 import std.stdio;
9 import dparse.ast;
10 import dparse.lexer;
11 import analysis.base;
12 import analysis.helpers;
13 import dsymbol.scope_;
14 
15 /**
16  * Checks for code with confusing && and || operator precedence
17  * ---
18  * if (a && b || c) // bad
19  * if (a && (b || c)) // good
20  * ---
21  */
22 class LogicPrecedenceCheck : BaseAnalyzer
23 {
24 	alias visit = BaseAnalyzer.visit;
25 
26 	enum string KEY = "dscanner.confusing.logical_precedence";
27 
28 	this(string fileName, const(Scope)* sc)
29 	{
30 		super(fileName, sc);
31 	}
32 
33 	override void visit(const OrOrExpression orOr)
34 	{
35 		if (orOr.left is null || orOr.right is null) return;
36 		const AndAndExpression left = cast(AndAndExpression) orOr.left;
37 		const AndAndExpression right = cast(AndAndExpression) orOr.right;
38 		if (left is null && right is null) return;
39 		if ((left !is null && left.right is null) && (right !is null && right.right is null)) return;
40 		addErrorMessage(orOr.line, orOr.column, KEY,
41 			"Use parenthesis to clarify this expression.");
42 		orOr.accept(this);
43 	}
44 }
45 
46 unittest
47 {
48 	import analysis.config : StaticAnalysisConfig;
49 
50 	StaticAnalysisConfig sac;
51 	sac.logical_precedence_check = true;
52 	assertAnalyzerWarnings(q{
53 		void testFish()
54 		{
55 			if (a && b || c) {} // [warn]: Use parenthesis to clarify this expression.
56 			if ((a && b) || c) {} // Good
57 			if (b || c && d) {} // [warn]: Use parenthesis to clarify this expression.
58 			if (b || (c && d)) {} // Good
59 		}
60 	}}, sac);
61 	stderr.writeln("Unittest for LogicPrecedenceCheck passed.");
62 }
63