1 package com.puppycrawl.tools.checkstyle.checks.coding; 20 21 import com.puppycrawl.tools.checkstyle.api.Check; 22 import com.puppycrawl.tools.checkstyle.api.DetailAST; 23 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 24 25 import com.puppycrawl.tools.checkstyle.checks.CheckUtils; 26 27 46 public class MultipleVariableDeclarationsCheck extends Check 47 { 48 49 public MultipleVariableDeclarationsCheck() 50 { 51 } 52 53 54 public int[] getDefaultTokens() 55 { 56 return new int[] {TokenTypes.VARIABLE_DEF}; 57 } 58 59 60 public void visitToken(DetailAST aAST) 61 { 62 DetailAST nextNode = (DetailAST) aAST.getNextSibling(); 63 final boolean isCommaSeparated = 64 ((nextNode != null) && (nextNode.getType() == TokenTypes.COMMA)); 65 66 if (nextNode == null) { 67 return; 69 } 70 71 if ((nextNode.getType() == TokenTypes.COMMA) 72 || (nextNode.getType() == TokenTypes.SEMI)) 73 { 74 nextNode = (DetailAST) nextNode.getNextSibling(); 75 } 76 77 if ((nextNode != null) 78 && (nextNode.getType() == TokenTypes.VARIABLE_DEF)) 79 { 80 final DetailAST firstNode = CheckUtils.getFirstNode(aAST); 81 if (isCommaSeparated) { 82 log(firstNode, "multiple.variable.declarations.comma"); 83 return; 84 } 85 86 final DetailAST lastNode = getLastNode(aAST); 87 final DetailAST firstNextNode = CheckUtils.getFirstNode(nextNode); 88 89 if (firstNextNode.getLineNo() == lastNode.getLineNo()) { 90 log(firstNode, "multiple.variable.declarations"); 91 } 92 } 93 94 } 95 96 101 private static DetailAST getLastNode(final DetailAST aNode) 102 { 103 DetailAST currentNode = aNode; 104 DetailAST child = (DetailAST) aNode.getFirstChild(); 105 while (child != null) { 106 final DetailAST newNode = getLastNode(child); 107 if ((newNode.getLineNo() > currentNode.getLineNo()) 108 || ((newNode.getLineNo() == currentNode.getLineNo()) 109 && (newNode.getColumnNo() > currentNode.getColumnNo()))) 110 { 111 currentNode = newNode; 112 } 113 child = (DetailAST) child.getNextSibling(); 114 } 115 116 return currentNode; 117 } 118 } 119 | Popular Tags |