001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2017 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle.checks.coding; 021 022import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 023import com.puppycrawl.tools.checkstyle.api.DetailAST; 024import com.puppycrawl.tools.checkstyle.api.TokenTypes; 025 026/** 027 * Ensures there is a package declaration. 028 * Rationale: Classes that live in the null package cannot be 029 * imported. Many novice developers are not aware of this. 030 * 031 * @author <a href="mailto:simon@redhillconsulting.com.au">Simon Harris</a> 032 * @author Oliver Burn 033 */ 034public final class PackageDeclarationCheck extends AbstractCheck { 035 036 /** 037 * A key is pointing to the warning message text in "messages.properties" 038 * file. 039 */ 040 public static final String MSG_KEY = "missing.package.declaration"; 041 042 /** Line number used to log violation when no AST nodes are present in file. */ 043 private static final int DEFAULT_LINE_NUMBER = 1; 044 045 /** Is package defined. */ 046 private boolean defined; 047 048 @Override 049 public int[] getDefaultTokens() { 050 return new int[] {TokenTypes.PACKAGE_DEF}; 051 } 052 053 @Override 054 public int[] getRequiredTokens() { 055 return getDefaultTokens(); 056 } 057 058 @Override 059 public int[] getAcceptableTokens() { 060 return new int[] {TokenTypes.PACKAGE_DEF}; 061 } 062 063 @Override 064 public void beginTree(DetailAST ast) { 065 defined = false; 066 } 067 068 @Override 069 public void finishTree(DetailAST ast) { 070 if (!defined) { 071 int lineNumber = DEFAULT_LINE_NUMBER; 072 if (ast != null) { 073 lineNumber = ast.getLineNo(); 074 } 075 log(lineNumber, MSG_KEY); 076 } 077 } 078 079 @Override 080 public void visitToken(DetailAST ast) { 081 defined = true; 082 } 083}