<?xml version="1.0"?>
<ruleset name="PMD ruleset for Checkstyle"
        xmlns="http://pmd.sourceforge.net/ruleset/2.0.0"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://pmd.sourceforge.net/ruleset/2.0.0
                            http://pmd.sourceforge.net/ruleset_2_0_0.xsd">
  <description>
    PMD common ruleset for Checkstyle main/test sourcesets
  </description>

  <rule ref="category/java/bestpractices.xml">
    <!-- We do not care about this minor overhead, we are not Android application and we do not
         want to change visibility of methods. Package-private visibility should be avoid almost
         always. -->
    <exclude name="AccessorMethodGeneration"/>
    <!-- The PMD mistakes the AbstractViolationReporter::log() as a debug log. -->
    <exclude name="GuardLogStatement"/>
    <!-- too much false-positives from 6.18.0 -->
    <exclude name="UnusedPrivateMethod"/>
  </rule>
  <rule ref="category/java/bestpractices.xml/AvoidPrintStackTrace">
    <properties>
      <!-- It is ok to use print stack trace in CLI class. -->
      <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='Main']"/>
    </properties>
  </rule>
  <rule ref="category/java/bestpractices.xml/JUnitAssertionsShouldIncludeMessage">
    <properties>
      <!-- The PMD check accepts only a string constant as the assert message.
           This check uses a method call. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='JavadocCatchCheck']
                           //MethodDeclaration[@Name='visitJavadocToken']"/>
    </properties>
  </rule>
  <rule ref="category/java/bestpractices.xml/SystemPrintln">
    <properties>
      <!-- it is ok to use println in CLI class. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration
                       [@Image='Main' or @Image='Main$CliOptions'
                       or @Image='JavadocPropertiesGenerator']"/>
    </properties>
  </rule>

  <rule ref="category/java/documentation.xml">
    <!-- We use class comments as source for xdoc files,
         so content is big and that is by design. -->
    <exclude name="CommentSize"/>
  </rule>
  <rule ref="category/java/documentation.xml/CommentRequired">
    <properties>
      <!-- RequireThisCheck$AbstractFrame is a private class, no comment is required. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='RequireThisCheck']"/>
    </properties>
  </rule>

  <rule ref="category/java/codestyle.xml">
    <!-- Opposite to UnnecessaryConstructor. -->
    <exclude name="AtLeastOneConstructor"/>
    <!-- Turning a local variable to the field may create design problems and extend the scope of
           the variable. -->
    <exclude name="AvoidFinalLocalVariable"/>
    <!-- Conflicts with names that does not mean in/out. -->
    <exclude name="AvoidPrefixingMethodParameters"/>
    <!-- Calling super() is completely pointless, no matter if class inherits anything or not;
         it is meaningful only if you do not call implicit constructor of the base class. -->
    <exclude name="CallSuperInConstructor"/>
    <!-- Pollutes code with modifiers. -->
    <exclude name="LocalVariableCouldBeFinal"/>
    <!-- Pollutes the code with modifiers. We use the ParameterAssignmentCheck to protect the
         parameters. -->
    <exclude name="MethodArgumentCouldBeFinal"/>
    <!-- It is possible only in functional languages and fanatically-pristine code, without
         additional option that are done at ReturnCountExtendedCheck it is not a good rule. -->
    <exclude name="OnlyOneReturn"/>
    <!-- it is not easily configurable we use our Check to cover our needs -->
    <exclude name="ShortVariable"/>
    <!-- huge amount of false positives from 6.18.0 -->
    <exclude name="UnnecessaryFullyQualifiedName"/>
  </rule>
  <rule ref="category/java/codestyle.xml/ClassNamingConventions">
    <properties>
     <property name="classPattern" value="[A-Z][a-zA-Z0-9]*" />
     <property name="abstractClassPattern" value="Abstract[A-Z][a-zA-Z0-9]*" />
     <property name="interfacePattern" value="[A-Z][a-zA-Z0-9]*" />
     <property name="enumPattern" value="[A-Z][a-zA-Z0-9]*" />
     <property name="annotationPattern" value="[A-Z][a-zA-Z0-9]*" />
     <property name="utilityClassPattern" value="[A-Z][a-zA-Z0-9]*Util" />
     <!-- We can not brake compatibility with previous versions. -->
     <property name="violationSuppressXPath"
               value="//ClassOrInterfaceDeclaration
                          [@Image='AbstractClassNameCheck' or @Image='AutomaticBean']"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/ClassNamingConventions">
    <properties>
     <!-- Definitions and XmlLoader.LoadExternalDtdFeatureProvider aren't utility classes.
          JavadocTokenTypes and TokenTypes aren't utility classes.
            They are token definition classes. Also, they are part of the API. -->
     <property name="violationSuppressXPath"
               value="//ClassOrInterfaceDeclaration[@Image='Definitions'
                   or @Image='JavadocTokenTypes' or @Image='TokenTypes'
                   or @Image='LoadExternalDtdFeatureProvider']"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/ConfusingTernary">
    <properties>
      <!-- False positives on IF_ELSE-IF-ELSE-IF. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='XMLLogger']
                           //MethodDeclaration[@Name='isReference']
      | //ClassOrInterfaceDeclaration[@Image='DetailAstImpl']
              //MethodDeclaration[@Name='addPreviousSibling']
      | //ClassOrInterfaceDeclaration[@Image='AnnotationLocationCheck']
              //MethodDeclaration[@Name='checkAnnotations']
      | //ClassOrInterfaceDeclaration[@Image='AbstractImportControl']
              //MethodDeclaration[@Name='checkAccess']
      | //ClassOrInterfaceDeclaration[@Image='HandlerFactory']
              //MethodDeclaration[@Name='getHandler']"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/EmptyMethodInAbstractClassShouldBeAbstract">
    <properties>
      <!-- Can not change the API. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='AbstractFileSetCheck'
        or @Image='AbstractCheck' or @Image='AbstractJavadocCheck' or @Image='AbstractNode'
        or @Image='AbstractViolationReporter']"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/UseUnderscoresInNumericLiterals">
    <properties>
      <!-- Numbers up to 6 digits are easy to read without underscores. -->
      <property name="acceptableDecimalLength" value="6"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/LongVariable">
    <properties>
      <!-- Nothing bad with the long and descriptive variable names if only they fit the line,
           but still keep it reasonable. -->
      <property name="minimum" value="45"/>
    </properties>
  </rule>
  <rule ref="category/java/codestyle.xml/ShortClassName">
    <properties>
      <!-- Main is a good name for the class containing the main method.
           Tag as inner class name is fine. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='Main' or @Image='Tag']"/>
    </properties>
  </rule>
  <rule ref="category/java/errorprone.xml">
    <!-- That rule is not practical, no options to allow some magic numbers,
         we will use our implementation. -->
    <exclude name="AvoidLiteralsInIfCondition"/>
    <!-- It is not our goal for now to keep all Serializable, maybe in the future. -->
    <exclude name="BeanMembersShouldSerialize"/>
    <!-- We need compare by ref as Tree structure is immutable, we can easily
         rely on refs. -->
    <exclude name="CompareObjectsWithEquals"/>
    <!-- Too many false positives. -->
    <exclude name="DataflowAnomalyAnalysis"/>
    <!-- This rule does not have any option, unreasonable to use. -->
    <exclude name="MissingBreakInSwitch"/>
    <!-- We reuse Check instances between java files, we need to clear state of
         class in beginTree() methods. -->
    <exclude name="NullAssignment"/>
    <!-- We cannot change the class loader because it breaks the build.
         See https://github.com/checkstyle/checkstyle/issues/5680 for details. -->
    <exclude name="UseProperClassLoader"/>
    <!-- Demand for static modifier is not correct for library projects.
         It is valid only for application projects -->
    <exclude name="ProperLogger" />
  </rule>
  <rule ref="category/java/errorprone.xml/AvoidDuplicateLiterals">
    <properties>
      <!-- Annotations like '@SuppressWarnings' don't need to be checked, it is better to keep their
             strings connected to the annotation instead of separating. -->
      <property name="skipAnnotations" value="true"/>
    </properties>
  </rule>
  <rule ref="category/java/errorprone.xml/EmptyCatchBlock">
    <properties>
      <property name="allowCommentedBlocks" value="true"/>
    </properties>
  </rule>
  <rule ref="category/java/errorprone.xml/DoNotCallSystemExit">
    <properties>
      <!-- There is no alternative to using System.exit in the CLI class
           to report the return code. -->
      <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='Main']"/>
    </properties>
  </rule>

  <rule ref="category/java/design.xml">
    <!-- Too much false-positives on the check classes.
         We do not follow the philosophy of complete encapsulation, we like data classes
         (preferable immutable) to transfer content from one part to another.
         There is no way to configure the rule (it has no properties). -->
    <exclude name="DataClass"/>
    <!-- Too much alarms on the check classes, we will never move logic out of the check,
         each check is an independent logic container. -->
    <exclude name="GodClass"/>
    <!-- Too many violations, will be suppressed until we find out how use these metrics. -->
    <exclude name="LawOfDemeter"/>
    <!-- We use our ImportControl to control imports in packages and classes. -->
    <exclude name="LoosePackageCoupling"/>
  </rule>
  <rule ref="category/java/design.xml/AvoidCatchingGenericException">
    <properties>
      <!-- Checker: There is no other way to deliver the filename that was under processing.
           See https://github.com/checkstyle/checkstyle/issues/2285
           TranslationCheck: It is better to catch all exceptions since it can throw
           a runtime exception.
           JavadocMethodCheck: Exception type is not predictable. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='Checker']
                             //MethodDeclaration[@Name='processFiles']
                      |//ClassOrInterfaceDeclaration[@Image='TranslationCheck']
                             //MethodDeclaration[@Name='getTranslationKeys']
                      |//ClassOrInterfaceDeclaration[@Image='JavadocMethodCheck']
                             //MethodDeclaration[@Name='resolveClass']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/AvoidDeeplyNestedIfStmts">
    <properties>
      <!-- The default is 3 but we try to use single point of exit from the method and that require
           some extra IFs. -->
      <property name="problemDepth" value="4"/>
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='ClassResolver']
                             //MethodDeclaration[@Name='resolve']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/AvoidThrowingRawExceptionTypes">
    <properties>
      <!-- There is no other way to deliver the filename that was under processing.
           See https://github.com/checkstyle/checkstyle/issues/2285 -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='Checker']
                             //MethodDeclaration[@Name='processFiles']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/CouplingBetweenObjects">
    <properties>
      <!-- I do not see any problem, looks like a false positive. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='HandlerFactory']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/NcssCount">
    <properties>
      <property name="methodReportLevel" value="32"/>
      <!-- Main, PackageObjectFactory, RequireThisCheck, HandlerFactory,
             VariableDeclarationUsageDistanceCheck,
             are big and should not be split without a good reason.
           The methods visitToken/leaveToken are a big SWITCH block with a number of IF blocks.
             If we split the block to several methods it will damage the readability.
           XMLLogger.encode, FallThroughCheck.isTerminated, ElementNode.iterateAxis,
             NoWhitespaceAfterCheck.getArrayDeclaratorPreviousElement are also huge switches,
             they has to be monolithic.
           SuppressFilterElement is a single constructor and can't be split easily -->
      <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='Main'
        or @Image='PackageObjectFactory' or @Image='RequireThisCheck'
        or @Image='VariableDeclarationUsageDistanceCheck'
        or @Image='HandlerFactory']
      | //ClassOrInterfaceDeclaration[@Image='XMLLogger']//MethodDeclaration[@Name='encode']
      | //ClassOrInterfaceDeclaration[@Image='LeftCurlyCheck' or @Image='FinalLocalVariableCheck'
        or @Image='NPathComplexityCheck']
             //MethodDeclaration[@Name='visitToken']
      | //ClassOrInterfaceDeclaration[@Image='FallThroughCheck']
             //MethodDeclaration[@Name='isTerminated']
      | //ClassOrInterfaceDeclaration[@Image='ModifiedControlVariableCheck'
        or @Image='NPathComplexityCheck']//MethodDeclaration[@Name='leaveToken']
      | //ClassOrInterfaceDeclaration[@Image='NoWhitespaceAfterCheck']
             //MethodDeclaration[@Name='getArrayDeclaratorPreviousElement']
      | //ClassOrInterfaceDeclaration[@Image='ElementNode' or @Image='RootNode']
             //MethodDeclaration[@Name='iterateAxis']
      | //ClassOrInterfaceDeclaration[@Image='SuppressFilterElement']
             //ConstructorDeclaration
      "/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/CyclomaticComplexity">
    <properties>
      <property name="classReportLevel" value="75"/>
      <property name="methodReportLevel" value="11"/>
      <!-- RequireThisCheck, VariableDeclarationUsageDistanceCheck, XdocsPagesTest,
             JavadocMethodCheck and CommentsIndentationCheck are big classes and should not
             be split without a good reason.
           Main.validateCli is not reasonable to split as encapsulation of the logic will be
             damaged.
           *.visitToken are a big SWITCH block with a number of IF blocks.
             If we split the block to several methods it will damage the readability.
           JavadocStyleCheck is deprecated.
           SuppressWarningsHolder.getAcceptableParent, FallThroughCheck.isTerminated,
             ElementNode.iterateAxis, RootNode.iterateAxis are also huge switches,
             they has to be monolithic.
           CustomImportOrderCheck.finishImportList, CustomImportOrderCheck.getImportGroup are
             validated by checkstyle version of Npath, we think that pmd is wrong here.
           Checker.processFiles is validated by checkstyle version of Npath, we think that pmd is
             wrong here.
           CommonUtil is clearly designed for a large number of small methods for common use.
           XdocsJavaDocsTest.testAllCheckSectionJavaDocs is needed until all suppressions are
             removed. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='RequireThisCheck'
      or @Image='VariableDeclarationUsageDistanceCheck' or @Image='XdocsPagesTest'
      or @Image='JavadocMethodCheck' or @Image='CommentsIndentationCheck' or @Image='CommonUtil']
    | //ClassOrInterfaceDeclaration[@Image='Main']//MethodDeclaration[@Name='validateCli']
    | //ClassOrInterfaceDeclaration[@Image='Checker']//MethodDeclaration[@Name='processFiles']
    | //ClassOrInterfaceDeclaration[@Image='FallThroughCheck']
          //MethodDeclaration[@Name='isTerminated']
    | //ClassOrInterfaceDeclaration[@Image='SuppressWarningsHolder']
          //MethodDeclaration[@Name='getAcceptableParent']
    | //ClassOrInterfaceDeclaration[@Image='CustomImportOrderCheck']
          //MethodDeclaration[@Name='finishImportList' or @Name='getImportGroup']
    | //ClassOrInterfaceDeclaration[@Image='JavadocStyleCheck']
          //MethodDeclaration[@Name='checkHtmlTags']
    | //ClassOrInterfaceDeclaration[@Image='ElementNode' or @Image='RootNode']
          //MethodDeclaration[@Name='iterateAxis']
    | //ClassOrInterfaceDeclaration[@Image='NPathComplexityCheck'
      or @Image='EmptyLineSeparatorCheck' or @Image='LeftCurlyCheck'
      or @Image='DeclarationOrderCheck' or @Image='MissingOverrideCheck'
      or @Image='FinalLocalVariableCheck' or @Image='ModifiedControlVariableCheck'
      or @Image='ParameterAssignmentCheck' or @Image='UnnecessaryParenthesesCheck'
      or @Image='AbstractClassCouplingCheck' or @Image='BooleanExpressionComplexityCheck'
      or @Image='ParenPadCheck' or @Image='IllegalTypeCheck']//MethodDeclaration[@Name='visitToken']
    | //ClassOrInterfaceDeclaration[@Image='XdocsJavaDocsTest']
          //MethodDeclaration[@Name='testAllCheckSectionJavaDocs']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/TooManyFields">
    <properties>
      <!-- Unable to split fields out of the class. -->
      <!-- Main has an annotated field for each command line option. This is by design. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='Checker']
    | //ClassOrInterfaceDeclaration[@Image='Main']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/ImmutableField">
    <properties>
      <!-- Main has annotated fields whose value is injected by picocli.
        These fields should not be marked final. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='Main']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/TooManyMethods">
    <properties>
      <property name="maxmethods" value="20"/>
      <!-- The class PackageObjectFactory has many boilerplate methods.
           JavadocMethodCheck is in the process of being rewritten. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='PackageObjectFactory']
          |//ClassOrInterfaceDeclaration[@Image='JavadocMethodCheck']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/ExcessiveClassLength">
    <properties>
      <!-- *TokenTypes are special classes that are big due to a lot of description comments.
           RequireThisCheck has to work with and identify many frames.
           JavadocMethodCheck is in the process of being rewritten. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='JavadocTokenTypes'
        or @Image='TokenTypes' or @Image='RequireThisCheck' or @Image='JavadocMethodCheck']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/ExcessiveParameterList">
    <properties>
      <!-- The class LocalizedMessage has a constructor with many parameters by design. -->
      <property name="violationSuppressXPath"
                value="//ClassOrInterfaceDeclaration[@Image='LocalizedMessage']"/>
    </properties>
  </rule>
  <rule ref="category/java/design.xml/ExcessiveImports">
    <properties>
      <!-- Main actively uses Checkstyle, logging and command line parsing API.
           Checker collects external resource locations and sets up the configuration.
           CheckstyleAntTask integrates Checkstyle with Ant.
            -->
      <property name="violationSuppressXPath" value="//ClassOrInterfaceDeclaration[@Image='Main'
        or @Image='Checker' or @Image='CheckstyleAntTask']"/>
    </properties>
  </rule>

  <rule ref="category/java/multithreading.xml">
    <!-- Checkstyle is not thread safe till https://github.com/checkstyle/checkstyle/projects/5. -->
    <exclude name="UseConcurrentHashMap"/>
  </rule>
  <rule ref="category/java/multithreading.xml/AvoidSynchronizedAtMethodLevel">
    <properties>
      <!-- UniqueProperties#put and OrderedProperties#keys
      overloads a synchronized method, so it should have synchronized
      modifier. -->
      <property name="violationSuppressXPath"
        value="//ClassOrInterfaceDeclaration[@Image='UniqueProperties'
          or @Image='SequencedProperties']//MethodDeclaration[@Name='keys' or @Name='put']"/>
    </properties>
  </rule>

  <rule ref="category/java/performance.xml">
    <!-- Produces more false positives than real problems. -->
    <exclude name="AvoidInstantiatingObjectsInLoops"/>
    <!-- Not configurable, decreases readability. -->
    <exclude name="UseStringBufferForStringAppends"/>
  </rule>
</ruleset>
