001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2015 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.naming;
021
022import com.puppycrawl.tools.checkstyle.api.DetailAST;
023import com.puppycrawl.tools.checkstyle.api.TokenTypes;
024import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck;
025
026/**
027 * Abstract class for checking that names conform to a specified format.
028 *
029 * @author Rick Giles
030 */
031public abstract class AbstractNameCheck
032    extends AbstractFormatCheck {
033    /**
034     * Message key for invalid pattern error.
035     */
036    public static final String MSG_INVALID_PATTERN = "name.invalidPattern";
037
038    /**
039     * Creates a new {@code AbstractNameCheck} instance.
040     * @param format format to check with
041     */
042    protected AbstractNameCheck(String format) {
043        super(format);
044    }
045
046    @Override
047    public void visitToken(DetailAST ast) {
048        if (mustCheckName(ast)) {
049            final DetailAST nameAST = ast.findFirstToken(TokenTypes.IDENT);
050            if (!getRegexp().matcher(nameAST.getText()).find()) {
051                log(nameAST.getLineNo(),
052                    nameAST.getColumnNo(),
053                    MSG_INVALID_PATTERN,
054                    nameAST.getText(),
055                    getFormat());
056            }
057        }
058    }
059
060    /**
061     * Decides whether the name of an AST should be checked against
062     * the format regexp.
063     * @param ast the AST to check.
064     * @return true if the IDENT subnode of ast should be checked against
065     *     the format regexp.
066     */
067    protected abstract boolean mustCheckName(DetailAST ast);
068}