com.puppycrawl.tools.checkstyle.api.DetailAST Java Examples

The following examples show how to use com.puppycrawl.tools.checkstyle.api.DetailAST. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SpringMethodOrderCheck.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
@Override
public void visitToken(DetailAST ast) {
	DetailAST block = ast.findFirstToken(TokenTypes.OBJBLOCK);
	DetailAST candidate = block.getFirstChild();
	List<DetailAST> methods = new ArrayList<>();
	while (candidate != null) {
		candidate = candidate.getNextSibling();
		if (candidate != null && candidate.getType() == TokenTypes.METHOD_DEF) {
			DetailAST ident = candidate.findFirstToken(TokenTypes.IDENT);
			DetailAST parameters = candidate.findFirstToken(TokenTypes.PARAMETERS);
			if (isOrderedMethod(ident, parameters)) {
				methods.add(ident);
			}
		}
	}
	checkOrder(methods);
}
 
Example #2
Source File: MonitoringRecordFactoryConventionCheck.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * This method finds out whether the given class implements the record factory
 * or not.
 *
 * @param clazz
 *            The class in question.
 *
 * @return true if and only if the class implements the record factory.
 */
private static boolean implementsFactory(final DetailAST clazz) {
	final DetailAST implementsClause = clazz.findFirstToken(TokenTypes.IMPLEMENTS_CLAUSE);
	if (implementsClause != null) {
		DetailAST clause = implementsClause.getFirstChild();

		// Run through the whole implements clause
		while (clause != null) {
			// It has to be a combination of two names
			if ((clause.getType() == TokenTypes.DOT) && (clause.getChildCount() == 2)) {
				final String fstClauseIdent = clause.getFirstChild().getText();
				final String sndClauseIdent = clause.getLastChild().getText();

				return (FACTORY_FST_NAME.equals(fstClauseIdent)) && (FACTORY_SND_NAME.equals(sndClauseIdent));
			}

			clause = clause.getNextSibling();
		}
	}
	return false;
}
 
Example #3
Source File: UnusedParameterCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */
public boolean mustCheckReferenceCount(DetailAST aAST)
{
    boolean result = false;
    final DetailAST parent = aAST.getParent();
    if (parent != null) {
        if (parent.getType() == TokenTypes.PARAMETERS) {
            final DetailAST grandparent = parent.getParent();
            if (grandparent != null) {
                result = hasBody(grandparent)
                    && (!mIgnoreNonLocal || isLocal(grandparent));
            }
        }
        else if (parent.getType() == TokenTypes.LITERAL_CATCH) {
            result = !mIgnoreCatch;
        }
    }
    return result;
}
 
Example #4
Source File: MonitoringRecordFactoryConventionCheck.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the given field is valid or not.
 *
 * @param field
 *            The field to check.
 *
 * @return true if and only if the field is a valid one.
 */
private static boolean isValidTypeField(final DetailAST field) {
	final String ident = field.findFirstToken(TokenTypes.IDENT).getText();

	// Is the name correct?
	if (FIELD_NAME.equals(ident)) {
		final DetailAST modifiers = field.findFirstToken(TokenTypes.MODIFIERS);

		// Check whether the field is static and final
		if (modifiers.branchContains(TokenTypes.LITERAL_STATIC) && modifiers.branchContains(TokenTypes.FINAL)) {
			return MonitoringRecordFactoryConventionCheck.treeCompare(field.findFirstToken(TokenTypes.TYPE),
					TYPE_AST);
		}
	}

	return false;
}
 
Example #5
Source File: SpringLambdaCheck.java    From spring-javaformat with Apache License 2.0 6 votes vote down vote up
private void visitLambda(DetailAST lambda) {
	if (hasSingleParameter(lambda)) {
		boolean hasParentheses = hasToken(lambda, TokenTypes.LPAREN);
		if (this.singleArgumentParentheses && !hasParentheses) {
			log(lambda.getLineNo(), lambda.getColumnNo(), "lambda.missingParen");
		}
		else if (!this.singleArgumentParentheses && hasParentheses) {
			if (!isUsingParametersToDefineType(lambda)) {
				log(lambda.getLineNo(), lambda.getColumnNo(), "lambda.unnecessaryParen");
			}
		}
	}
	DetailAST block = lambda.getLastChild();
	int statements = countDescendantsOfType(block, TokenTypes.SEMI);
	int requireBlock = countDescendantsOfType(block, TokenTypes.LCURLY, TokenTypes.LITERAL_THROW, TokenTypes.SLIST);
	if (statements == 1 && requireBlock == 0) {
		log(block.getLineNo(), block.getColumnNo(), "lambda.unnecessaryBlock");
	}
}
 
Example #6
Source File: AnalysisComponentConstructorCheck.java    From kieker with Apache License 2.0 6 votes vote down vote up
@Override
public void visitToken(final DetailAST ast) {
	// Check whether we are interested in the class (whether it is an
	// analysis component or not)
	if (!(this.ignoreAbstractClasses && CSUtility.isAbstract(ast))
			&& AnalysisComponentConstructorCheck.isAnalysisComponent(ast)) {
		// Now check the constructors
		DetailAST child = ast.findFirstToken(TokenTypes.OBJBLOCK).findFirstToken(TokenTypes.CTOR_DEF);
		while (child != null) {
			if ((child.getType() == TokenTypes.CTOR_DEF)
					&& AnalysisComponentConstructorCheck.isValidConstructor(child)) {
				// We found a valid constructor
				return;
			}

			child = child.getNextSibling();
		}

		// Seems like there is no valid constructor
		this.log(ast.getLineNo(), "invalid analysis component constructor");
	}
}
 
Example #7
Source File: PluralEnumNames.java    From aws-sdk-java-v2 with Apache License 2.0 6 votes vote down vote up
private boolean hasPublicStaticField(DetailAST ast) {
    DetailAST classBody = ast.findFirstToken(TokenTypes.OBJBLOCK);
    DetailAST maybeVariableDefinition = classBody.getFirstChild();

    String className = ast.findFirstToken(TokenTypes.IDENT).getText();

    // Filter out util classes
    if (className.endsWith("Utils")) {
        return false;
    }

    while (maybeVariableDefinition != null) {
        if (maybeVariableDefinition.getType() == TokenTypes.VARIABLE_DEF) {
            DetailAST modifiers = maybeVariableDefinition.findFirstToken(TokenTypes.MODIFIERS);
            if (modifiers != null && isPublic(modifiers) && isStatic(modifiers)) {
                return true;
            }
        }

        maybeVariableDefinition = maybeVariableDefinition.getNextSibling();
    }

    return false;
}
 
Example #8
Source File: OverrideAnnotationOnTheSameLineCheck.java    From ignite with Apache License 2.0 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void visitToken(DetailAST ast) {
    DetailAST node = ast.findFirstToken(MODIFIERS);

    if (node == null)
        node = ast.findFirstToken(ANNOTATIONS);

    if (node == null)
        return;

    for (node = node.getFirstChild(); node != null; node = node.getNextSibling()) {
        if (node.getType() == TokenTypes.ANNOTATION &&
            Override.class.getSimpleName().equals(annotationName(node)) &&
            node.getLineNo() != nextNode(node).getLineNo())
            log(node.getLineNo(), DIFF_LINE_ERR_MSG, annotationName(node));
    }
}
 
Example #9
Source File: AnalysisComponentConstructorCheck.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * Checks whether the given constructor seems to be a valid one or not.
 *
 * @param constructor
 *            The constructor in question.
 *
 * @return true if and only if the constructor seems to be valid.
 */
private static boolean isValidConstructor(final DetailAST constructor) {
	// Find the available parameters of the constructor
	final DetailAST parameters = constructor.findFirstToken(TokenTypes.PARAMETERS);

	// Make sure that there are exactly TWO parameters (two parameters plus
	// a comma in the middle)
	if (parameters.getChildCount() == 3) {
		final DetailAST fstParType = parameters.getFirstChild().findFirstToken(TokenTypes.TYPE);
		final DetailAST sndParType = parameters.getLastChild().findFirstToken(TokenTypes.TYPE);

		final DetailAST fstParIdent = fstParType.findFirstToken(TokenTypes.IDENT);
		final DetailAST sndParIdent = sndParType.findFirstToken(TokenTypes.IDENT);

		return fstParIdent.getText().equals(CONSTRUCTOR_FST_PARAMETER)
				&& sndParIdent.getText().equals(CONSTRUCTOR_SND_PARAMETER);
	}

	return false;
}
 
Example #10
Source File: AnalysisComponentConstructorCheck.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * This method finds out whether the given class is an analysis component or
 * not (by searching for annotations with the names "Plugin" or
 * "Repository").
 *
 * @param clazz
 *            The class in question.
 *
 * @return true if and only if the class is an analysis component.
 */
private static boolean isAnalysisComponent(final DetailAST clazz) {
	// Get the list of modifiers as the annotations are within those
	final DetailAST modifiers = clazz.findFirstToken(TokenTypes.MODIFIERS);

	DetailAST modifier = modifiers.getFirstChild();

	// Run through the modifiers
	while (modifier != null) {
		// If we find an annotation we check the name
		if ((modifier.getType() == TokenTypes.ANNOTATION) && (modifier.findFirstToken(TokenTypes.IDENT) != null)) {
			final String annotationName = modifier.findFirstToken(TokenTypes.IDENT).getText();
			if (annotationName.equals(PLUGIN_ANNOTATION_NAME)
					|| annotationName.equals(REPOSITORY_ANNOTATION_NAME)) {
				// We found an annotation with the correct name
				return true;
			}
		}

		modifier = modifier.getNextSibling();
	}

	// Seems like there is no such annotation
	return false;
}
 
Example #11
Source File: DocumentNavigator.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Get a (single-member) iterator over this node's parent.
 *
 * @param aObject the context node for the parent axis.
 * @return A possibly-empty iterator (not null).
 */
public Iterator getParentAxisIterator(Object aObject)
{
    if (isAttribute(aObject)) {
        return new SingleObjectIterator(((Attribute) aObject).getParent());
    }
    else {
        DetailAST parent = ((DetailAST) aObject).getParent();
        if (parent != null) {
            return new SingleObjectIterator(parent);
        }
        else {
            return EMPTY_ITERATOR;
        }
    }
}
 
Example #12
Source File: SpringCatchCheck.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private void checkIdent(DetailAST ast) {
	String text = ast.getText();
	if (text.length() == 1) {
		log(ast.getLineNo(), ast.getColumnNo(), "catch.singleLetter");
	}
	if (text.toLowerCase().equals("o_o")) {
		log(ast.getLineNo(), ast.getColumnNo(), "catch.wideEye");
	}
}
 
Example #13
Source File: Attribute.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Constructs an <code>Attribute</code>.
 * @param aParent the parent element.
 * @param aName the name.
 * @param aValue the value.
 */
public Attribute(DetailAST aParent, String aName, String aValue)
{
    mParent = aParent;
    mName = aName;
    mValue = aValue;
}
 
Example #14
Source File: SpringTernaryCheck.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private void visitQuestion(DetailAST ast) {
	DetailAST expression = ast.getFirstChild();
	if (!hasType(expression, TokenTypes.LPAREN)) {
		if (expression != null && requiresParens(expression)) {
			log(ast.getLineNo(), ast.getColumnNo(), "ternary.missingParen");
		}
	}
	while (hasType(expression, TokenTypes.LPAREN)) {
		expression = expression.getNextSibling();
	}
	if (isSimpleEqualsExpression(expression) && !isEqualsTestAllowed(ast)) {
		log(ast.getLineNo(), ast.getColumnNo(), "ternary.equalOperator");
	}
}
 
Example #15
Source File: SpringJUnit5Check.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private void visitMethodDef(DetailAST ast) {
	if (AnnotationUtil.containsAnnotation(ast, TEST_ANNOTATIONS)) {
		this.testMethods.add(ast);
	}
	if (AnnotationUtil.containsAnnotation(ast, LIFECYCLE_ANNOTATIONS)) {
		this.lifecycleMethods.add(ast);
	}
}
 
Example #16
Source File: NodeIterator.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see java.util.Iterator#next() */
public Object next()
{
    if (mNode == null) {
        throw new NoSuchElementException();
    }
    final DetailAST ret = mNode;
    mNode = getNextNode(mNode);
    return ret;
}
 
Example #17
Source File: SymTabAST.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * initialized this node with input node
 * @param aAST the node to initialize from. Must be a
 * <code>DetailAST</code> object.
 */
public void initialize(AST aAST)
{
    if (aAST != null) {
        super.initialize(aAST);
        final DetailAST detailAST = (DetailAST) aAST;
        setDetailNode(detailAST);
        _column = detailAST.getColumnNo() + 1;
        _line = detailAST.getLineNo();
    } 
}
 
Example #18
Source File: UnusedParameterCheck.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Checks if a given method is local, i.e. either static or private.
 * @param aAST method def for check
 * @return true if a given method is iether static or private.
 */
private boolean isLocal(DetailAST aAST)
{
    if (aAST.getType() == TokenTypes.METHOD_DEF) {
        final DetailAST modifiers =
            aAST.findFirstToken(TokenTypes.MODIFIERS);
        return (modifiers == null)
            || modifiers.branchContains(TokenTypes.LITERAL_STATIC)
            || modifiers.branchContains(TokenTypes.LITERAL_PRIVATE);
    }
    return true;
}
 
Example #19
Source File: SymTabAST.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * initialized this node with input node
 * @param aAST the node to initialize from. Must be a
 * <code>DetailAST</code> object.
 */
public void initialize(AST aAST)
{
    if (aAST != null) {
        super.initialize(aAST);
        final DetailAST detailAST = (DetailAST) aAST;
        setDetailNode(detailAST);
        _column = detailAST.getColumnNo() + 1;
        _line = detailAST.getLineNo();
    } 
}
 
Example #20
Source File: SpringMethodOrderCheck.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private boolean isOrderedMethod(DetailAST ident, DetailAST parameters) {
	if ("equals".equals(ident.getText()) && parameters.getChildCount() == 1) {
		return true;
	}
	if ("hashCode".equals(ident.getText()) && parameters.getChildCount() == 0) {
		return true;
	}
	if ("toString".equals(ident.getText()) && parameters.getChildCount() == 0) {
		return true;
	}
	return false;
}
 
Example #21
Source File: SpringJUnit5Check.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void visitToken(DetailAST ast) {
	switch (ast.getType()) {
	case TokenTypes.METHOD_DEF:
		visitMethodDef(ast);
	case TokenTypes.IMPORT:
		visitImport(ast);
		break;
	}
}
 
Example #22
Source File: SpringHideUtilityClassConstructor.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private boolean isBypassed(DetailAST ast) {
	for (String bypassAnnotation : BYPASS_ANNOTATIONS) {
		if (AnnotationUtil.containsAnnotation(ast, bypassAnnotation)) {
			return true;
		}
	}
	return false;
}
 
Example #23
Source File: IdentCheckFilter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
@Override
public void visitToken(DetailAST ast) {
	if (ast.getType() == TokenTypes.IDENT && isFiltered(ast)) {
		return;
	}
	super.visitToken(ast);
}
 
Example #24
Source File: IdentCheckFilter.java    From spring-javaformat with Apache License 2.0 5 votes vote down vote up
private boolean isFiltered(DetailAST ast) {
	String name = ast.getText();
	if (this.names.contains(name)) {
		return true;
	}
	return false;
}
 
Example #25
Source File: SdkPublicMethodNameCheck.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void visitToken(DetailAST ast) {
    // Get class classDef
    DetailAST classDef = ast.getParent().getParent();

    try {
        if (!AnnotationUtil.containsAnnotation(ast, OVERRIDE)
            && AnnotationUtil.containsAnnotation(classDef, SDK_PUBLIC_API)) {
            super.visitToken(ast);
        }
    } catch (NullPointerException ex) {
        //If that method is in an anonymous class, it will throw NPE, ignoring those.
    }

}
 
Example #26
Source File: MissingSdkAnnotationCheck.java    From aws-sdk-java-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public void visitToken(DetailAST ast) {
    if (!ScopeUtil.isOuterMostType(ast) || SDK_ANNOTATIONS.stream().anyMatch(a -> AnnotationUtil.containsAnnotation
        (ast, a))) {
        return;
    }

    log(ast, "SDK annotation is missing on this class. eg: @SdkProtectedApi");
}
 
Example #27
Source File: MonitoringRecordFactoryConventionCheck.java    From kieker with Apache License 2.0 5 votes vote down vote up
/**
 * This method checks whether the given trees are more or less equal. This is
 * necessary as the available methods do not work as expected for this special
 * case.
 *
 * @param actual
 *            The actual tree.
 * @param expected
 *            The expected tree.
 *
 * @return true if and only if the trees are (more or less) equal.
 */
private static boolean treeCompare(final DetailAST actual, final DetailAST expected) {
	if ((actual != null) && (expected != null) && (actual.getType() == expected.getType())) {
		// If they are identifiers, we check the texts
		if ((actual.getType() == TokenTypes.IDENT) && (!actual.getText().equals(expected.getText()))) {
			return false;
		}

		// Everything fine so far. Check the equality of the children
		DetailAST actChild = actual.getFirstChild();
		DetailAST expChild = expected.getFirstChild();

		while (actChild != null) {
			// The treeCompare method checks whether one of the children is null (we
			// recognize therefore if the parents have different number of children).
			if (!MonitoringRecordFactoryConventionCheck.treeCompare(actChild, expChild)) {
				return false;
			}

			actChild = actChild.getNextSibling();
			expChild = expChild.getNextSibling();
		}

		// Everything seems to be fine - just make sure that expChild is null as well or
		// otherwise the parents had a different number of children
		return expChild == null;
	}

	return false;
}
 
Example #28
Source File: XPathCheck.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**  @see com.puppycrawl.tools.checkstyle.api.Check */
public void beginTree(DetailAST aAST)
{
    if (mXPath != null) {
        final ASTFactory factory = new ASTFactory();
        factory.setASTNodeType(DetailAST.class.getName());
        // TODO: Need to resolve if need a fake root node....
        final DetailAST root =
            (DetailAST) factory.create(TokenTypes.EOF, "ROOT");
        root.setFirstChild(aAST);
        try {
            final Iterator it = mXPath.selectNodes(aAST).iterator();
            while (it.hasNext()) {
                final DetailAST node = (DetailAST) it.next();
                log(
                    node.getLineNo(),
                    node.getColumnNo(),
                    mMessage,
                    new String[] {node.getText()});
            }
        }
        catch (JaxenException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
Example #29
Source File: NodeIterator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see java.util.Iterator#next() */
public Object next()
{
    if (mNode == null) {
        throw new NoSuchElementException();
    }
    final DetailAST ret = mNode;
    mNode = getNextNode(mNode);
    return ret;
}
 
Example #30
Source File: OneMethodPrivateFieldCheck.java    From contribution with GNU Lesser General Public License v2.1 5 votes vote down vote up
/** @see com.puppycrawl.tools.checkstyle.checks.usage.AbstractUsageCheck */
public boolean mustCheckReferenceCount(DetailAST aAST)
{
    final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS);
    return ((mods != null)
        && (ScopeUtils.getScopeFromMods(mods) == Scope.PRIVATE));
}