001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2009 SonarSource SA 004 * mailto:contact AT sonarsource DOT com 005 * 006 * Sonar is free software; you can redistribute it and/or 007 * modify it under the terms of the GNU Lesser General Public 008 * License as published by the Free Software Foundation; either 009 * version 3 of the License, or (at your option) any later version. 010 * 011 * Sonar is distributed in the hope that it will be useful, 012 * but WITHOUT ANY WARRANTY; without even the implied warranty of 013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 014 * Lesser General Public License for more details. 015 * 016 * You should have received a copy of the GNU Lesser General Public 017 * License along with Sonar; if not, write to the Free Software 018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 019 */ 020 package org.sonar.squid.ast.visitor; 021 022 import java.util.Arrays; 023 import java.util.List; 024 025 import org.sonar.squid.api.SourceClass; 026 import org.sonar.squid.measures.Metric; 027 028 import com.puppycrawl.tools.checkstyle.api.DetailAST; 029 import com.puppycrawl.tools.checkstyle.api.TokenTypes; 030 031 public class ClassVisitor extends AstVisitor { 032 033 private static final List<Integer> wantedTokens = Arrays.asList(TokenTypes.CLASS_DEF, TokenTypes.INTERFACE_DEF, TokenTypes.ENUM_DEF, 034 TokenTypes.ANNOTATION_DEF); 035 036 @Override 037 public List<Integer> getWantedTokens() { 038 return wantedTokens; 039 } 040 041 @Override 042 public void visitToken(DetailAST ast) { 043 String className = ast.findFirstToken(TokenTypes.IDENT).getText(); 044 SourceClass unit = createClassResource(className); 045 unit.setStartAtLine(ast.getLineNo()); 046 if (isInterface(ast.getType())) { 047 unit.setMeasure(Metric.INTERFACES, 1); 048 } 049 if (isAbstract(ast)) { 050 unit.setMeasure(Metric.ABSTRACT_CLASSES, 1); 051 } 052 } 053 054 private boolean isAbstract(DetailAST ast) { 055 final DetailAST abstractAST = ast.findFirstToken(TokenTypes.MODIFIERS).findFirstToken(TokenTypes.ABSTRACT); 056 return abstractAST != null; 057 } 058 059 private boolean isInterface(int type) { 060 if (type == TokenTypes.INTERFACE_DEF) { 061 return true; 062 } 063 return false; 064 } 065 066 private SourceClass createClassResource(String className) { 067 if (peekResource().isType(SourceClass.class)) { 068 addResource(SourceClass.create((SourceClass) peekResource(), className)); 069 } else { 070 addResource(SourceClass.create(peekParentPackage(), className)); 071 } 072 return (SourceClass) peekResource(); 073 } 074 075 @Override 076 public void leaveToken(DetailAST ast) { 077 popResource(); 078 } 079 }