01: package org.acm.seguin.pmd.rules;
02:
03: import org.acm.seguin.pmd.AbstractRule;
04: import org.acm.seguin.pmd.RuleContext;
05: import net.sourceforge.jrefactory.ast.ASTFieldDeclaration;
06: import net.sourceforge.jrefactory.ast.ASTLocalVariableDeclaration;
07: import net.sourceforge.jrefactory.ast.ASTReferenceType;
08: import net.sourceforge.jrefactory.ast.ASTPrimitiveType;
09: import net.sourceforge.jrefactory.ast.ASTType;
10: import net.sourceforge.jrefactory.ast.ASTVariableDeclarator;
11: import net.sourceforge.jrefactory.ast.ASTVariableDeclaratorId;
12: import net.sourceforge.jrefactory.ast.AccessNode;
13: import net.sourceforge.jrefactory.ast.Node;
14:
15: public class VariableNamingConventionsRule extends AbstractRule {
16:
17: public Object visit(ASTLocalVariableDeclaration node, Object data) {
18: return checkNames(node, data);
19: }
20:
21: public Object visit(ASTFieldDeclaration node, Object data) {
22: return checkNames(node, data);
23: }
24:
25: public Object checkNames(Node node, Object data) {
26:
27: boolean isFinal = false;
28: if (node instanceof AccessNode) {
29: isFinal = ((AccessNode) node).isFinal();
30: }
31:
32: ASTType childNodeType = (ASTType) node.jjtGetChild(0);
33: String varType = "";
34: if (childNodeType.jjtGetChild(0) instanceof ASTReferenceType) {
35: varType = ((ASTReferenceType) childNodeType.jjtGetChild(0))
36: .getImage();
37: } else if (childNodeType.jjtGetChild(0) instanceof ASTPrimitiveType) {
38: varType = ((ASTPrimitiveType) childNodeType.jjtGetChild(0))
39: .getImage();
40: }
41: if (varType != null && varType.length() > 0) {
42: //Get the variable name
43: ASTVariableDeclarator childNodeName = (ASTVariableDeclarator) node
44: .jjtGetChild(1);
45: ASTVariableDeclaratorId childNodeId = (ASTVariableDeclaratorId) childNodeName
46: .jjtGetChild(0);
47: String varName = childNodeId.getImage();
48:
49: if (isFinal) {
50: if (!varName.equals(varName.toUpperCase())) {
51: String msg = "Variables that are final should be in all caps.";
52: RuleContext ctx = (RuleContext) data;
53: ctx.getReport().addRuleViolation(
54: createRuleViolation(ctx, childNodeName
55: .getBeginLine(), msg));
56:
57: }
58: } else {
59: if (varName.indexOf("_") >= 0) {
60: String msg = "Variables that are not final should not contain underscores.";
61: RuleContext ctx = (RuleContext) data;
62: ctx.getReport().addRuleViolation(
63: createRuleViolation(ctx, childNodeName
64: .getBeginLine(), msg));
65: }
66: if (Character.isUpperCase(varName.charAt(0))) {
67: String msg = "Variables should start with a lowercase character";
68: RuleContext ctx = (RuleContext) data;
69: ctx.getReport().addRuleViolation(
70: createRuleViolation(ctx, childNodeName
71: .getBeginLine(), msg));
72: }
73:
74: }
75: }
76: return data;
77: }
78: }
|