1 package com.puppycrawl.tools.checkstyle.checks.usage; 20 21 import java.util.HashSet ; 22 import java.util.Iterator ; 23 import java.util.Set ; 24 25 import com.puppycrawl.tools.checkstyle.api.DetailAST; 26 import com.puppycrawl.tools.checkstyle.api.Scope; 27 import com.puppycrawl.tools.checkstyle.api.ScopeUtils; 28 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 29 import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.Definition; 30 import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.Reference; 31 import com.puppycrawl.tools.checkstyle.checks.usage.transmogrify.SymTabAST; 32 33 34 51 public class OneMethodPrivateFieldCheck 52 extends AbstractUsageCheck 53 { 54 55 public int[] getDefaultTokens() 56 { 57 return new int[] { 58 TokenTypes.VARIABLE_DEF, 59 }; 60 } 61 62 63 public String getErrorKey() 64 { 65 return "one.method.private.field"; 66 } 67 68 69 public boolean mustCheckReferenceCount(DetailAST aAST) 70 { 71 final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS); 72 return ((mods != null) 73 && (ScopeUtils.getScopeFromMods(mods) == Scope.PRIVATE)); 74 } 75 76 77 public void applyTo(Set aNodes) 78 { 79 final Set methods = new HashSet (); 81 final Iterator it = aNodes.iterator(); 82 while (it.hasNext()) { 83 methods.clear(); 84 final DetailAST nameAST = (DetailAST) it.next(); 85 final Iterator refIt = getReferences(nameAST); 87 while (refIt.hasNext()) { 88 final Reference ref = (Reference) refIt.next(); 89 final SymTabAST refNode = ref.getTreeNode(); 90 final DetailAST refDetail = refNode.getDetailNode(); 91 if (refDetail == nameAST) { 93 continue; 94 } 95 DetailAST parent = refDetail.getParent(); 96 while (parent != null) { 97 final int type = parent.getType(); 98 if ((type == TokenTypes.METHOD_DEF) 99 || (type == TokenTypes.CTOR_DEF) 100 || (type == TokenTypes.INSTANCE_INIT) 101 || (type == TokenTypes.STATIC_INIT)) 102 { 103 methods.add(parent); 104 break; 105 } 106 else if (type == TokenTypes.CLASS_DEF) { 108 break; 109 } 110 parent = parent.getParent(); 111 } 112 } 113 if (methods.size() == 1) { 114 log( 115 nameAST.getLineNo(), 116 nameAST.getColumnNo(), 117 getErrorKey(), 118 nameAST.getText()); 119 } 120 } 121 } 122 123 128 private Iterator getReferences(DetailAST aAST) 129 { 130 final SymTabAST ident = getASTManager().get(aAST); 131 final Definition definition = 132 (Definition) ident.getDefinition(); 133 if (definition != null) { 134 return definition.getReferences(); 135 } 136 final Set dummy = new HashSet (); 137 return dummy.iterator(); 138 } 139 } 140 | Popular Tags |