I want to create a PMD rule to forbid usage of labeled statements
Sadly I could not find a common XPath for such statements.
I need a XPath query which finds
//LabeledStatement for the labels itself
and for the ContinueStatement and BreakStatement i would need a possiblity to check if a label is defined there. From the PMD Rule builder (XPath builder) the labels are defined as:
BreakStatement:loop (loop is the defined label name and could be anything)
ContinueStatement:loop (loop is the defined label name and could be anything)
can someone give me a hint what XPath I should define?
You are on a very good track. Using the rule designer is a great way to figure this one out, specially since PMD 6.0.0 which revamped the GUI.
As you figured, //LabeledStatement
will match all labels (which you don't want), and //BreakStatement
and //ContinueStatement
will flag all break / continues, which you only want to flag if they are followed by a tag.
Therefore, you simply need to check if those have a tag set or not. Using the designer to inspect properties of those AST nodes makes it easy to figure it out, the attribute where the label is stored is the Image
, which is null when none is defined. As XPath stringifies all attributes, a null value is an empty string.
Therefore:
//LabeledStatement | //BreakStatement[@Image != ""] | //ContinueStatement[@Image != ""]
Will match: