如何创建自定义 PMD 规则来检查 DSLContext 的实例是否在循环中开始引用?

How do I create a custom PMD rule to check if an instance of DSLContext is begin referenced in a loop?

我正在尝试创建自定义 PMD 规则,如果在循环中引用 org.jooq.DSLContext 的实例,该规则将导致违规。

我对 PMD 完全陌生,所以我不知道从哪里开始。

有人可以帮忙吗?

起点明确:https://pmd.github.io/latest/pmd_userdocs_extending_writing_rules_intro.html

对于具体问题,我建议创建一个基于 XPath 的规则。 您可以使用自定义 XPath 函数“pmd-java:typeIs”来检查特定类型。

例如要查找所有用法,您可以使用此查询:

//PrimaryPrefix[pmd-java:typeIs("org.jooq.DSLContext")]

为了在循环内限制查询,您可能需要这样写:

//(ForStatement | WhileStatement | DoStatement)
    //PrimaryPrefix[pmd-java:typeIs("org.jooq.DSLContext")]

注意:由于 PMD (https://github.com/pmd/pmd/pull/3499) 中的错误,此查询需要手动扩展,请参阅下面 XML 规则片段中的最终表达式。

完整的规则 XML 片段可能如下所示:

<rule name="DontReferenceDSLContextInLoops"
      language="java"
      message="Do not reference DSLContext in Loops"
      class="net.sourceforge.pmd.lang.rule.XPathRule" >
    <description>
TODO

Why is it bad to reference DSLContext?

What should you do instead?

Are there exceptions - when is it valid to suppress this violation?
    </description>
    <priority>3</priority>
    <properties>
        <property name="version" value="2.0"/>
        <property name="xpath">
            <value>
<![CDATA[
//ForStatement//PrimaryPrefix[pmd-java:typeIs("org.jooq.DSLContext")]
|
//WhileStatement//PrimaryPrefix[pmd-java:typeIs("org.jooq.DSLContext")]
|
//DoStatement//PrimaryPrefix[pmd-java:typeIs("org.jooq.DSLContext")]
]]>
            </value>
        </property>
    </properties>
</rule>