001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2024 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; 021 022import com.puppycrawl.tools.checkstyle.StatelessCheck; 023import com.puppycrawl.tools.checkstyle.api.AbstractCheck; 024import com.puppycrawl.tools.checkstyle.api.DetailAST; 025import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 026 027/** 028 * <p> 029 * Checks whether file contains code. 030 * Java compiler is not raising errors on files with no code or all commented out. 031 * Files which are considered to have no code: 032 * </p> 033 * <ul> 034 * <li> 035 * File with no text 036 * </li> 037 * <li> 038 * File with single-line comment(s) 039 * </li> 040 * <li> 041 * File with a multi line comment(s). 042 * </li> 043 * </ul> 044 * <p> 045 * Parent is {@code com.puppycrawl.tools.checkstyle.TreeWalker} 046 * </p> 047 * <p> 048 * Violation Message Keys: 049 * </p> 050 * <ul> 051 * <li> 052 * {@code nocode.in.file} 053 * </li> 054 * </ul> 055 * 056 * @since 8.33 057 */ 058@StatelessCheck 059public class NoCodeInFileCheck extends AbstractCheck { 060 061 /** 062 * A key is pointing to the warning message text in "messages.properties" 063 * file. 064 */ 065 public static final String MSG_KEY_NO_CODE = "nocode.in.file"; 066 067 /** Line number used to log violation when no AST nodes are present in file. */ 068 private static final int DEFAULT_LINE_NUMBER = 1; 069 070 @Override 071 public int[] getDefaultTokens() { 072 return getRequiredTokens(); 073 } 074 075 @Override 076 public int[] getAcceptableTokens() { 077 return getRequiredTokens(); 078 } 079 080 @Override 081 public int[] getRequiredTokens() { 082 return CommonUtil.EMPTY_INT_ARRAY; 083 } 084 085 @Override 086 public void finishTree(DetailAST ast) { 087 if (ast == null) { 088 log(DEFAULT_LINE_NUMBER, MSG_KEY_NO_CODE); 089 } 090 } 091}