blob: 5ce5661c02e7b0b914216995fa50bc8261c5dfab (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/*******************************************************************************
* Copyright (c) 2009 Alena Laskavaia
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Alena Laskavaia - initial API and implementation
*******************************************************************************/
package org.eclipse.cdt.codan.checkers.sample;
import org.eclipse.cdt.codan.core.model.AbstractIndexAstChecker;
import org.eclipse.cdt.core.dom.ast.ASTNodeProperty;
import org.eclipse.cdt.core.dom.ast.ASTVisitor;
import org.eclipse.cdt.core.dom.ast.IASTBinaryExpression;
import org.eclipse.cdt.core.dom.ast.IASTExpression;
import org.eclipse.cdt.core.dom.ast.IASTForStatement;
import org.eclipse.cdt.core.dom.ast.IASTIfStatement;
import org.eclipse.cdt.core.dom.ast.IASTTranslationUnit;
public class AssignmentInConditionChecker extends AbstractIndexAstChecker {
private static final String ER_ID = "org.eclipse.cdt.codan.checkers.sample.AssignmentInConditionProblem";
public void processAst(IASTTranslationUnit ast) {
// traverse the ast using the visitor pattern.
ast.accept(new CheckCodeVisitor());
}
class CheckCodeVisitor extends ASTVisitor {
CheckCodeVisitor() {
shouldVisitExpressions = true;
}
public int visit(IASTExpression expression) {
if (isAssignmentExpression(expression)
&& isUsedAsCondition(expression)) {
reportProblem(ER_ID, expression, "Possible assignment in condition");
}
return PROCESS_CONTINUE;
}
private boolean isAssignmentExpression(IASTExpression e) {
if (e instanceof IASTBinaryExpression) {
IASTBinaryExpression binExpr = (IASTBinaryExpression) e;
return binExpr.getOperator() == IASTBinaryExpression.op_assign;
}
return false;
}
private boolean isUsedAsCondition(IASTExpression expression) {
ASTNodeProperty prop = expression.getPropertyInParent();
if (prop == IASTForStatement.CONDITION
|| prop == IASTIfStatement.CONDITION)
return true;
return false;
}
}
}
|