Custom Checkstyle Check Nesting Isssue

90 Views Asked by At

I am trying to create a custom Checkstyle check that enforces a rule in Java that after an opening curly brace there is a new blank line. I have tried a couple approaches but the issue I keep running into is that my check only applies to whatever the top level of code is.

For example in a Java file it only enforces the rule on classes but not methods themselves are inside them.

I have tried two main approaches to writing the check by either checking for the line by going through all the curly brace tokens, or an approach where you look at the entire file contents and check line number similar to this Github issue, https://github.com/checkstyle/checkstyle/pull/11525/files.

In either case I am extending the puppycrawl Checkstyle tools and using the visitToken method for the implementation. Then in the checkstyle.xml I am adding my check into the TreeWalker module of the Checker module. Also as a note I am trying to use this check in the Intellij Checkstyle plugin.

1

There are 1 best solutions below

0
mlebedy On

I think the LeftCurly check is the closest implementation of your intention.

I would start by creating a new checker (what you've already done) based on the LeftCurlyCheck code and modifying the verifyBrace method.

There you can get the line after the left curly bracket (e.g. String lineAfterBrace = getLine(brace.getLineNo());) and check if it is empty or not.

(Or you can extend the original LeftCurly check with an option to verify if the next line is blank)